Example #1
0
def register_user():
    """Return HTTP response

    Register an user into the database during the login process.

    This function uses JWT (JSON Web Tokens) to ensure authenticity
    in all subsequent API calls. For more information, see https://jwt.io/.

    If the given user mail is already registered, then just create
    a new JWT token. Otherwise, create the new user with a new token.
    """
    request_json = request.get_json()

    user = User.query.filter_by(email=request_json.get('email')).first()

    if user is None:
        new_user = User(
            email=request_json.get('email'),
            uid=request_json.get('uid'),
            avatar=request_json.get('avatar')
        )
        db.session.add(new_user)
        db.session.commit()
        auth_token = new_user.encode_auth_token(
            new_user.id)
    else:
        auth_token = user.encode_auth_token(user.id)

    return make_response(jsonify({
        'status': 'success',
        'message': 'User has been successfully registered',
        'auth_token': auth_token.decode()
    })), 201