def signup_user(): # get body of request; if nothing included, abort with 400 body = request.get_json() if not body: abort(400) # set attributes for new User based on body input username = body.get('username', None) usertype = body.get('usertype', None) email = body.get('email', None) password = body.get('password', None) # proceed only if both required fields are provided if username and usertype: # First, check to see if username is already being used in local bd, and abort with 409 (conflict) if so if Mentor.exists(username) or Coder.exists(username): abort(409) # Then, try to add new user to auth0 database: url = f'https://{AUTH0_DOMAIN}/dbconnections/signup' post_object = { "client_id": AUTH0_CLIENT_ID, "email": email, "password": password, "connection": AUTH0_CONNECTION, "username": username, "user_metadata": { "role": usertype.title() } } auth0_response = requests.post(url, json=post_object) # If there was a problem with auth0 process, abort: if hasattr(auth0_response, 'error'): abort(401) # Finally, if auth0 signup orcess successful, # insert user into local database: # instantiate a new object for the new user if usertype == 'mentor': user = Mentor(username=username) if usertype == 'coder': user = Coder(username=username) # try to add the new user to the applicable table in the database try: user.insert() except: abort(500) # if required fields weren't provided in the request, abort with 400 else: abort(400) return jsonify({"success": "True", "user_id": user.id})
def mentors(): if request.method == 'GET': return {'mentors': [mentor_dict for mentor_dict in Mentor.select().dicts()]} mentor_data = request.form if request.method == 'POST': try: Mentor.insert(mentor_data).execute() return 'Success' except IntegrityError: return 'Mentor exists (email)', 409
def get_mentor_by_uid(): uid = g.uid if request.method == 'GET': try: user = Users.select(Users.mentor_id).where(Users.uid == uid).get() return {'mentors': Mentor.select().where(Mentor.id == user.mentor_id).dicts().get()} except DoesNotExist: return {'mentors': []} elif request.method == 'PUT': mentor_data = request.json try: user = Users.select(Users.mentor_id).where(Users.uid == uid).get() Mentor.select().where(Mentor.id == user.mentor_id).dicts().get() exists = True except DoesNotExist: exists = False try: if exists: updated = Mentor.update(mentor_data).where(Mentor.id == user.mentor_id).execute() updated_user = Users.update(mentor_id=updated).where(Users.uid == uid).execute() else: updated = Mentor.insert(mentor_data).execute() updated_user = Users.insert(uid=uid, mentor_id=updated, is_manager=False, is_admin=False).execute() except Exception as e: return f'Failed with error: {e}', 409 return 'Success' if updated else 'Non updated'