def post_signin(): """ POST /auth/get_jwt Signs in the user and fetches the user's token. requires: email, password :return: A Flask Response """ data = request.get_json() if not data: return error_response(), 400 email = data.get('email') password = data.get('password') try: user = User.query.filter_by(email=email).first() if user and bcrypt.check_password_hash(user.password, password): token = user.encode_jwt(user.id) if token: return success_response( '{email} signed in.'.format(email=email), data={'token': token.decode()}), 200 return error_response('User does not exist.'), 404 except Exception as e: print(e) return error_response('Try again.'), 500
def post_users(user_id): """ POST /users Adds a new user. model: username, email, password, active, admin, created_at :param user_id: :return: Flask Response """ if not is_admin(user_id): return error_response('You do not have permission to do that.'), 401 data = request.get_json() if not data: return error_response(), 400 username = data.get('username') email = data.get('email') password = data.get('password') # TODO setup validation try: if not User.query.filter( or_(User.username == username, User.email == email)).first(): add_user(username, email, password) return success_response( '{email} was added!'.format(email=email)), 201 return error_response('User already exists.'), 400 except (exc.IntegrityError, ValueError): db.session.rollback() return error_response(), 400
def post_signup(): """ POST /auth/signup Signs up the new user. requires: { username: '******' email: 'email', password: '******' } :return: flask response """ data = request.get_json() if not data: return error_response(), 400 # TODO validate username = data.get('username') email = data.get('email') password = data.get('password') try: if not User.query.filter( or_(User.username == username, User.email == email)).first(): new_user = add_user(username, email, password) token = new_user.encode_jwt(new_user.id) return success_response('{email} signed up.'.format(email=email), data={'token': token.decode()}), 201 return error_response('User already exists.'), 400 except (exc.IntegrityError, ValueError): db.session.rollback() return error_response(), 400
def get_user_by_id(user_id): """ GET /users/<user_id> Fetches a user with the specified id. :param user_id: :return: Flask Response """ try: user = User.query.filter_by(id=int(user_id)).first() if not user: return error_response('User does not exist.'), 404 return success_response( 'User {user_id} fetched.'.format(user_id=user_id), data={ 'username': user.username, 'email': user.email, 'created_at': user.created_at }), 200 except ValueError: return error_response('User does not exist.'), 404