Example #1
0
def register_user():
    # get post data
    post_data = request.get_json()
    response_object = {'status': 'fail', 'message': 'Invalid payload.'}
    if not post_data:
        return jsonify(response_object), 400
    username = post_data.get('username')
    email = post_data.get('email')
    password = post_data.get('password')
    try:
        # check for existing user
        user = User.query.filter(
            or_(User.username == username, User.email == email)).first()
        if not user:
            # add new user to db
            new_user = User(username=username, email=email, password=password)
            db.session.add(new_user)
            db.session.commit()
            # generate auth token
            auth_token = new_user.encode_auth_token(new_user.id)
            response_object['status'] = 'success'
            response_object['message'] = 'Successfully registered.'
            response_object['auth_token'] = auth_token.decode()
            return jsonify(response_object), 201
        else:
            response_object['message'] = 'Sorry. That user already exists.'
            return jsonify(response_object), 400
    # handler errors
    except (exc.IntegrityError, ValueError) as e:
        db.session.rollback()
        return jsonify(response_object), 400
Example #2
0
def seed_db():
    """Seeds the database."""
    # db.create_all()
    db.session.add(User(username='******', email="*****@*****.**"))
    db.session.add(
        User(username='******', email="*****@*****.**"))
    db.session.add(User(username='******', email="*****@*****.**"))
    db.session.add(User(username='******', email="*****@*****.**"))
    db.session.commit()
Example #3
0
    def func_wrapper(*args, **kwargs):
        # Check for the authentication token
        auth_header = request.headers.get("Authorization")
        if not auth_header:
            # If there's no token provided
            response = {
                "message": "Please register or login to access this resource!"
            }
            return make_response(jsonify(response)), 401

        else:
            access_token = auth_header.split(" ")[1]
            if access_token:
                # Attempt to decode the token and get the user id
                user_id = User.decode_auth_token(access_token)

                if isinstance(user_id, str):
                    # User id does not exist so payload is an error message
                    message = user_id
                    response = jsonify({
                        "message": message
                    })

                    response.status_code = 401
                    return response

                else:
                    return func(user_id=user_id, *args, **kwargs)
            else:
                response = {
                    "message": "Register or log in to access this resource"
                }
                return make_response(jsonify(response)), 401
Example #4
0
def get_user_status():
    # get auth token
    auth_header = request.headers.get('Authorization')
    if auth_header:
        auth_token = auth_header.split(" ")[1]
        resp = User.decode_auth_token(auth_token)
        if not isinstance(resp, str):
            user = User.query.filter_by(id=resp).first()
            response_object = {
                'status': 'success',
                'data': {
                    'id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'is_active': user.is_active,
                    'created_at': user.created_at
                }
            }
            return jsonify(response_object), 200
        response_object = {'status': 'error', 'message': resp}
        return jsonify(response_object), 401
    else:
        response_object = {
            'status': 'error',
            'message': 'Provide a valid auth token.'
        }
        return jsonify(response_object), 401
Example #5
0
def add_user(username, email, password, created_at=datetime.datetime.utcnow()):
    user = User(username=username,
                email=email,
                password=password,
                created_at=created_at)
    db.session.add(user)
    db.session.commit()
    return user
Example #6
0
 def test_add_user_duplicate_email(self):
     add_user('justatest', '*****@*****.**', 'test')
     duplicate_user = User(
         username='******',
         email='*****@*****.**',
         password='******',
     )
     db.session.add(duplicate_user)
     self.assertRaises(IntegrityError, db.session.commit)
Example #7
0
def logout_user():
    # get auth token
    auth_header = request.headers.get('Authorization')
    response_object = {
        'status': 'fail',
        'message': 'Provide a valid auth token.'
    }
    if auth_header:
        auth_token = auth_header.split(' ')[1]
        resp = User.decode_auth_token(auth_token)
        if not isinstance(resp, str):
            response_object['status'] = 'success'
            response_object['message'] = 'Successfully logged out.'
            return jsonify(response_object), 200
        else:
            response_object['message'] = resp
            return jsonify(response_object), 401
    else:
        return jsonify(response_object), 403
Example #8
0
def add_user():
    post_data = request.get_json()
    if not post_data:
        response_object = {
            'status': 'fail',
            'message': 'Invalid payload.'
        }
        return jsonify(response_object), 400
    username = post_data.get('username')
    email = post_data.get('email')
    password = post_data.get('password')
    try:
        user = User.query.filter_by(email=email).first()
        if not user:
            db.session.add(User(
                username=username,
                email=email,
                password=password))
            db.session.commit()
            response_object = {
                'status': 'success',
                'message': f'{email} was added!'
            }
            return jsonify(response_object), 201
        else:
            response_object = {
                'status': 'fail',
                'message': 'Sorry. That email already exists.'
            }
            return jsonify(response_object), 400
    except (exc.IntegrityError, ValueError) as e:
        db.session.rollback()
        response_object = {
            'status': 'fail',
            'message': 'Invalid payload.'
        }
        return jsonify(response_object), 400