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 5 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 @@ -119,6 +119,27 @@ paths:
summary: User Token
security:
- ApiKeyAuth: []
/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 @@ -645,6 +666,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
34 changes: 34 additions & 0 deletions api/src/api/users/user_routes.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import logging
from datetime import timedelta

from src.adapters import db
from src.adapters.db import flask_db
from src.api import response
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 UserTokenRefreshResponseSchema
from src.auth.api_jwt_auth import api_jwt_auth, get_config
from src.auth.api_key_auth import api_key_auth
from src.db.models.user_models import UserTokenSession
from src.util import datetime_util

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -34,3 +41,30 @@ def user_token(x_oauth_login_gov: dict) -> response.ApiResponse:
logger.info(message)

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
config = get_config()
expiration_time = datetime_util.utcnow() + timedelta(minutes=config.token_expiration_minutes)
babebe marked this conversation as resolved.
Show resolved Hide resolved

with db_session.begin():
user_token_session.expires_at = expiration_time
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")
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 @@ -51,3 +51,8 @@ class UserTokenSchema(Schema):

class UserTokenResponseSchema(AbstractResponseSchema):
data = fields.Nested(UserTokenSchema)


class UserTokenRefreshResponseSchema(AbstractResponseSchema):
# No data returned
data = fields.MixinField(metadata={"example": None})
35 changes: 35 additions & 0 deletions api/tests/src/api/users/test_user_route_token.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
##################
# POST /token
##################
from datetime import datetime

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


def test_post_user_route_token_200(client, api_auth_token):
Expand All @@ -25,3 +29,34 @@ def test_post_user_route_token_400(client, api_auth_token):
resp = client.post("v1/users/token", headers={"X-Auth": api_auth_token})
assert resp.status_code == 400
assert resp.get_json()["message"] == "Missing X-OAuth-login-gov header"


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)
expiration = user_token_session.expires_at
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 != expiration
babebe marked this conversation as resolved.
Show resolved Hide resolved


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"