Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Issue 2817] Create a /users/token/refresh endpoint #3002

Merged
merged 15 commits into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions api/openapi.generated.yml
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,27 @@ paths:
summary: User Token Logout
security:
- ApiJwtAuth: []
/v1/users/token/refresh:
post:
parameters: []
responses:
'200':
content:
application/json:
schema:
$ref: '#/components/schemas/UserTokenRefreshResponse'
description: Successful response
'401':
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
description: Authentication error
tags:
- User v1
summary: User Token Refresh
security:
- ApiJwtAuth: []
/v1/opportunities/search:
post:
parameters: []
Expand Down Expand Up @@ -679,6 +700,19 @@ components:
type: integer
description: The HTTP status code
example: 200
UserTokenRefreshResponse:
type: object
properties:
message:
type: string
description: The message to return
example: Success
data:
example: null
status_code:
type: integer
description: The HTTP status code
example: 200
FundingInstrumentFilterV1:
type: object
properties:
Expand Down
29 changes: 27 additions & 2 deletions api/src/api/users/user_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
from src.api.route_utils import raise_flask_error
from src.api.users import user_schemas
from src.api.users.user_blueprint import user_blueprint
from src.api.users.user_schemas import UserTokenLogoutResponseSchema
from src.auth.api_jwt_auth import api_jwt_auth
from src.api.users.user_schemas import UserTokenLogoutResponseSchema, UserTokenRefreshResponseSchema
from src.auth.api_jwt_auth import api_jwt_auth, refresh_token_expiration
from src.auth.api_key_auth import api_key_auth
from src.db.models.user_models import UserTokenSession

Expand Down Expand Up @@ -41,6 +41,31 @@ def user_token(x_oauth_login_gov: dict) -> response.ApiResponse:
raise_flask_error(400, message)


@user_blueprint.post("/token/refresh")
@user_blueprint.output(UserTokenRefreshResponseSchema)
@user_blueprint.doc(responses=[200, 401])
@user_blueprint.auth_required(api_jwt_auth)
@flask_db.with_db_session()
def user_token_refresh(db_session: db.Session) -> response.ApiResponse:
logger.info("POST /v1/users/token/refresh")

user_token_session: UserTokenSession = api_jwt_auth.current_user # type: ignore

with db_session.begin():
refresh_token_expiration(user_token_session)
db_session.add(user_token_session)

logger.info(
"Refreshed a user token",
extra={
"user_token_session.token_id": str(user_token_session.token_id),
"user_token_session.user_id": str(user_token_session.user_id),
},
)

return response.ApiResponse(message="Success")


@user_blueprint.post("/token/logout")
@user_blueprint.output(UserTokenLogoutResponseSchema)
@user_blueprint.doc(responses=[200, 401])
Expand Down
5 changes: 5 additions & 0 deletions api/src/api/users/user_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ class UserTokenResponseSchema(AbstractResponseSchema):
data = fields.Nested(UserTokenSchema)


class UserTokenRefreshResponseSchema(AbstractResponseSchema):
# No data returned
data = fields.MixinField(metadata={"example": None})


class UserTokenLogoutResponseSchema(AbstractResponseSchema):
# No data returned
data = fields.MixinField(metadata={"example": None})
12 changes: 12 additions & 0 deletions api/src/auth/api_jwt_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,3 +205,15 @@ def example_method(db_session: db.Session) -> response.ApiResponse:
# The message is just the value we set when constructing the JwtValidationError
logger.info("JWT Authentication Failed for provided token", extra={"auth.issue": e.message})
raise_flask_error(401, e.message)


def refresh_token_expiration(
token_session: UserTokenSession, config: ApiJwtConfig | None = None
) -> UserTokenSession:
if config is None:
config = get_config()

expiration_time = datetime_util.utcnow() + timedelta(minutes=config.token_expiration_minutes)
token_session.expires_at = expiration_time

return token_session
38 changes: 36 additions & 2 deletions api/tests/src/api/users/test_user_route_token.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
from datetime import datetime

from freezegun import freeze_time

from src.auth.api_jwt_auth import create_jwt_for_user
from tests.src.db.models.factories import UserFactory


##################
# POST /token
##################


def test_post_user_route_token_200(client, api_auth_token):
resp = client.post(
"/v1/users/token", headers={"X-Auth": api_auth_token, "X-OAuth-login-gov": "test"}
Expand All @@ -30,6 +33,37 @@ def test_post_user_route_token_400(client, api_auth_token):
assert resp.get_json()["message"] == "Missing X-OAuth-login-gov header"


@freeze_time("2024-11-22 12:00:00", tz_offset=0)
def test_post_user_route_token_refresh_200(
enable_factory_create, client, db_session, api_auth_token
):
user = UserFactory.create()
token, user_token_session = create_jwt_for_user(user, db_session)
db_session.commit()

resp = client.post("v1/users/token/refresh", headers={"X-SGG-Token": token})

db_session.refresh(user_token_session)

assert resp.status_code == 200
assert user_token_session.expires_at == datetime.fromisoformat("2024-11-22 12:30:00+00:00")


def test_post_user_route_token_refresh_expired(
enable_factory_create, client, db_session, api_auth_token
):
user = UserFactory.create()

token, session = create_jwt_for_user(user, db_session)
session.expires_at = datetime.fromisoformat("1980-01-01 12:00:00+00:00")
db_session.commit()

resp = client.post("v1/users/token/refresh", headers={"X-SGG-Token": token})

assert resp.status_code == 401
assert resp.get_json()["message"] == "Token expired"


def test_post_user_route_token_logout_200(
enable_factory_create, client, db_session, api_auth_token
):
Expand Down