2026-05-06 12:02:26 +01:00
|
|
|
"""
|
|
|
|
|
Module specific business logic for auth module
|
|
|
|
|
|
|
|
|
|
Exports:
|
|
|
|
|
- claims_dependency
|
|
|
|
|
- authed_dependency
|
|
|
|
|
"""
|
|
|
|
|
import json
|
2026-05-07 12:54:55 +01:00
|
|
|
import requests
|
2026-05-06 12:02:26 +01:00
|
|
|
|
2026-05-07 12:54:55 +01:00
|
|
|
from typing import Annotated, Any
|
|
|
|
|
from joserfc import jwt
|
2026-05-06 12:02:26 +01:00
|
|
|
from urllib.request import urlopen
|
|
|
|
|
|
|
|
|
|
from fastapi import Depends, HTTPException
|
|
|
|
|
from fastapi.security import OpenIdConnect
|
2026-05-07 12:54:55 +01:00
|
|
|
from joserfc.jwk import KeySet
|
2026-05-06 12:02:26 +01:00
|
|
|
|
|
|
|
|
from src.auth.config import auth_settings
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
oidc = OpenIdConnect(openIdConnectUrl=auth_settings.OIDC_CONFIG)
|
|
|
|
|
oidc_dependency = Annotated[str, Depends(oidc)]
|
|
|
|
|
|
|
|
|
|
|
2026-05-07 12:54:55 +01:00
|
|
|
async def get_current_user(oidc_auth_string: oidc_dependency) -> dict[str, Any]:
|
2026-05-06 12:02:26 +01:00
|
|
|
config_url = urlopen(auth_settings.OIDC_CONFIG)
|
|
|
|
|
config = json.loads(config_url.read())
|
|
|
|
|
jwks_uri = config["jwks_uri"]
|
2026-05-07 12:54:55 +01:00
|
|
|
key_response = requests.get(jwks_uri)
|
|
|
|
|
jwk_keys = KeySet.import_key_set(key_response.json())
|
2026-05-06 12:02:26 +01:00
|
|
|
|
|
|
|
|
claims_options = {
|
|
|
|
|
"exp": {"essential": True},
|
|
|
|
|
"aud": {"essential": True, "value": "account"},
|
|
|
|
|
"iss": {"essential": True, "value": auth_settings.OIDC_ISSUER},
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-07 12:54:55 +01:00
|
|
|
token = jwt.decode(
|
2026-05-06 12:02:26 +01:00
|
|
|
oidc_auth_string.replace("Bearer ", ""),
|
2026-05-07 12:54:55 +01:00
|
|
|
jwk_keys
|
2026-05-06 12:02:26 +01:00
|
|
|
)
|
|
|
|
|
|
2026-05-07 12:54:55 +01:00
|
|
|
claims_requests = jwt.JWTClaimsRegistry(**claims_options)
|
2026-05-06 12:02:26 +01:00
|
|
|
|
2026-05-07 12:54:55 +01:00
|
|
|
claims_requests.validate(token.claims)
|
2026-05-06 12:02:26 +01:00
|
|
|
|
2026-05-07 12:54:55 +01:00
|
|
|
return token.claims
|
2026-05-06 12:02:26 +01:00
|
|
|
|
2026-05-07 12:54:55 +01:00
|
|
|
|
|
|
|
|
claims_dependency = Annotated[dict[str, Any], Depends(get_current_user)]
|
2026-05-06 12:02:26 +01:00
|
|
|
|
|
|
|
|
|
|
|
|
|
async def is_authed_user(claims: claims_dependency) -> bool:
|
|
|
|
|
authed_users: list[str] = ["chris@sr2.uk"]
|
|
|
|
|
user_email = claims.get("email", None)
|
|
|
|
|
if not user_email or user_email not in authed_users:
|
|
|
|
|
raise HTTPException(status_code=403, detail="Not authenticated")
|
|
|
|
|
return claims.get("email") in authed_users
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
authed_dependency = Annotated[bool, Depends(is_authed_user)]
|