Integrated different auth methods with eachother
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
This commit is contained in:
@@ -20,6 +20,7 @@ dependencies = [
|
||||
"sentence-transformers~=5.5.1",
|
||||
"torch",
|
||||
"sqlmodel~=0.0.33",
|
||||
"argon2-cffi~=25.1.0",
|
||||
]
|
||||
|
||||
[[tool.uv.index]]
|
||||
|
||||
@@ -129,6 +129,11 @@ class Token(BaseModel):
|
||||
nullable=False,
|
||||
description="The epoch value for the token. Used for versioning of tokens.",
|
||||
)
|
||||
user_fingerprint_hash: str = Field(
|
||||
index=True,
|
||||
nullable=False,
|
||||
description="A hash of the user's fingerprint to ensure the token is used by the same user.",
|
||||
)
|
||||
|
||||
|
||||
class IdToken(Token):
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import logging
|
||||
from typing import Annotated
|
||||
from typing import Annotated, Dict
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Body, Depends, Response, status
|
||||
@@ -8,8 +8,8 @@ from sqlmodel import Session
|
||||
from inse.tags import Tags
|
||||
|
||||
import inse.auth.service as auth_service
|
||||
from inse.auth.model import IdToken, RefreshToken, AccessToken
|
||||
from inse.database import SessionDep, get_session
|
||||
from inse.auth.model import AccessToken, IdToken, RefreshToken
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -48,7 +48,9 @@ async def request_otk(
|
||||
async def login(
|
||||
session: SessionDep,
|
||||
response: Response,
|
||||
email_code: Annotated[str, Body(embed=True, description="One-time code sent to user's email")],
|
||||
email_code: Annotated[
|
||||
str, Body(embed=True, description="One-time code sent to user's email")
|
||||
],
|
||||
):
|
||||
return auth_service.login(session, response, email_code)
|
||||
|
||||
@@ -62,12 +64,22 @@ async def login(
|
||||
status.HTTP_200_OK: {"description": "Access token retrieved successfully."}
|
||||
},
|
||||
)
|
||||
async def get_access_token(
|
||||
async def get_action_tokens(
|
||||
response: Response,
|
||||
session: SessionDep,
|
||||
account_id: Annotated[uuid.UUID, Body(description="User's account ID")],
|
||||
id_token: IdToken,
|
||||
):
|
||||
auth_service.get_access_token(account_id, id_token)
|
||||
real_account_id: Annotated[uuid.UUID, Body(description="User's account ID")],
|
||||
effective_account_id: Annotated[
|
||||
uuid.UUID, Body(description="Effective account ID for the access token")
|
||||
],
|
||||
id_token: Annotated[IdToken, auth_service.CurrentUserIdTokenPayloadDep],
|
||||
) -> Dict[str, str]:
|
||||
return auth_service.get_access_token(
|
||||
response=response,
|
||||
session=session,
|
||||
real_account_id=real_account_id,
|
||||
effective_account_id=effective_account_id,
|
||||
id_token=id_token,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
@@ -80,10 +92,11 @@ async def get_access_token(
|
||||
},
|
||||
)
|
||||
async def refresh_access_token(
|
||||
session: SessionDep,
|
||||
refresh_token: RefreshToken,
|
||||
):
|
||||
auth_service.refresh_access_token(refresh_token)
|
||||
refresh_token: Annotated[
|
||||
RefreshToken, auth_service.CurrentUserRefreshTokenPayloadDep
|
||||
],
|
||||
) -> str:
|
||||
return auth_service.refresh_access_token(refresh_token=refresh_token)
|
||||
|
||||
|
||||
@router.post(
|
||||
@@ -95,9 +108,12 @@ async def refresh_access_token(
|
||||
)
|
||||
async def logout(
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
access_token: AccessToken = auth_service.CurrentUserTokenPayloadDep,
|
||||
access_token: Annotated[
|
||||
AccessToken,
|
||||
auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
],
|
||||
):
|
||||
return auth_service.logout(session, access_token)
|
||||
return auth_service.logout(session=session, access_token=access_token)
|
||||
|
||||
|
||||
@router.post(
|
||||
@@ -117,11 +133,14 @@ async def change_password(
|
||||
str,
|
||||
Body(description="New password", min_length=8),
|
||||
],
|
||||
access_token: AccessToken = auth_service.CurrentUserTokenPayloadDep,
|
||||
access_token: Annotated[
|
||||
AccessToken,
|
||||
auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
],
|
||||
):
|
||||
return auth_service.change_password(
|
||||
session,
|
||||
access_token,
|
||||
current_password,
|
||||
new_password,
|
||||
session=session,
|
||||
access_token=access_token,
|
||||
current_password=current_password,
|
||||
new_password=new_password,
|
||||
)
|
||||
|
||||
@@ -10,7 +10,14 @@ from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
|
||||
from fastapi import Depends, HTTPException, Request, Response, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from inse.auth.model import AccessToken, Account, RefreshToken, Secret, UserRole
|
||||
from inse.auth.model import (
|
||||
AccessToken,
|
||||
Account,
|
||||
IdToken,
|
||||
RefreshToken,
|
||||
Secret,
|
||||
UserRole,
|
||||
)
|
||||
from inse.config import get_settings
|
||||
from inse.database import get_session
|
||||
from sqlmodel import Session, select
|
||||
@@ -19,6 +26,8 @@ ID_TOKEN_EXPIRATION_MINUTES = 60 * 24 * 30 # 30 days
|
||||
REFRESH_TOKEN_EXPIRATION_MINUTES = 15 # 15 minutes
|
||||
ACCESS_TOKEN_EXPIRATION_MINUTES = 5 # 5 minutes
|
||||
|
||||
OTK_EXPIRATION_MINUTES = 15 # 15 minutes
|
||||
|
||||
REAL_ACCOUNT_ID_KEY = "real_account_id"
|
||||
EFFECTIVE_ACCOUNT_ID_KEY = "effective_account_id"
|
||||
EFFECTIVE_ROLE_KEY = "effective_role"
|
||||
@@ -26,6 +35,9 @@ EPOCH_KEY = "epoch"
|
||||
ORGANIZATION_ID_KEY = "organization_id"
|
||||
USER_FINGERPRINT_HASH_KEY = "user_fingerprint_hash"
|
||||
|
||||
ID_FP_COOKIE_KEY = "__Secure-Fgp-ID"
|
||||
ACT_FP_COOKIE_KEY = "__Secure-Fgp-Act"
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -34,12 +46,34 @@ security_scheme = HTTPBearer()
|
||||
|
||||
_password_hasher = PasswordHasher()
|
||||
|
||||
AccountNotFoundException = HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Account not found.",
|
||||
)
|
||||
|
||||
|
||||
def _hash_password(password: str) -> str:
|
||||
"""Hashes the provided password using Argon2 and returns the hashed value.
|
||||
|
||||
Args:
|
||||
password (str): The password to hash.
|
||||
|
||||
Returns:
|
||||
str: The hashed password.
|
||||
"""
|
||||
return _password_hasher.hash(password)
|
||||
|
||||
|
||||
def _verify_password(password: str, password_hash: str) -> bool:
|
||||
"""Verifies the provided password against the stored password hash using Argon2.
|
||||
|
||||
Args:
|
||||
password (str): The password to verify.
|
||||
password_hash (str): The stored password hash to verify against.
|
||||
|
||||
Returns:
|
||||
bool: True if the password is correct, False otherwise.
|
||||
"""
|
||||
try:
|
||||
return _password_hasher.verify(password_hash, password)
|
||||
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||
@@ -47,20 +81,36 @@ def _verify_password(password: str, password_hash: str) -> bool:
|
||||
|
||||
|
||||
def request_otk(session: Session, email: str, password: str):
|
||||
"""Requests a one-time key (OTK) for authentication using email and password. Validates the provided credentials and generates a one-time key if valid.
|
||||
|
||||
Args:
|
||||
session (Session): The database session used to query the account and secret.
|
||||
email (str): The user's email address.
|
||||
password (str): The user's password.
|
||||
|
||||
|
||||
Raises:
|
||||
HTTPException: If the email or password is invalid.
|
||||
HTTPException: If the account is not found.
|
||||
"""
|
||||
account = session.exec(
|
||||
select(Account).where(
|
||||
Account.email == email,
|
||||
Account.deleted == False,
|
||||
not Account.deleted,
|
||||
)
|
||||
).first()
|
||||
|
||||
if account is None:
|
||||
if account is None or account.deleted or account.id is None:
|
||||
logger.warning("OTK request failed for email %s: account not found", email)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid email or password",
|
||||
)
|
||||
|
||||
if not _verify_password(password, account.password_hash):
|
||||
logger.warning(
|
||||
"OTK request failed for email %s: password verification failed", email
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid email or password",
|
||||
@@ -68,12 +118,10 @@ def request_otk(session: Session, email: str, password: str):
|
||||
|
||||
otk_code = f"{secrets.randbelow(1_000_000):06d}"
|
||||
|
||||
secret = session.exec(
|
||||
select(Secret).where(Secret.account_id == account.id)
|
||||
).first()
|
||||
secret = session.exec(select(Secret).where(Secret.account_id == account.id)).first()
|
||||
|
||||
expires_at = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
|
||||
minutes=5
|
||||
minutes=OTK_EXPIRATION_MINUTES
|
||||
)
|
||||
|
||||
if secret is None:
|
||||
@@ -89,12 +137,25 @@ def request_otk(session: Session, email: str, password: str):
|
||||
|
||||
session.commit()
|
||||
|
||||
logger.info("OTK code for account %s: %s", account.id, otk_code)
|
||||
logger.info(
|
||||
"Saved OTK for account %s with expiration at %s", account.id, expires_at
|
||||
)
|
||||
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
def login(session: Session, response: Response, email_code: str):
|
||||
"""Login using a one-time key (OTK) sent to the user's email. Validates the OTK and generates an ID token for the user.
|
||||
|
||||
Args:
|
||||
session (Session): The database session used to query the account and secret.
|
||||
response (Response): The response object to set the ID token cookie.
|
||||
email_code (str): The one-time code sent to the user's email.
|
||||
|
||||
Raises:
|
||||
HTTPException: If the code is invalid or expired.
|
||||
HTTPException: If the account is not active.
|
||||
"""
|
||||
now = datetime.datetime.now(datetime.timezone.utc)
|
||||
|
||||
secret = session.exec(
|
||||
@@ -102,12 +163,19 @@ def login(session: Session, response: Response, email_code: str):
|
||||
).first()
|
||||
|
||||
if secret is None or secret.expires_at <= now:
|
||||
logger.warning("Login failed: invalid or expired code %s", email_code)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired code",
|
||||
)
|
||||
|
||||
account = _get_active_account(session, secret.account_id)
|
||||
if not account or account.deleted or account.id is None:
|
||||
logger.warning("Login failed: account is not active %s", secret.account_id)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Account is not active.",
|
||||
)
|
||||
|
||||
id_token = _build_id_token(
|
||||
response,
|
||||
@@ -118,30 +186,30 @@ def login(session: Session, response: Response, email_code: str):
|
||||
session.delete(secret)
|
||||
session.commit()
|
||||
|
||||
return {"idToken": id_token}
|
||||
return {"id_token": id_token}
|
||||
|
||||
|
||||
|
||||
def _get_current_user_token_payload(
|
||||
def _get_current_user_access_token_payload(
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
request: Request,
|
||||
credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)],
|
||||
) -> AccessToken:
|
||||
"""Extracts and verifies the current user's token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies.
|
||||
"""Extracts and verifies the current user's access token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies.
|
||||
|
||||
Args:
|
||||
request (Request): The FastAPI request object containing the cookies.
|
||||
credentials (Annotated[HTTPAuthorizationCredentials, Depends): The HTTP authorization credentials extracted from the request.
|
||||
session (Annotated[Session, Depends): The database session used to query the account and secret.
|
||||
request (Request): The request object containing the access token.
|
||||
credentials (Annotated[HTTPAuthorizationCredentials, Depends): The HTTP authorization credentials containing the access token.
|
||||
|
||||
Returns:
|
||||
Dict[str, Any]: The verified token payload.
|
||||
AccessToken: The verified access token payload.
|
||||
"""
|
||||
|
||||
token = credentials.credentials
|
||||
|
||||
access_token_payload = _verify_fp_token(
|
||||
request=request,
|
||||
cookie_key="__Secure-Fgp-Act",
|
||||
cookie_key=ACT_FP_COOKIE_KEY,
|
||||
token=token,
|
||||
session=session,
|
||||
)
|
||||
@@ -159,73 +227,191 @@ def _get_current_user_token_payload(
|
||||
)
|
||||
|
||||
|
||||
CurrentUserTokenPayloadDep = Depends(_get_current_user_token_payload)
|
||||
def _get_current_user_refresh_token_payload(
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
request: Request,
|
||||
credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)],
|
||||
) -> RefreshToken:
|
||||
"""Extracts and verifies the current user's refresh token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies.
|
||||
|
||||
Args:
|
||||
session (Annotated[Session, Depends): The database session used to query the account and secret.
|
||||
request (Request): The request object containing the refresh token.
|
||||
credentials (Annotated[HTTPAuthorizationCredentials, Depends): The HTTP authorization credentials containing the refresh token.
|
||||
|
||||
Returns:
|
||||
RefreshToken: The verified refresh token payload.
|
||||
"""
|
||||
token = credentials.credentials
|
||||
|
||||
refresh_token_payload = _verify_fp_token(
|
||||
request=request,
|
||||
cookie_key=ACT_FP_COOKIE_KEY,
|
||||
token=token,
|
||||
session=session,
|
||||
)
|
||||
# If reaches here, the refresh token is valid and the fingerprint matches
|
||||
return RefreshToken(
|
||||
real_account_id=uuid.UUID(refresh_token_payload[REAL_ACCOUNT_ID_KEY]),
|
||||
effective_account_id=uuid.UUID(refresh_token_payload[EFFECTIVE_ACCOUNT_ID_KEY]),
|
||||
expires_at=datetime.datetime.fromtimestamp(
|
||||
refresh_token_payload["exp"], tz=datetime.timezone.utc
|
||||
),
|
||||
epoch=refresh_token_payload[EPOCH_KEY],
|
||||
effective_role=UserRole(refresh_token_payload[EFFECTIVE_ROLE_KEY]),
|
||||
effective_organization_id=uuid.UUID(refresh_token_payload[ORGANIZATION_ID_KEY]),
|
||||
)
|
||||
|
||||
|
||||
def _get_current_user_id_token_payload(
|
||||
session: Annotated[Session, Depends(get_session)],
|
||||
request: Request,
|
||||
credentials: Annotated[HTTPAuthorizationCredentials, Depends(security_scheme)],
|
||||
) -> IdToken:
|
||||
"""Extracts and verifies the current user's ID token payload from the request, ensuring that the token's fingerprint matches the one stored in the cookies.
|
||||
|
||||
Args:
|
||||
session (Annotated[Session, Depends): The database session used to query the account and secret.
|
||||
request (Request): The request object containing the ID token.
|
||||
credentials (Annotated[HTTPAuthorizationCredentials, Depends): The HTTP authorization credentials containing the ID token.
|
||||
|
||||
Returns:
|
||||
Dict[str, Any]: The verified ID token payload.
|
||||
"""
|
||||
token = credentials.credentials
|
||||
|
||||
id_token_payload = _verify_fp_token(
|
||||
request=request,
|
||||
cookie_key=ID_FP_COOKIE_KEY,
|
||||
token=token,
|
||||
session=session,
|
||||
)
|
||||
# If reaches here, the ID token is valid and the fingerprint matches
|
||||
|
||||
return IdToken(
|
||||
real_account_id=uuid.UUID(id_token_payload[REAL_ACCOUNT_ID_KEY]),
|
||||
expires_at=datetime.datetime.fromtimestamp(
|
||||
id_token_payload["exp"], tz=datetime.timezone.utc
|
||||
),
|
||||
epoch=id_token_payload[EPOCH_KEY],
|
||||
)
|
||||
|
||||
|
||||
CurrentUserAccessTokenPayloadDep = Depends(_get_current_user_access_token_payload)
|
||||
CurrentUserRefreshTokenPayloadDep = Depends(_get_current_user_refresh_token_payload)
|
||||
CurrentUserIdTokenPayloadDep = Depends(_get_current_user_id_token_payload)
|
||||
|
||||
|
||||
def _get_account_epoch(
|
||||
account_id: uuid.UUID,
|
||||
session: Session,
|
||||
account_id: uuid.UUID,
|
||||
) -> int:
|
||||
"""Retrieves the current epoch value for the specified account ID, ensuring that the account exists and is not deleted.
|
||||
|
||||
Args:
|
||||
session (Session): The database session used to query the account.
|
||||
account_id (uuid.UUID): The unique identifier of the account for which to retrieve the epoch.
|
||||
|
||||
Raises:
|
||||
HTTPException: If the account does not exist, is deleted, or has no valid ID.
|
||||
|
||||
Returns:
|
||||
int: The current epoch value for the account.
|
||||
"""
|
||||
account = session.get(Account, account_id)
|
||||
|
||||
if account is None or account.deleted:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Account is not active.",
|
||||
)
|
||||
if account is None or account.deleted or account.id is None:
|
||||
raise AccountNotFoundException
|
||||
|
||||
return account.epoch
|
||||
|
||||
|
||||
def _get_account_role(account_id: uuid.UUID) -> UserRole:
|
||||
def _get_account_role(session: Session, account_id: uuid.UUID) -> UserRole:
|
||||
"""Retrieves the role for the given account ID.
|
||||
|
||||
Args:
|
||||
session (Session): The database session.
|
||||
account_id (uuid.UUID): The unique identifier of the account for which to retrieve the role.
|
||||
|
||||
Returns:
|
||||
UserRole: The role associated with the given account ID.
|
||||
"""
|
||||
return (
|
||||
UserRole.USER
|
||||
) # TODO: Replace with actual logic to retrieve the role for the account
|
||||
account = session.get(Account, account_id)
|
||||
|
||||
if not account or account.deleted or account.id is None:
|
||||
raise AccountNotFoundException
|
||||
|
||||
return account.role
|
||||
|
||||
|
||||
def _get_account_organization(account_id: uuid.UUID) -> uuid.UUID:
|
||||
def _get_account_organization(session: Session, account_id: uuid.UUID) -> uuid.UUID:
|
||||
"""Retrieves the organization ID for the given account ID.
|
||||
|
||||
Args:
|
||||
session (Session): The database session.
|
||||
account_id (uuid.UUID): The unique identifier of the account for which to retrieve the organization ID.
|
||||
|
||||
Returns:
|
||||
uuid.UUID: The organization ID associated with the given account ID.
|
||||
"""
|
||||
return (
|
||||
uuid.uuid4()
|
||||
) # TODO: Replace with actual logic to retrieve the organization ID for the account
|
||||
account = session.get(Account, account_id)
|
||||
|
||||
if not account or account.deleted or account.id is None:
|
||||
raise AccountNotFoundException
|
||||
|
||||
return account.organization_id
|
||||
|
||||
|
||||
def _is_valid_impersonation(
|
||||
real_account_id: uuid.UUID, effective_account_id: uuid.UUID
|
||||
session: Session, real_account_id: uuid.UUID, effective_account_id: uuid.UUID
|
||||
) -> bool:
|
||||
"""Checks if the real account is allowed to impersonate the effective account.
|
||||
|
||||
Args:
|
||||
session (Session): The database session.
|
||||
real_account_id (uuid.UUID): The unique identifier of the real account.
|
||||
effective_account_id (uuid.UUID): The unique identifier of the effective account.
|
||||
|
||||
Returns:
|
||||
bool: True if impersonation is allowed, False otherwise.
|
||||
"""
|
||||
return True # TODO: Replace with actual logic to check if impersonation is allowed
|
||||
real_account = session.get(Account, real_account_id)
|
||||
if not real_account or real_account.deleted or real_account.id is None:
|
||||
raise AccountNotFoundException
|
||||
effective_account = session.get(Account, effective_account_id)
|
||||
if (
|
||||
not effective_account
|
||||
or effective_account.deleted
|
||||
or effective_account.id is None
|
||||
):
|
||||
raise AccountNotFoundException
|
||||
|
||||
if real_account.role == UserRole.SUPER_ADMIN:
|
||||
return True # Super admins can impersonate any account
|
||||
|
||||
if real_account.organization_id != effective_account.organization_id:
|
||||
return False # Cannot impersonate accounts from different organizations
|
||||
|
||||
if real_account.role == UserRole.ADMIN and effective_account.role in [
|
||||
UserRole.MANAGER,
|
||||
UserRole.USER,
|
||||
]:
|
||||
return True # Admins can impersonate managers and users within the same organization
|
||||
|
||||
if (
|
||||
real_account.role == UserRole.MANAGER
|
||||
and effective_account.role == UserRole.USER
|
||||
):
|
||||
return True # Managers can impersonate users within the same organization
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def get_access_token(
|
||||
request: Request,
|
||||
response: Response,
|
||||
id_token: str,
|
||||
real_account_id: uuid.UUID,
|
||||
session: Session,
|
||||
id_token: IdToken,
|
||||
real_account_id: uuid.UUID,
|
||||
effective_account_id: Optional[uuid.UUID] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Generates access and refresh tokens for the specified real and effective account IDs, verifying the provided ID token and ensuring that the fingerprint matches the one stored in the cookies.
|
||||
@@ -244,23 +430,20 @@ def get_access_token(
|
||||
Returns:
|
||||
Dict[str, Any]: A dictionary containing the generated access and refresh tokens.
|
||||
"""
|
||||
# IMPORTANT: The ID token has already been verified by the dependency injection system, so we can trust its payload here.
|
||||
|
||||
id_token_payload = _verify_fp_token(
|
||||
request=request,
|
||||
cookie_key="__Secure-Fgp-ID",
|
||||
token=id_token,
|
||||
session=session,
|
||||
)
|
||||
# If reaches here, the id_token is valid and the fingerprint matches
|
||||
|
||||
if str(real_account_id) != id_token_payload[REAL_ACCOUNT_ID_KEY]:
|
||||
if str(real_account_id) != id_token.real_account_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Real account ID does not match ID token",
|
||||
)
|
||||
|
||||
if effective_account_id:
|
||||
if not _is_valid_impersonation(real_account_id, effective_account_id):
|
||||
if not _is_valid_impersonation(
|
||||
session=session,
|
||||
real_account_id=real_account_id,
|
||||
effective_account_id=effective_account_id,
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Impersonation not allowed",
|
||||
@@ -269,9 +452,11 @@ def get_access_token(
|
||||
# No impersonation, set effective_account_id to real_account_id
|
||||
effective_account_id = real_account_id
|
||||
|
||||
role = _get_account_role(effective_account_id)
|
||||
epoch = _get_account_epoch(effective_account_id, session=session)
|
||||
organization_id = _get_account_organization(effective_account_id)
|
||||
role = _get_account_role(session=session, account_id=effective_account_id)
|
||||
epoch = _get_account_epoch(account_id=effective_account_id, session=session)
|
||||
organization_id = _get_account_organization(
|
||||
session=session, account_id=effective_account_id
|
||||
)
|
||||
|
||||
user_fingerprint_hash = _set_act_fp_cookie(response=response)
|
||||
|
||||
@@ -299,7 +484,7 @@ def _set_id_fp_cookie(response: Response) -> str:
|
||||
str: The hashed value of the fingerprint.
|
||||
"""
|
||||
return _set_fingerprint_cookie(
|
||||
response, "__Secure-Fgp-ID", max_age=ID_TOKEN_EXPIRATION_MINUTES * 60
|
||||
response, ID_FP_COOKIE_KEY, max_age=ID_TOKEN_EXPIRATION_MINUTES * 60
|
||||
)
|
||||
|
||||
|
||||
@@ -313,7 +498,7 @@ def _set_act_fp_cookie(response: Response) -> str:
|
||||
str: The hashed value of the fingerprint.
|
||||
"""
|
||||
return _set_fingerprint_cookie(
|
||||
response, "__Secure-Fgp-Act"
|
||||
response, ACT_FP_COOKIE_KEY
|
||||
) # Setting no max age to make it a session cookie, which will be deleted when the browser is closed.
|
||||
|
||||
|
||||
@@ -345,35 +530,46 @@ def _set_fingerprint_cookie(
|
||||
return hashlib.sha256(user_fingerprint.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def refresh_access_token(refresh_token: RefreshToken) -> str:
|
||||
"""Refreshes the access token using the provided refresh token and verifies the fingerprint from the request cookies.
|
||||
|
||||
Args:
|
||||
request (Request): The FastAPI request object containing the cookies.
|
||||
session (Session): The database session.
|
||||
refresh_token (RefreshToken): The refresh token to verify.
|
||||
|
||||
Returns:
|
||||
str: The refreshed access token.
|
||||
"""
|
||||
# IMPORTANT: The refresh token has already been verified by the dependency injection system, so we can trust its payload here.
|
||||
|
||||
return _refresh_access_token(
|
||||
refresh_token=refresh_token,
|
||||
)
|
||||
|
||||
|
||||
def _refresh_access_token(
|
||||
request: Request,
|
||||
refresh_token: str,
|
||||
session: Session,
|
||||
refresh_token: RefreshToken,
|
||||
) -> str:
|
||||
"""Refreshes the access token using the provided refresh token and verifies the fingerprint from the request cookies.
|
||||
|
||||
Args:
|
||||
request (Request): The FastAPI request object containing the cookies.
|
||||
refresh_token (str): The refresh token to verify.
|
||||
refresh_token (RefreshToken): The refresh token to verify.
|
||||
current_user_epoch (int): The epoch value for the tokens.
|
||||
|
||||
Returns:
|
||||
str: The refreshed access token.
|
||||
"""
|
||||
refresh_payload = _verify_fp_token(
|
||||
request=request,
|
||||
cookie_key="__Secure-Fgp-Act",
|
||||
token=refresh_token,
|
||||
session=session,
|
||||
)
|
||||
# IMPORTANT: The refresh token has already been verified by the dependency injection system, so we can trust its payload here.
|
||||
|
||||
access_payload = {
|
||||
REAL_ACCOUNT_ID_KEY: refresh_payload[REAL_ACCOUNT_ID_KEY],
|
||||
EFFECTIVE_ACCOUNT_ID_KEY: refresh_payload[EFFECTIVE_ACCOUNT_ID_KEY],
|
||||
EPOCH_KEY: refresh_payload[EPOCH_KEY],
|
||||
EFFECTIVE_ROLE_KEY: refresh_payload[EFFECTIVE_ROLE_KEY],
|
||||
ORGANIZATION_ID_KEY: refresh_payload[ORGANIZATION_ID_KEY],
|
||||
USER_FINGERPRINT_HASH_KEY: refresh_payload[USER_FINGERPRINT_HASH_KEY],
|
||||
REAL_ACCOUNT_ID_KEY: refresh_token.real_account_id,
|
||||
EFFECTIVE_ACCOUNT_ID_KEY: refresh_token.effective_account_id,
|
||||
EPOCH_KEY: refresh_token.epoch,
|
||||
EFFECTIVE_ROLE_KEY: refresh_token.effective_role,
|
||||
ORGANIZATION_ID_KEY: refresh_token.effective_organization_id,
|
||||
USER_FINGERPRINT_HASH_KEY: refresh_token.user_fingerprint_hash,
|
||||
}
|
||||
return _build_token(
|
||||
payload=access_payload, expiration_min=ACCESS_TOKEN_EXPIRATION_MINUTES
|
||||
@@ -520,8 +716,8 @@ def _verify_fp_token(
|
||||
epoch_account_id = uuid.UUID(effective_account_id)
|
||||
|
||||
current_account_epoch = _get_account_epoch(
|
||||
epoch_account_id,
|
||||
session=session,
|
||||
account_id=epoch_account_id,
|
||||
)
|
||||
|
||||
token_epoch = payload.get(EPOCH_KEY)
|
||||
@@ -545,14 +741,22 @@ def _verify_fp_token(
|
||||
)
|
||||
|
||||
|
||||
def refresh_access_token(refresh_token: RefreshToken):
|
||||
pass
|
||||
|
||||
|
||||
def _get_active_account(session: Session, account_id: uuid.UUID) -> Account:
|
||||
"""Gets the active account for the given account ID, ensuring that the account exists and is not deleted.
|
||||
|
||||
Args:
|
||||
session (Session): The database session used to query the account.
|
||||
account_id (uuid.UUID): The ID of the account to retrieve.
|
||||
|
||||
Raises:
|
||||
HTTPException: If the account does not exist or is deleted.
|
||||
|
||||
Returns:
|
||||
Account: The active account if it exists and is not deleted.
|
||||
"""
|
||||
account = session.get(Account, account_id)
|
||||
|
||||
if account is None or account.deleted:
|
||||
if account is None or account.deleted or account.id is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Account is not active.",
|
||||
@@ -561,7 +765,18 @@ def _get_active_account(session: Session, account_id: uuid.UUID) -> Account:
|
||||
return account
|
||||
|
||||
|
||||
def logout(session: Session, access_token: AccessToken) -> dict:
|
||||
def logout(session: Session, access_token: AccessToken) -> Dict[str, str]:
|
||||
"""Logout the user by incrementing the epoch of the account associated with the provided access token, effectively invalidating all existing tokens for that account.
|
||||
|
||||
Args:
|
||||
request (Request): The FastAPI request object.
|
||||
session (Session): The database session used to query the account.
|
||||
access_token (AccessToken): The access token for the user to logout.
|
||||
|
||||
Returns:
|
||||
dict: A dictionary containing the status of the logout operation.
|
||||
"""
|
||||
|
||||
account = _get_active_account(session, access_token.effective_account_id)
|
||||
|
||||
account.epoch += 1
|
||||
@@ -577,7 +792,22 @@ def change_password(
|
||||
access_token: AccessToken,
|
||||
current_password: str,
|
||||
new_password: str,
|
||||
) -> dict:
|
||||
) -> Dict[str, str]:
|
||||
"""Change the password for the user associated with the provided access token.
|
||||
|
||||
Args:
|
||||
request (Request): The FastAPI request object.
|
||||
session (Session): The database session used to query the account.
|
||||
access_token (AccessToken): The access token for the user.
|
||||
current_password (str): The current password for the user.
|
||||
new_password (str): The new password for the user.
|
||||
|
||||
Raises:
|
||||
HTTPException: If the access token is invalid or the current password is incorrect.
|
||||
|
||||
Returns:
|
||||
Dict[str, str]: A dictionary containing the status of the password change operation.
|
||||
"""
|
||||
account = _get_active_account(session, access_token.effective_account_id)
|
||||
|
||||
if not _verify_password(current_password, account.password_hash):
|
||||
|
||||
Generated
+53
-4
@@ -2,8 +2,10 @@ version = 1
|
||||
revision = 3
|
||||
requires-python = ">=3.12"
|
||||
resolution-markers = [
|
||||
"sys_platform != 'darwin'",
|
||||
"sys_platform == 'darwin'",
|
||||
"python_full_version >= '3.14' and sys_platform != 'darwin'",
|
||||
"python_full_version < '3.14' and sys_platform != 'darwin'",
|
||||
"python_full_version >= '3.14' and sys_platform == 'darwin'",
|
||||
"python_full_version < '3.14' and sys_platform == 'darwin'",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -37,6 +39,49 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/da/42/e921fccf5015463e32a3cf6ee7f980a6ed0f395ceeaa45060b61d86486c2/anyio-4.13.0-py3-none-any.whl", hash = "sha256:08b310f9e24a9594186fd75b4f73f4a4152069e3853f1ed8bfbf58369f4ad708", size = 114353, upload-time = "2026-03-24T12:59:08.246Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "argon2-cffi"
|
||||
version = "25.1.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "argon2-cffi-bindings" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/0e/89/ce5af8a7d472a67cc819d5d998aa8c82c5d860608c4db9f46f1162d7dab9/argon2_cffi-25.1.0.tar.gz", hash = "sha256:694ae5cc8a42f4c4e2bf2ca0e64e51e23a040c6a517a85074683d3959e1346c1", size = 45706, upload-time = "2025-06-03T06:55:32.073Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/4f/d3/a8b22fa575b297cd6e3e3b0155c7e25db170edf1c74783d6a31a2490b8d9/argon2_cffi-25.1.0-py3-none-any.whl", hash = "sha256:fdc8b074db390fccb6eb4a3604ae7231f219aa669a2652e0f20e16ba513d5741", size = 14657, upload-time = "2025-06-03T06:55:30.804Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "argon2-cffi-bindings"
|
||||
version = "25.1.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "cffi" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/5c/2d/db8af0df73c1cf454f71b2bbe5e356b8c1f8041c979f505b3d3186e520a9/argon2_cffi_bindings-25.1.0.tar.gz", hash = "sha256:b957f3e6ea4d55d820e40ff76f450952807013d361a65d7f28acc0acbf29229d", size = 1783441, upload-time = "2025-07-30T10:02:05.147Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/60/97/3c0a35f46e52108d4707c44b95cfe2afcafc50800b5450c197454569b776/argon2_cffi_bindings-25.1.0-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:3d3f05610594151994ca9ccb3c771115bdb4daef161976a266f0dd8aa9996b8f", size = 54393, upload-time = "2025-07-30T10:01:40.97Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9d/f4/98bbd6ee89febd4f212696f13c03ca302b8552e7dbf9c8efa11ea4a388c3/argon2_cffi_bindings-25.1.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:8b8efee945193e667a396cbc7b4fb7d357297d6234d30a489905d96caabde56b", size = 29328, upload-time = "2025-07-30T10:01:41.916Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/43/24/90a01c0ef12ac91a6be05969f29944643bc1e5e461155ae6559befa8f00b/argon2_cffi_bindings-25.1.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:3c6702abc36bf3ccba3f802b799505def420a1b7039862014a65db3205967f5a", size = 31269, upload-time = "2025-07-30T10:01:42.716Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d4/d3/942aa10782b2697eee7af5e12eeff5ebb325ccfb86dd8abda54174e377e4/argon2_cffi_bindings-25.1.0-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a1c70058c6ab1e352304ac7e3b52554daadacd8d453c1752e547c76e9c99ac44", size = 86558, upload-time = "2025-07-30T10:01:43.943Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0d/82/b484f702fec5536e71836fc2dbc8c5267b3f6e78d2d539b4eaa6f0db8bf8/argon2_cffi_bindings-25.1.0-cp314-cp314t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e2fd3bfbff3c5d74fef31a722f729bf93500910db650c925c2d6ef879a7e51cb", size = 92364, upload-time = "2025-07-30T10:01:44.887Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c9/c1/a606ff83b3f1735f3759ad0f2cd9e038a0ad11a3de3b6c673aa41c24bb7b/argon2_cffi_bindings-25.1.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:c4f9665de60b1b0e99bcd6be4f17d90339698ce954cfd8d9cf4f91c995165a92", size = 85637, upload-time = "2025-07-30T10:01:46.225Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/44/b4/678503f12aceb0262f84fa201f6027ed77d71c5019ae03b399b97caa2f19/argon2_cffi_bindings-25.1.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ba92837e4a9aa6a508c8d2d7883ed5a8f6c308c89a4790e1e447a220deb79a85", size = 91934, upload-time = "2025-07-30T10:01:47.203Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f0/c7/f36bd08ef9bd9f0a9cff9428406651f5937ce27b6c5b07b92d41f91ae541/argon2_cffi_bindings-25.1.0-cp314-cp314t-win32.whl", hash = "sha256:84a461d4d84ae1295871329b346a97f68eade8c53b6ed9a7ca2d7467f3c8ff6f", size = 28158, upload-time = "2025-07-30T10:01:48.341Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b3/80/0106a7448abb24a2c467bf7d527fe5413b7fdfa4ad6d6a96a43a62ef3988/argon2_cffi_bindings-25.1.0-cp314-cp314t-win_amd64.whl", hash = "sha256:b55aec3565b65f56455eebc9b9f34130440404f27fe21c3b375bf1ea4d8fbae6", size = 32597, upload-time = "2025-07-30T10:01:49.112Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/05/b8/d663c9caea07e9180b2cb662772865230715cbd573ba3b5e81793d580316/argon2_cffi_bindings-25.1.0-cp314-cp314t-win_arm64.whl", hash = "sha256:87c33a52407e4c41f3b70a9c2d3f6056d88b10dad7695be708c5021673f55623", size = 28231, upload-time = "2025-07-30T10:01:49.92Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/1d/57/96b8b9f93166147826da5f90376e784a10582dd39a393c99bb62cfcf52f0/argon2_cffi_bindings-25.1.0-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:aecba1723ae35330a008418a91ea6cfcedf6d31e5fbaa056a166462ff066d500", size = 54121, upload-time = "2025-07-30T10:01:50.815Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0a/08/a9bebdb2e0e602dde230bdde8021b29f71f7841bd54801bcfd514acb5dcf/argon2_cffi_bindings-25.1.0-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:2630b6240b495dfab90aebe159ff784d08ea999aa4b0d17efa734055a07d2f44", size = 29177, upload-time = "2025-07-30T10:01:51.681Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b6/02/d297943bcacf05e4f2a94ab6f462831dc20158614e5d067c35d4e63b9acb/argon2_cffi_bindings-25.1.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:7aef0c91e2c0fbca6fc68e7555aa60ef7008a739cbe045541e438373bc54d2b0", size = 31090, upload-time = "2025-07-30T10:01:53.184Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c1/93/44365f3d75053e53893ec6d733e4a5e3147502663554b4d864587c7828a7/argon2_cffi_bindings-25.1.0-cp39-abi3-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1e021e87faa76ae0d413b619fe2b65ab9a037f24c60a1e6cc43457ae20de6dc6", size = 81246, upload-time = "2025-07-30T10:01:54.145Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/09/52/94108adfdd6e2ddf58be64f959a0b9c7d4ef2fa71086c38356d22dc501ea/argon2_cffi_bindings-25.1.0-cp39-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d3e924cfc503018a714f94a49a149fdc0b644eaead5d1f089330399134fa028a", size = 87126, upload-time = "2025-07-30T10:01:55.074Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/72/70/7a2993a12b0ffa2a9271259b79cc616e2389ed1a4d93842fac5a1f923ffd/argon2_cffi_bindings-25.1.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:c87b72589133f0346a1cb8d5ecca4b933e3c9b64656c9d175270a000e73b288d", size = 80343, upload-time = "2025-07-30T10:01:56.007Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/78/9a/4e5157d893ffc712b74dbd868c7f62365618266982b64accab26bab01edc/argon2_cffi_bindings-25.1.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1db89609c06afa1a214a69a462ea741cf735b29a57530478c06eb81dd403de99", size = 86777, upload-time = "2025-07-30T10:01:56.943Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/74/cd/15777dfde1c29d96de7f18edf4cc94c385646852e7c7b0320aa91ccca583/argon2_cffi_bindings-25.1.0-cp39-abi3-win32.whl", hash = "sha256:473bcb5f82924b1becbb637b63303ec8d10e84c8d241119419897a26116515d2", size = 27180, upload-time = "2025-07-30T10:01:57.759Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e2/c6/a759ece8f1829d1f162261226fbfd2c6832b3ff7657384045286d2afa384/argon2_cffi_bindings-25.1.0-cp39-abi3-win_amd64.whl", hash = "sha256:a98cd7d17e9f7ce244c0803cad3c23a7d379c301ba618a5fa76a67d116618b98", size = 31715, upload-time = "2025-07-30T10:01:58.56Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/42/b9/f8d6fa329ab25128b7e98fd83a3cb34d9db5b059a9847eddb840a0af45dd/argon2_cffi_bindings-25.1.0-cp39-abi3-win_arm64.whl", hash = "sha256:b0fdbcf513833809c882823f98dc2f931cf659d9a1429616ac3adebb49f5db94", size = 27149, upload-time = "2025-07-30T10:01:59.329Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "certifi"
|
||||
version = "2026.5.20"
|
||||
@@ -1083,6 +1128,7 @@ name = "service"
|
||||
version = "0.1.0"
|
||||
source = { virtual = "." }
|
||||
dependencies = [
|
||||
{ name = "argon2-cffi" },
|
||||
{ name = "cryptography" },
|
||||
{ name = "dotenv" },
|
||||
{ name = "fastapi" },
|
||||
@@ -1103,6 +1149,7 @@ dependencies = [
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
{ name = "argon2-cffi", specifier = "~=25.1.0" },
|
||||
{ name = "cryptography", specifier = "~=42.0.0" },
|
||||
{ name = "dotenv", specifier = ">=0.9.9" },
|
||||
{ name = "fastapi", specifier = "~=0.115.0" },
|
||||
@@ -1265,7 +1312,8 @@ name = "torch"
|
||||
version = "2.12.0"
|
||||
source = { registry = "https://download.pytorch.org/whl/cpu" }
|
||||
resolution-markers = [
|
||||
"sys_platform == 'darwin'",
|
||||
"python_full_version >= '3.14' and sys_platform == 'darwin'",
|
||||
"python_full_version < '3.14' and sys_platform == 'darwin'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "filelock", marker = "sys_platform == 'darwin'" },
|
||||
@@ -1289,7 +1337,8 @@ name = "torch"
|
||||
version = "2.12.0+cpu"
|
||||
source = { registry = "https://download.pytorch.org/whl/cpu" }
|
||||
resolution-markers = [
|
||||
"sys_platform != 'darwin'",
|
||||
"python_full_version >= '3.14' and sys_platform != 'darwin'",
|
||||
"python_full_version < '3.14' and sys_platform != 'darwin'",
|
||||
]
|
||||
dependencies = [
|
||||
{ name = "filelock", marker = "sys_platform != 'darwin'" },
|
||||
|
||||
Reference in New Issue
Block a user