Example #1
0
    async def put(self):
        email_schema = EmailSchema()
        user_identity = get_jwt_identity()
        current_user = await UserModel.find_user_by_email(user_identity)

        if current_user:
            newEmail = await request.get_json()
            try:
                get_user = email_schema.load(newEmail)
            except ValidationError as err:
                return err.messages, 400

            try:
                current_user.email = get_user["email"]
                if get_user[
                        'email'] == current_user.email or await UserModel.find_user_by_email(
                            get_user['email']):
                    return {
                        "message": EMAIL_TAKEN.format(get_user['email'])
                    }, 400

                new_confirmation = UserConfirmationModel(current_user.id)
                new_confirmation.save_to_db()
                current_user.send_email()

                db.session.commit()
                return {"message": EMAIL_UPDATED}, 200

            except (MailgunException, Exception) as err:
                return {'message': str(err)}, 500

        return {"message": USER_NOT_FOUND}, 404
Example #2
0
async def project_get():
    if request.method == 'GET':
        name = request.args.get('name')
        current_user = get_jwt_identity()
        return jsonify(project.get_project(name, current_user)), 200
    else:
        return jsonify(msg="method not supported"), 400
Example #3
0
async def rooms_route():
    identity = get_jwt_identity()

    async with app.db_pool.acquire() as con:
        projects = await con.fetch("""
            SELECT
                r.id,
                r.name,
                u.name as creator,
                r.last_updated
            FROM
                rooms as r
            LEFT JOIN
                users as u
            ON
                r.creator = u.id
            WHERE LOWER(u.email) = $1;
        """, identity)

    room_dicts = [dict(r) for r in projects]
    for room_dict in room_dicts:
        arrow_dt = arrow.get(room_dict["last_updated"])
        room_dict["last_updated"] = arrow_dt.humanize()

    return {"status": 200, "result": room_dicts}
Example #4
0
 def delete(cls):
     user_identity = get_jwt_identity()
     user = UserModel.find_user_by_email(user_identity)
     if not user:
         return {"Message": USER_NOT_FOUND}, 404
     user.delete_from_db()
     return {"message": USER_DELETED.format(user.username)}, 200
Example #5
0
    async def put(self):
        location_schema = LocationSchema()
        user_identity = get_jwt_identity()
        current_user = await UserModel.find_user_by_email(user_identity)

        if current_user:
            currentLocation = await request.get_json()
            try:
                get_user = location_schema.load(currentLocation)
            except ValidationError as err:
                return err.messages, 400

            current_user.country = await Country.get_country_name(
                Country, get_user['country'])
            _ = await Country.get_country_region(Country)
            current_user.phone_number = await Country.get_user_phonenumber(
                Country, get_user["phone_number"])
            current_user.state = await Country.get_states(
                Country, get_user['state'])
            current_user.city = await Country.get_city(Country,
                                                       get_user['city'])

            db.session.commit()

            return {"message": ACCOUNT_UPDATED}, 200
        return {"message": USER_NOT_FOUND}, 404
Example #6
0
async def invalid_token_callback(error_string) -> Response:
    """
    Log that an access attempt was made with a token that was invalid and return
    the result from the default callback.

    Parameters
    ----------
    error_string : str
        Reason the token is invalid

    Returns
    -------
    Response

    """
    current_app.access_logger.error(
        "INVALID_TOKEN",
        error_string=error_string,
        route=request.path,
        request_id=request.request_id,
        user=str(get_jwt_identity()),
        src_ip=request.headers.get("Remote-Addr"),
        json_payload=await request.json,
    )
    return default_invalid_token_callback(error_string)
async def refresh():
    # Do the same thing that we did in the login endpoint here
    current_user = get_jwt_identity()
    access_token = create_access_token(identity=current_user)
    access_jti = get_jti(encoded_token=access_token)
    revoked_store.set(access_jti, "false", ACCESS_EXPIRES * 1.2)
    ret = {"access_token": access_token}
    return ret, 201
Example #8
0
async def partially_protected():
    # If no JWT is sent in with the request, get_jwt_identity()
    # will return None
    current_user = get_jwt_identity()
    if current_user:
        return dict(logged_in_as=current_user), 200
    else:
        return dict(logged_in_as="anonymous user"), 200
Example #9
0
async def project_update():
    if request.method == 'POST':
        data = await request.get_json()
        current_user = get_jwt_identity()
        project_updated = await project.update_project(data, current_user)
        if project_updated:
            return jsonify({'status': '200'})
        else:
            return jsonify({'status': '500'})
Example #10
0
async def project_create():
    if request.method == 'POST':
        data = await request.get_json()
        project_created = await project.create_project(data,
                                                       get_jwt_identity())
        if project_created:
            return jsonify({'status': '200'})
        else:
            return jsonify({'status': '500'})
async def refresh():
    # Create the new access token
    current_user = get_jwt_identity()
    access_token = create_access_token(identity=current_user)

    # Set the JWT access cookie in the response
    resp = {"refresh": True}
    set_access_cookies(resp, access_token)
    return resp, 200
async def refresh():
    # Create the new access token
    current_user = get_jwt_identity()
    access_token = create_access_token(identity=current_user)

    # Set the access JWT and CSRF double submit protection cookies
    # in this response
    resp = {"refresh": True}
    set_access_cookies(resp, access_token)
    return resp, 200
Example #13
0
def add_request_data(_, __, event_dict):
    """
    Processor which adds request data to log entries if available in this context.
    """
    if has_request_context():
        event_dict = dict(
            **event_dict,
            request=dict(
                request_id=getattr(request, "request_id", None),
                path=request.path,
                src_ip=request.headers.get("Remote-Addr"),
                user=str(get_jwt_identity()),
            ),
        )
    return event_dict
Example #14
0
async def create_room():
    identity = get_jwt_identity()

    async with app.db_pool.acquire() as con:
        user_id = await con.fetchval("""
            SELECT
                id
            FROM
                users
            WHERE LOWER(email) = $1;
        """, identity)

    room = await Room.new("Untitled room", user_id)

    return {"result": room.id}
Example #15
0
async def get_user():
    identity = get_jwt_identity()

    async with app.db_pool.acquire() as con:
        user = await con.fetchrow("""
            SELECT
                id,
                email,
                name
            FROM
                users
            WHERE LOWER(email) = $1;
        """, identity)

    return {"status": 200, "result": dict(user)}
Example #16
0
def user_loader_callback(identity):
    """
    Call back for loading user from JWT.

    Parameters
    ----------
    identity : str
        Username

    Returns
    -------
    UserObject
        User with claims pulled from the decoded jwt token

    """
    current_app.access_logger.info(
        "Attempting to load user",
        request_id=request.request_id,
        route=request.path,
        user=get_jwt_identity(),
        src_ip=request.headers.get("Remote-Addr"),
    )

    claims = decompress_claims(get_jwt_claims())

    log_dict = dict(
        request_id=request.request_id,
        route=request.path,
        user=get_jwt_identity(),
        src_ip=request.headers.get("Remote-Addr"),
        claims=claims,
    )
    current_app.access_logger.info("Loaded user", **log_dict)

    return UserObject(username=identity,
                      scopes=list(expand_scopes(scopes=claims)))
Example #17
0
async def refresh_expiring_jwts(response):
    if str(request.url_rule) == "/api/logout":
        return response

    try:
        exp_timestamp = jwt.get_raw_jwt()["exp"]
        now = datetime.utcnow()
        target_timestamp = datetime.timestamp(now + timedelta(minutes=30))
        if target_timestamp > exp_timestamp:
            access_token = jwt.create_access_token(
                identity=jwt.get_jwt_identity())
            response.set_cookie("access_token_cookie", access_token)
            response.set_cookie("jwt_csrf_token",
                                jwt.get_csrf_token(access_token))
        return response
    except (RuntimeError, KeyError):
        return response
Example #18
0
async def claims_verification_failed_callback() -> Tuple[Dict[str, str], int]:
    """
    Log that an access attempt was made with claims that failed verification and return
    a json error message and 401 error code.

    Returns
    -------
    Response
    """
    current_app.access_logger.error(
        "CLAIMS_VERIFICATION_FAILED",
        route=request.path,
        request_id=request.request_id,
        user=str(get_jwt_identity()),
        src_ip=request.headers.get("Remote-Addr"),
        json_payload=await request.json,
    )
    return {"msg": "User claims verification failed"}, 403
Example #19
0
async def revoked_token_callback() -> Response:
    """
    Log that an access attempt was made with a revoked token and return
    the result from the default callback.

    Returns
    -------
    Response
    """
    current_app.access_logger.error(
        "REVOKED_TOKEN",
        route=request.path,
        request_id=request.request_id,
        user=str(get_jwt_identity()),
        src_ip=request.headers.get("Remote-Addr"),
        json_payload=await request.json,
    )
    return default_revoked_token_callback()
Example #20
0
    async def put(self):
        username_schema = UsernameSchema()
        user_identity = get_jwt_identity()
        current_user = await UserModel.find_user_by_email(user_identity)

        if current_user:
            newUsername = await request.get_json()
            try:
                get_user = username_schema.load(newUsername)
            except ValidationError as err:
                return err.messages, 400

            current_user.username = get_user["username"]

            db.session.commit()

            return {"message": ACCOUNT_UPDATED}, 200
        return {"message": USER_NOT_FOUND}, 404
Example #21
0
    async def put(self):
        password_schema = PasswordSchema()
        user_identity = get_jwt_identity()
        current_user = await UserModel.find_user_by_email(user_identity)

        if current_user:
            user = await request.get_json()
            try:
                get_user = password_schema.load(user)
            except ValidationError as err:
                return err.messages, 400

            current_user.password = psw.generate_password_hash(
                get_user["password"])

            db.session.commit()

            return {"message": ACCOUNT_UPDATED}, 200
        return {"message": USER_NOT_FOUND}, 404
Example #22
0
async def unauthorized_callback(error_string) -> Response:
    """
    Log that an access attempt was made without a token and return
    the result from the default callback.

    Returns
    -------
    Response
    """
    current_app.access_logger.error(
        "UNAUTHORISED",
        error_string=error_string,
        route=request.path,
        request_id=request.request_id,
        user=str(get_jwt_identity()),
        src_ip=request.headers.get("Remote-Addr"),
        json_payload=await request.json,
    )
    return default_unauthorized_callback(error_string)
Example #23
0
async def protected():
    username = get_jwt_identity()
    return dict(logged_in_as=username), 200
Example #24
0
async def refresh():
    current_user = get_jwt_identity()
    ret = {"access_token": create_access_token(identity=current_user)}
    return ret, 200
async def refresh():
    current_user = get_jwt_identity()
    new_token = create_access_token(identity=current_user, fresh=False)
    ret = {"access_token": new_token}
    return ret, 200
Example #26
0
 async def post(cls):
     current_user = get_jwt_identity()
     new_token = create_access_token(identity=current_user, fresh=False)
     return {"access_token": new_token}, 200
Example #27
0
async def refresh():
    """Refreshes a JWT token."""
    access_token = jwt.create_access_token(identity=jwt.get_jwt_identity())
    return {"token": access_token}, 200
Example #28
0
async def register():
    existing_jwt = jwt.get_jwt_identity()
    if existing_jwt:
        return {
            "status": 401,
            "error":
            "You cannot register for a new account if you are logged in."
        }, 401

    try:
        data = await request.get_json()
    except Exception:
        return {"status": 400, "error": "Invalid POST data."}, 400

    email = data.get("email")
    password = data.get("password")
    name = data.get("name")

    if not email:
        return {"status": 400, "error": "Missing email parameter."}, 400
    elif not password:
        return {"status": 400, "error": "Missing password parameter."}, 400
    elif not name:
        return {"status": 400, "error": "Missing name parameter."}, 400

    hash_ = hasher.hash(password)

    async with app.db_pool.acquire() as con:
        existing = await con.fetchval(
            """
            SELECT
                email
            FROM
                users
            WHERE LOWER($1) = LOWER(email);
        """, email)

        if existing:
            return {
                "status": 400,
                "error": "User with specified email already exists."
            }, 400

        new_user = await con.fetchrow(
            """
            INSERT INTO
                users (
                    email,
                    password_hash,
                    name
                )
            VALUES
                ($1, $2, $3)
            RETURNING id::TEXT, email, name;
        """, email, hash_, name)

    additional = {"name": name}
    access_token = jwt.create_access_token(identity=email.lower(),
                                           user_claims=additional)

    headers = {"Content-Type": "application/json"}

    response = Response(json.dumps({
        "status": 200,
        "result": dict(new_user)
    }),
                        headers=headers)

    response.set_cookie("access_token_cookie", access_token)
    response.set_cookie("jwt_csrf_token", jwt.get_csrf_token(access_token))

    return response
Example #29
0
async def username():
    username = get_jwt_identity()
    return jsonify(username=username), 200
 async def optional_protected():
     if get_jwt_identity():
         return jsonify(foo="baz")
     else:
         return jsonify(foo="bar")