cloud-api/src/auth/service.py

64 lines
1.6 KiB
Python
Raw Normal View History

2026-04-06 12:41:49 +01:00
"""
2026-05-28 11:10:55 +01:00
Module specific business logic for the auth module
2026-04-06 12:41:49 +01:00
Exports:
2026-05-28 11:10:55 +01:00
- claims_dependency: Dict[str, Any] containing OIDC claims and database ID
2026-04-06 12:41:49 +01:00
"""
2026-04-06 12:41:49 +01:00
import json
import requests
2026-04-06 12:41:49 +01:00
from typing import Annotated, Any
from joserfc import jwt
from joserfc.errors import ExpiredTokenError
from joserfc.jwk import KeySet
2026-04-06 12:41:49 +01:00
from urllib.request import urlopen
from fastapi import Depends
2026-04-06 12:41:49 +01:00
from fastapi.security import OpenIdConnect
from src.auth.exceptions import UnauthorizedException
2026-04-06 12:41:49 +01:00
from src.auth.config import auth_settings
from src.user.service import add_user_to_db
2026-05-29 14:15:50 +01:00
from src.database import db_dependency
2026-04-06 12:41:49 +01:00
oidc = OpenIdConnect(openIdConnectUrl=auth_settings.OIDC_CONFIG)
oidc_dependency = Annotated[str, Depends(oidc)]
def get_dev_user():
return {"db_id": 1}
2026-04-06 12:41:49 +01:00
async def get_current_user(
oidc_auth_string: oidc_dependency, db: db_dependency
) -> dict[str, Any]:
2026-04-06 12:41:49 +01:00
config_url = urlopen(auth_settings.OIDC_CONFIG)
config = json.loads(config_url.read())
jwks_uri = config["jwks_uri"]
key_response = requests.get(jwks_uri)
jwk_keys = KeySet.import_key_set(key_response.json())
2026-04-06 12:41:49 +01:00
claims_options = {
"exp": {"essential": True},
"iss": {"essential": True, "value": auth_settings.OIDC_ISSUER},
}
token = jwt.decode(oidc_auth_string.replace("Bearer ", ""), jwk_keys)
2026-04-06 12:41:49 +01:00
claims_requests = jwt.JWTClaimsRegistry(**claims_options)
2026-04-06 12:41:49 +01:00
try:
claims_requests.validate(token.claims)
except ExpiredTokenError:
raise UnauthorizedException(message="Token is expired")
2026-05-29 14:15:50 +01:00
db_id = await add_user_to_db(db, token.claims)
2026-04-06 12:41:49 +01:00
token.claims["db_id"] = db_id
2026-04-06 12:41:49 +01:00
return token.claims
claims_dependency = Annotated[dict[str, Any], Depends(get_current_user)]