def users(): ''' For GET requests, return all users. For POST requests, add a new user. ''' if request.method == 'GET': all_users = User.query.all() schema = UserSchema(many=True, strict=True) users = schema.dump(all_users) return jsonify(users[0]) # request is a POST else: username = request.form.get('Username') role = request.form.get('Role') role = Role.query.filter_by(name=role).first() user = User.query.filter_by(username=username).first() if user is not None: return json.dumps({'success': False}), 200, { 'ContentType': 'application/json' } elif role is None: return 'failed to enter into database - role doesnt exist', 400 user = User(username=username, role_id=role.id) user.set_password(request.form.get('Password')) db.session.add(user) db.session.commit() schema = UserSchema(strict=True) user_data = schema.dump(user) return jsonify(user_data[0]), 201
def GetUser(request): print(current_user.get_id()) userdetails = User.query.filter_by(id=current_user.get_id()).first() schema = UserSchema() pprint(schema.dump(userdetails).data) user_details = schema.dump(userdetails).data if request == None: return user_details return jsonify(user_details)
def user(user_id): ''' For GET requests, return the given user. For DELETE requests, delete the given user. ''' user = User.query.filter_by(id=user_id).first() if user is None: return 'user does not exist', 404 # request is a GET if request.method == 'GET': schema = UserSchema(strict=True) user_data = schema.dump(user) return jsonify(user_data) # request is a DELETE elif request.method == 'DELETE': if current_user == user: return json.dumps({'success': False}), 200, { 'ContentType': 'application/json' } db.session.delete(user) db.session.commit() return json.dumps({'success': True}), 200, { 'ContentType': 'application/json' }
def read_all(active_only=False): query = User.query if active_only: query = query.filter(User.is_active == True) users = query.all() user_schema = UserSchema(many=True) return user_schema.dump(users)
def profiles(): '''render webpage profiles''' users = db.session.query(User).all() if request.method == "POST": serializer = UserSchema(many=True) result = serializer.dump(users) return jsonify({'Users': result.data}) return render_template('profile.html', users=users)
def on_get(self, req, res): session = req.context['session'] users = session.query(User).all() schema = UserSchema() out = [] for u in users: out.append(schema.dump(u).data) res.status = falcon.HTTP_200 res.body = self.to_json(out)
class UserController(MethodView): def __init__(self): self.service = UserService() self.schema = UserSchema() self.many_schema = UserSchema(many=True) def get(self, user_id): res = None serialized = None if user_id is None: res = self.service.get_all_users() serialized = self.many_schema.dump(res) else: res = self.service.get_user_by_id(user_id) serialized = self.schema.dump(res) return jsonify({'user': serialized}), 200 def post(self): password = request.json['password'] encrypted_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) user = User( email=request.json['email'], password=encrypted_password) self.service.save_user(user) serialized = self.schema.dump(user) return jsonify({'user': serialized}), 201 def put(self, user_id): user = self.service.update_user_by_id(user_id, request.json['user']) serialized = self.schema.dump(user) return jsonify({'user': serialized}), 200 def delete(self, user_id): self.service.delete_user_by_id(user_id) return jsonify({}), 204
def get_one_user(public_id): """ This route gets a single user from the database and returns it as a json object. Args {string} public_id Returns {Object<json>} 200 success: {string} user: {Object<json>} Throws {Exception{Object<json>}} error: NoResultFound 404 SQLAlchemyError 400 NotAuthorized 401 """ # Get the user's id from access token uid = get_jwt_identity() # If user's public_id doesn't equal public id in url, return error if user.public_id != public_id: return jsonify({'error': 'Not authorized!'}), 401 # Try to get user from database query = User.query.filter_by(public_id=uid) try: user = query.one() # If no result found, return error except NoResultFound: return jsonify({'error': 'No result found!'}), 404 # If some other sqlalchemy error is thrown, return error except SQLAlchemyError: return jsonify({'error': 'Some problem occurred!'}), 400 # Serialze the user object and return json response user_schema = UserSchema() output = user_schema.dump(user).data return jsonify({ 'success': 'Successfully retrieved user.', 'user': output }), 200
def get_all_users(): """ This route gets all users from the database and returns the array as a json object. Returns {Object<json>} 200 num_results: {string} success: {string} users: {Object<json>} Throws {Exception{Object<json>}} error: NoResultFound 404 SQLAlchemyError 400 """ # Try to get all users from database query = User.query try: users = query.all() # If query returns no users, return erorr if len(users) == 0: return jsonify({'error': 'No results found!'}), 404 # If no result found, return error except NoResultFound: return jsonify({'error': 'No result found!'}), 404 # If some other sqlalchemy error is thrown, return error except SQLAlchemyError: return jsonify({'error': 'Some problem occurred!'}), 400 # Serialize array of users user_schema = UserSchema(many=True) output = user_schema.dump(users).data # Return json response return jsonify({ 'num_results': str(len(output)), 'success': 'Successfully retrieved users!', 'users': output, }), 200
def on_post(self, req, res): """ Create a new user. Will test the data passed to the resource. """ session = req.context['session'] data = json.loads(req.bounded_stream.read().decode()) result = UserSchema().load(data) if result.errors: res.status = falcon.HTTP_BAD_REQUEST res.body = self.to_json({'errors': result.errors}) else: roles = get_roles() user = User(email=data['email'], fn=data['fn'], ln=data['ln'], password=hash_password(data['password']), role=roles['member']) session.add(user) session.flush() schema = UserSchema() res.status = falcon.HTTP_200 res.body = self.to_json(schema.dump(user).data)
def edit_user(id): """ This route edits a user in the database and returns the updated user aa a json object. Returns {Object<json>} 200 success: {string} user: {Object<json>} Throws {Exception{Object<json>}} error: NotAuthorized 401 ExpiredSignatureError 400 DecodeJWTError 400 NoResultFound 404 SQLAlchemyError 400 """ auth = {} # Get the user data from the request data = request.get_json() # If there is no authorization header, get # the user's id from the access token cookie if not request.headers.get('Authorization'): public_id = get_jwt_identity() # If user's id doesn't match url id, return error if public_id != id: return jsonify({'error': 'Not authorized!'}), 401 # If basic authorization, get the user's # id from the authorization username elif request.authorization: auth = request.authorization # If authorization credentials missing, return error if not auth or not auth.username or not auth.password: return make_response( jsonify({'error': 'Could not verify'}), 401, {'WWW-Authentication': 'Basic realm="Login required!"'}) public_id = auth.username # If the user's public id doesn't match url id, return error if public_id != id: return jsonify({'error': 'Not authorized!'}), 401 else: # Get the user's token from the authorization header token = request.headers.get('Authorization').split(' ')[1] # If there is no token, return error if not token: return jsonify({'error': 'Missing token!'}), 401 token = token.encode("utf-8") # Decode the jwt token try: jwt_data = jwt.decode(token, app.config.get('SECRET_KEY'), algorithm='HS256') # If the token has expired, return error except jwt.ExpiredSignatureError: # Signature has expired return jsonify( {'error': 'Reset token is expired. Please try again.'}), 400 # If failed to decode jwt, return error if not jwt_data: return jsonify({'error': 'Failed to decode jwt token.'}), 400 # Get the user's id from the decoded jwt public_id = jwt_data['public_id'] # If the user's id doesn't match the url id, return error if public_id != id: return jsonify({'error': 'Not authorized!'}), 401 # Try to get the user from the database query = User.query.filter_by(public_id=public_id) try: user = query.one() # If no result found, return error except NoResultFound: return jsonify({'error': 'No result found!'}), 404 # If some other sqlalchemy error is thrown, return error except SQLAlchemyError: return jsonify({'error': 'Some problem occurred!'}), 400 # If password provided but can't be verified, return error if 'password' in auth: if not check_password_hash(user.password, auth.password + user.salt): return jsonify({ 'error': ('The password you provided could ' 'not be found for this user.') }), 401 # If new password provided, create salt and hash it if 'password' in data: random_bytes = urandom(24) salt = b64encode(random_bytes).decode('utf-8') salted_password = data['password'] + salt hashed_password = generate_password_hash(salted_password, method='pbkdf2:sha512:80000', salt_length=20) user.password = hashed_password user.salt = salt # If other user attributes provided, add # them to user and save in database if 'name' in data: user.name = data['name'] if 'username' in data: user.username = data['username'] if 'email' in data: user.email = data['email'] if 'picture' in data: user.picture = data['picture'] db.session.commit() # Serialize user user_schema = UserSchema() output = user_schema.dump(user).data # Create json and return response return jsonify({'success': 'The user has been updated', 'user': output})
def create_user(): """ This route adds a new user to the database, sends a confirmation link to the user's email and returns a success message aa a json object. Returns {Object<json>} 200 success: {string} Throws {Exception{Object<json>}} error: NotAuthorized 401 NoResultFound 404 SQLAlchemyError 400 """ # Get user's authorization credentials auth = request.authorization # If no authorization credentials, return error if not auth or not auth.username or not auth.password: return make_response( jsonify({'error': 'Could not verify!'}), 401, {'WWW-Authentication': 'Basic realm="Login required!"'}) # Get user data from request data = request.get_json() # If name or email is missing, return error if not data['name'] or not data['email']: return make_response(jsonify({'error': 'Missing data!'}), 400) # Create a salted password random_bytes = urandom(24) salt = b64encode(random_bytes).decode('utf-8') salted_password = auth['password'] + salt # Hash the salted password hashed_password = generate_password_hash(salted_password, method='pbkdf2:sha512:80000', salt_length=20) # Create user object user = User(name=data['name'], email=data['email'], username=auth['username'], password=hashed_password, salt=salt, created_at=datetime.utcnow()) user.generate_public_id() # Try to add user to database try: db.session.add(user) db.session.commit() # If username already in database, return error except IntegrityError: return jsonify({'error': 'User with name or email already exists'}), 400 # If some other sqlalchemy error is thrown, return error except SQLAlchemyError: return jsonify({'error': 'Some problem occurred!'}), 400 # Serialize the user object user_schema = UserSchema() output = user_schema.dump(user).data # Create the tokens to be sent to the user expires = timedelta(seconds=1800) access_token = create_access_token(identity=user.public_id, expires_delta=expires) refresh_token = create_refresh_token(identity=user.public_id) # Get the csrf tokens so they can be set as headers in response csrf_access_token = get_csrf_token(access_token) csrf_refresh_token = get_csrf_token(refresh_token) # Create json response response = make_response( jsonify({ 'user': output, 'success': 'Login successful!' }), 200) # Set JWT cookies and headers and return response set_access_cookies(response, access_token) set_refresh_cookies(response, refresh_token) response.set_cookie('public_id', user.public_id) response.headers['access'] = csrf_access_token response.headers['refresh'] = csrf_refresh_token return response
def login(): """ This route authenticates the user by checking the username and password if it exists or by decoding the jwt token if it exists. Each time a user logs in new jwt tokens cookies will be set in the response. Returns {Object<json>} 200 success: {string} user: {Object<json>} Throws {Exception{Object<json}}: error: NoResultFound 401 SQLAlchemyError 400 InactiveUser 400 """ # If authorization header is present, try to authenticate the user if request.authorization: auth = request.authorization # If not username and password, return error if not auth.username or not auth.password: return not_authorized_error('Basic') # Find the user by username query = User.query.filter_by(username=auth.username) try: user = query.one() # If no user found, try by email or return error except NoResultFound: # Try to find the user by email query = User.query.filter_by(email=auth.username) try: user = query.one() # If no user found, try by email or return error except NoResultFound: return make_response( jsonify({ 'error': ('Sorry, your username or password was ' 'incorrect. Please try again.') }), 401, {'WWW-Authentication': 'Basic realm="Login required!"'}) # If some other sqlalchemy error is thrown, return error except SQLAlchemyError: return jsonify({'error': 'Some problem occurred!'}), 400 # If some other sqlalchemy error is thrown, return error except SQLAlchemyError: return jsonify({'error': 'Some problem occurred!'}), 400 # If provided password does not match user password, return error if not check_password_hash(user.password, auth.password + user.salt): return make_response( jsonify({ 'error': ('Sorry, your username or password was ' 'incorrect. Please try again.') }), 401, {'WWW-Authentication': 'Basic realm="Login required!"'}) # Serialize the user object user_schema = UserSchema() output = user_schema.dump(user).data # Create the tokens to be sent to the user expires = timedelta(seconds=1800) access_token = create_access_token(identity=user.public_id, expires_delta=expires) refresh_token = create_refresh_token(identity=user.public_id) # Get the csrf tokens so they can be set as headers in response csrf_access_token = get_csrf_token(access_token) csrf_refresh_token = get_csrf_token(refresh_token) # Create json response response = make_response( jsonify({ 'user': output, 'success': 'Login successful!' }), 200) # Set JWT cookies and headers and return response set_access_cookies(response, access_token) set_refresh_cookies(response, refresh_token) response.set_cookie('public_id', user.public_id) response.headers['access'] = csrf_access_token response.headers['refresh'] = csrf_refresh_token return response # If no authorization header present, check for jwt token cookies else: public_id = get_jwt_identity() # If there isn't a valid jwt token, return error if not public_id: return not_authorized_error('Cookie') # Find the user query = User.query.filter_by(public_id=public_id) try: user = query.first() # If no user found, return error except NoResultFound: return not_authorized_error('Cookie') # If some other sqlalchemy error is thrown, return error except SQLAlchemyError: return jsonify({'error': 'Some problem occurred!'}), 400 # Serialize the user object user_schema = UserSchema() output = user_schema.dump(user).data # Create the tokens to be sent to the user expires = timedelta(seconds=1800) access_token = create_access_token(identity=user.public_id, expires_delta=expires) refresh_token = create_refresh_token(identity=user.public_id) # Get the csrf tokens so they can be set as headers in response csrf_access_token = get_csrf_token(access_token) csrf_refresh_token = get_csrf_token(refresh_token) # Create json response response = make_response( jsonify({ 'user': output, 'success': 'Login successful!' }), 200) # Set JWT cookies and headers and return response set_access_cookies(response, access_token) set_refresh_cookies(response, refresh_token) response.set_cookie('public_id', user.public_id) response.headers['access'] = csrf_access_token response.headers['refresh'] = csrf_refresh_token return response
def confirm_email(token): '''This route takes in a token from the confirmation email link to authenticate the user. It returns the user json object as well as access and refresh token cookies and csrf headers Arg {string} token Returns {Object<json>} 200 success: {string} user: {Object<json>} ''' # Try to decode the jwt token token = token.encode("utf-8") try: data = jwt.decode(token, app.config.get('SECRET_KEY'), algorithm='HS256') # If the token is expired, return error except jwt.ExpiredSignatureError: # Signature has expired return jsonify({'error': 'Reset token is expired. Please try again.'}), 400 # Get the user's id from the token public_id = data['public_id'] # Try to get the user from the database query = User.query.filter_by(public_id=public_id) try: user = query.one() # If no user found, return error except NoResultFound: return jsonify( {'error': ('Could not identify the user. ' ' Please try again.')}), 404, {'WWW-Authentication': 'Basic realm="Login required!"'} # If some other sqlalchemy error is thrown, return error except SQLAlchemyError: return jsonify({'error': 'Some problem occurred!'}), 400 # Add a confirmation date to user and make status active user.confirmed_at = datetime.utcnow() user.is_active = True # Try to add updated user to database try: db.session.commit() # If username already in database, return error except IntegrityError: return jsonify({'error': 'Could not confirm user. Please try again.'}), 400 # If some other sqlalchemy error is thrown, return error except SQLAlchemyError: return jsonify({'error': 'Some problem occurred!'}), 400 # Serialize the user user_schema = UserSchema() output = user_schema.dump(user).data # Create the tokens to be sent to the user expires = timedelta(seconds=1800) access_token = create_access_token(identity=user.public_id, expires_delta=expires) refresh_token = create_refresh_token(identity=user.public_id) # Get the new csrf tokens to be sent as headers csrf_access_token = get_csrf_token(access_token) csrf_refresh_token = get_csrf_token(refresh_token) # Create json response response = make_response( jsonify({ 'user': output, 'success': 'Login successful!' }), 200) # Set access and refresh cookies and headers and return response set_access_cookies(response, access_token) set_refresh_cookies(response, refresh_token) response.set_cookie('public_id', user.public_id) response.headers['access'] = csrf_access_token response.headers['refresh'] = csrf_refresh_token return response
def get_user(id): user_schema = UserSchema() user = UserModel.query.filter_by(id=id).first_or_404() dump_data = user_schema.dump(user) return dump_data
def bot(): incoming_msg = request.values.get('Body', '').lower() resp = MessagingResponse() msg = resp.message() sender_number = request.values.get('From') print("IN BOT") print(incoming_msg) responded = False if 'add state' in incoming_msg: state_name = incoming_msg.split("add state", 1)[1] search_term = state_name.strip() search_term = f"%{search_term}%" state = State.query.filter((State.State.like(search_term))).first() stateSchema = StateSchema() state = stateSchema.dump(state) state_id = state["Id"] state_cured = state["Cured"] state_dead = state["Dead"] state_confirmed = state["Confirmed"] state_name = state["State"] check_user_state_exist = User.query.filter_by( MobileNo=sender_number, State_Id=state['Id']).first() if not check_user_state_exist: user_new = User(State_Id=state_id, MobileNo=sender_number) db.session.add(user_new) db.session.commit() msg.body(f"{state_name} added for COVID-19 tracking.") else: msg.body(f"{state_name} already added for tracking.") msg.body( f"Currently in {state_name}, there are \n {state_confirmed} cases confirmed \n {state_cured} cases " f"cured \n {state_dead} deaths ") responded = True if 'all states' in incoming_msg: user_list = User.query.filter_by(MobileNo=sender_number).all() userSchema = UserSchema(many=True) user_list = userSchema.dump(user_list) print(user_list) if not user_list: msg.body( f"No states added currently add it like *add state Gujarat*") for user_detail in user_list: state_id = user_detail["states"] state = State.query.filter_by(Id=state_id).first() stateSchema = StateSchema() state = stateSchema.dump(state) state_id = state["Id"] state_cured = state["Cured"] state_dead = state["Dead"] state_confirmed = state["Confirmed"] state_name = state["State"] empty = "‎‎ ‎" # invisible character, to get new line hack msg.body(empty) msg.body( f" Currently in \n *{state_name}*, there are \n {state_confirmed} cases confirmed \n {state_cured} cases " f"cured \n {state_dead} deaths. \n {empty}\n") responded = True if 'remove state' in incoming_msg: state_name = incoming_msg.split("remove state", 1)[1] search_term = state_name.strip() search_term = f"%{search_term}%" user_list = User.query.filter_by(MobileNo=sender_number).all() userSchema = UserSchema(many=True) user_list = userSchema.dump(user_list) print(user_list) if not user_list: msg.body( f"No states to remove currently add it like *add state Gujarat*" ) if user_list: state = State.query.filter((State.State.like(search_term))).first() stateSchema = StateSchema() state = stateSchema.dump(state) state_id = state["Id"] state_name = state["State"] User.query.filter_by(MobileNo=sender_number, State_Id=state_id).delete() db.session.commit() msg.body(f"{state_name} removed from tracking") responded = True if 'get news' in incoming_msg: all_news = News.query.all() news_schema = NewsSchema(many=True) all_news = news_schema.dump(all_news) for news in all_news: title = news["Title"] empty = "‎‎ ‎" # invisible character, to get new line hack msg.body(f" \n *Title* : {title} \n {empty}\n ") responded = True if "what is covid 19" in incoming_msg: msg.body( "COVID-19 is a disease caused by a new strain of coronavirus. ‘CO’ stands for corona, ‘VI’ for virus, and ‘D’ for disease. Formerly, this disease was referred to as ‘2019 novel coronavirus’ or ‘2019-nCoV.’ The COVID-19 virus is a new virus linked to the same family of viruses as Severe Acute Respiratory Syndrome (SARS) and some types of common cold" ) responded = True if "symptoms of covid 19" in incoming_msg: msg.body( "Symptoms can include fever, cough and shortness of breath. In more severe cases, infection can cause pneumonia or breathing difficulties. More rarely, the disease can be fatal. These symptoms are similar to the flu (influenza) or the common cold, which are a lot more common than COVID-19. This is why testing is required to confirm if someone has COVID-19." ) responded = True if "how to be safe" in incoming_msg: msg.body('''✓ staying home when sick ✓ covering mouth and nose with flexed elbow or tissue when coughing or sneezing. Dispose ofused tissue immediately; ✓ washing hands often with soap and water; and ✓ cleaning frequently touched surfaces and objects ''') responded = True if "help" in incoming_msg: msg.body('''You can give me the following commands 👉 add state {state name} 👉 all states 👉 remove state {state name} 👉 get news 👉 what is covid 19 👉 symptoms of covid 19 👉 how to be safe 👉 help ''') responded = True if not responded: chatter_resp = chat_bot.get_response(incoming_msg) # print(chatter_resp) # print(chatter_resp.serialize()) serialize_resp = chatter_resp.serialize() res_text = serialize_resp["text"] # print(res_text) empty = "‎‎ ‎" # invisible character, to get new line hack msg.body(f"{res_text}") msg.body(f"{empty} \n you can type *help* for menu") return str(resp)
def create_bracket(): """ This route adds a new bracket to the database and returns a success message as a json object. Returns {Object<json>} 200 success: {string} bracket: {Object<json>} Throws {Exception{Object<json>}} error: NotAuthorized 401 NoResultFound 404 SQLAlchemyError 400 """ # Get the user's id from access token uid = get_jwt_identity() # If no user id, return error if not uid: return make_response( jsonify({'error': 'Could not verify!'}), 401, {'WWW-Authentication': 'Basic realm="Login required!"'}) # Try to get user from database query = User.query.filter_by(public_id=uid) try: user = query.one() # If no result found, return error except NoResultFound: return jsonify({'error': 'No result found!'}), 401 # If some other sqlalchemy error is thrown, return error except SQLAlchemyError: return jsonify({'error': 'Some problem occurred!'}), 400 # Get bracket data from request data = request.get_json() # Verify that all required bracket data was sent bracket_columns = [ 'grp_a_1', 'grp_a_2', 'grp_b_1', 'grp_b_2', 'grp_c_1', 'grp_c_2', 'grp_d_1', 'grp_d_2', 'grp_e_1', 'grp_e_2', 'grp_f_1', 'grp_f_2', 'grp_g_1', 'grp_g_2', 'grp_h_1', 'grp_h_2' ] if not any(key in data for key in bracket_columns): return make_response(jsonify({'error': 'Missing data!'}), 400) # Create bracket object bracket = Bracket(uid=user.public_id, grp_a_1=data['grp_a_1'], grp_a_2=data['grp_a_2'], grp_b_1=data['grp_b_1'], grp_b_2=data['grp_b_2'], grp_c_1=data['grp_c_1'], grp_c_2=data['grp_c_2'], grp_d_1=data['grp_d_1'], grp_d_2=data['grp_d_2'], grp_e_1=data['grp_e_1'], grp_e_2=data['grp_e_2'], grp_f_1=data['grp_f_1'], grp_f_2=data['grp_f_2'], grp_g_1=data['grp_g_1'], grp_g_2=data['grp_g_2'], grp_h_1=data['grp_h_1'], grp_h_2=data['grp_h_2']) # Try to add bracket to database try: db.session.add(bracket) db.session.commit() # If bracket name already in database, return error except IntegrityError: return jsonify({'error': 'User with name or email already exists'}), 400 # If some other sqlalchemy error is thrown, return error except SQLAlchemyError: return jsonify({'error': 'Some problem occurred!'}), 400 # Add the bracket to the user object user.bracket = bracket # Serialze the bracket and user objects and return json response bracket_schema = BracketSchema() b_output = bracket_schema.dump(bracket).data user_schema = UserSchema() u_output = user_schema.dump(user).data return jsonify({ 'success': 'Successfully retrieved bracket.', 'bracket': b_output, 'user': u_output, }), 200
def oauth(provider): """ This route authenticates the user by receiving a provider and oauth token and verifying a user exists. When a user logs in new jwt tokens cookies will be set in the response. Args {string} provider - facebook or google Returns {Object<json>} 200 success: {string} user: {Object<json>} Throws {Exception{Object<json}}: error: Authorization 401 NoResultFound 401 SQLAlchemyError 400 MissingUser 400 InactiveUser 400 """ # If no authorization header, return error if not request.headers.get('Authorization'): return jsonify({'error': 'Not a valid request'}), 401 # Get the token from authorization header and convert to dictionary token = request.headers.get('Authorization').split('Bearer ')[1] token = json.loads(token) # Try to find oauth user in database query = OAuth.query.filter_by( provider=provider, provider_uid=token['userID'], ) try: oauth = query.first() # If no result found, return error except NoResultFound: return jsonify( {'error': "The user doesn't exist. Sign up to create an account"}), 404 # If some other sqlalchemy error is thrown, return error except SQLAlchemyError: return jsonify({'error': 'Some problem occurred!'}), 400 # If not oauth create a new user if not oauth: # Get user data from request data = request.get_json() # If name or email is missing, return error if not (data['name'] or not data['email'] or not data['picture'] or not data['provider_user_id']): return make_response(jsonify({'error': 'Missing data!'}), 400) # Create user object user = User(name=data['name'], email=data['email'], picture=data['picture'], created_at=datetime.utcnow()) user.generate_public_id() # Try to add user to database try: db.session.add(user) db.session.commit() # If username already in database, return error except IntegrityError: return jsonify({'error': 'User with name or email already exists'}), 400 # If some other sqlalchemy error is thrown, return error except SQLAlchemyError: return jsonify({'error': 'Some problem occurred!'}), 400 # Create new oauth token account for user oauth = OAuth( provider=provider, provider_uid=data['provider_user_id'], token=token, ) # Associate the new local user account with the OAuth token oauth.user = user # Save and commit database models db.session.add(oauth) db.session.commit() # If there is no user relation, return error if not oauth.user: return jsonify({'error': 'Some problem occurred!'}), 400 user = oauth.user # Serialze the user object user_schema = UserSchema() output = user_schema.dump(user).data # Create the tokens to be sent to the user expires = timedelta(seconds=1800) access_token = create_access_token(identity=user.public_id, expires_delta=expires) refresh_token = create_refresh_token(identity=user.public_id) # Get the csrf tokens so they can be set as headers in response csrf_access_token = get_csrf_token(access_token) csrf_refresh_token = get_csrf_token(refresh_token) # Create json response response = make_response( jsonify({ 'user': output, 'success': 'Login successful!' }), 200) # Set JWT cookies and headers and return response set_access_cookies(response, access_token) set_refresh_cookies(response, refresh_token) response.set_cookie('public_id', user.public_id) response.headers['access'] = csrf_access_token response.headers['refresh'] = csrf_refresh_token return response
def users(): users = User.query.all() user_schema = UserSchema(many=True) result = user_schema.dump(users) return jsonify(result.data)