Spaces:
Running on T4
Running on T4
Download backend/app/modules/auth/service.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 9.06 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/app/modules/auth/service.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/backend/app/modules/auth/service.py
-
curl -L -o service.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/backend/app/modules/auth/service.py
9.06 kB
| """Registration, password and social sign-in, refresh-token rotation and the password reset flow.""" | |
| import logging | |
| import uuid | |
| from collections.abc import Awaitable, Callable | |
| from datetime import UTC, datetime, timedelta | |
| from functools import lru_cache | |
| from sqlalchemy.exc import IntegrityError | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from app.core.config import get_settings | |
| from app.core.errors import Conflict, Unauthenticated, ValidationFailed | |
| from app.core.rate_limit import RateLimiter | |
| from app.core.security import create_access_token, hash_password, hash_token, new_opaque_token, verify_password | |
| from app.integrations.email import EmailClient | |
| from app.integrations.social_auth import InvalidSocialToken, SocialTokenVerifier | |
| from app.modules.accounts.models import Account | |
| from app.modules.accounts.schemas import UserOut | |
| from app.modules.auth.repository import ( | |
| AuthAccountRepository, | |
| AuthIdentityRepository, | |
| PasswordResetRepository, | |
| RefreshTokenRepository, | |
| ) | |
| from app.modules.auth.schemas import AuthOut, SocialAuthOut, TokensOut | |
| log = logging.getLogger(__name__) | |
| def _dummy_hash() -> str: | |
| return hash_password("timing-equaliser-password") | |
| def _email_taken() -> Conflict: | |
| return Conflict("An account with this email already exists.", code="EMAIL_TAKEN") | |
| def _token_revoked() -> Unauthenticated: | |
| return Unauthenticated("Your session has ended. Please sign in again.", code="TOKEN_REVOKED") | |
| def _invalid_token(message: str = "We couldn't verify that sign-in. Please try again.") -> Unauthenticated: | |
| return Unauthenticated(message, code="INVALID_TOKEN") | |
| class AuthService: | |
| def __init__(self, db: AsyncSession, limiter: RateLimiter, email: EmailClient | None = None, | |
| verifier: SocialTokenVerifier | None = None): | |
| self.db = db | |
| self.limiter = limiter | |
| self.email = email | |
| self.verifier = verifier | |
| self.accounts = AuthAccountRepository(db) | |
| self.refresh_tokens = RefreshTokenRepository(db) | |
| self.resets = PasswordResetRepository(db) | |
| self.identities = AuthIdentityRepository(db) | |
| # Sign-up and sign-in | |
| async def register(self, email: str, password: str, role: str) -> AuthOut: | |
| if await self.accounts.by_email(email): | |
| raise _email_taken() | |
| account = await self._create_account(email=email, password_hash=hash_password(password), role=role) | |
| return await self._auth_body(account) | |
| async def login(self, email: str, password: str, client_ip: str) -> AuthOut: | |
| """Only failed attempts count. Limits are per (email, IP) and per IP, never per email alone, | |
| so failing logins from elsewhere cannot lock the real user out of their account.""" | |
| email = email.strip().lower() | |
| keys = (f"login:email_ip:{email}:{client_ip}", f"login:ip:{client_ip}") | |
| self.limiter.check(*keys) | |
| account = await self.accounts.by_email(email) | |
| valid = verify_password(password, account.password_hash if account else _dummy_hash()) | |
| if account is None or not valid: | |
| self.limiter.record(*keys) | |
| raise Unauthenticated("Wrong email or password.", code="INVALID_CREDENTIALS") | |
| return await self._auth_body(account) | |
| async def social(self, provider: str, id_token: str, role: str) -> SocialAuthOut: | |
| assert self.verifier is not None | |
| try: | |
| identity = await self.verifier.verify(provider, id_token) | |
| except InvalidSocialToken as exc: | |
| log.info("social token rejected: provider=%s reason=%s", provider, exc) | |
| raise _invalid_token() from exc | |
| is_new = False | |
| linked = await self.identities.first_by(provider=provider, subject=identity.subject) | |
| account = await self.accounts.get(linked.account_id) if linked else None | |
| if account is None: | |
| if not identity.email or not identity.email_verified: | |
| raise _invalid_token("This sign-in did not share a verified email address.") | |
| email = identity.email.strip().lower() | |
| account = await self.accounts.by_email(email) | |
| if account is None: | |
| account = await self._create_account(email=email, password_hash=None, role=role) | |
| is_new = True | |
| await self.identities.create(account_id=account.id, provider=provider, subject=identity.subject) | |
| body = await self._auth_body(account) | |
| return SocialAuthOut(user=body.user, tokens=body.tokens, is_new=is_new) | |
| # Refresh tokens | |
| async def refresh(self, refresh_token: str) -> TokensOut: | |
| now = datetime.now(UTC) | |
| token = await self.refresh_tokens.by_hash_for_update(hash_token(refresh_token)) | |
| if token is None: | |
| raise _token_revoked() | |
| if token.revoked_at is not None: | |
| # A revoked token was replayed: assume theft and end the whole sign-in. Commit before raising, | |
| # because the request's unit of work rolls back on errors. | |
| await self.refresh_tokens.revoke_family(token.family_id, now) | |
| await self.db.commit() | |
| raise _token_revoked() | |
| if token.expires_at <= now: | |
| raise _token_revoked() | |
| await self.refresh_tokens.update(token, revoked_at=now) | |
| return await self._issue_tokens(token.account_id, token.family_id) | |
| async def logout(self, account: Account, refresh_token: str) -> None: | |
| token = await self.refresh_tokens.by_hash_for_update(hash_token(refresh_token)) | |
| if token is not None and token.account_id == account.id and token.revoked_at is None: | |
| await self.refresh_tokens.update(token, revoked_at=datetime.now(UTC)) | |
| # Password reset | |
| async def forgot_password(self, email: str, client_ip: str) -> Callable[[], Awaitable[None]] | None: | |
| """Always succeeds from the caller's view so the endpoint cannot be used to find accounts. | |
| Returns the email job for the controller to run after the response, so known and unknown | |
| addresses answer in the same time. | |
| """ | |
| self.limiter.hit(f"forgot:email:{email}", f"forgot:ip:{client_ip}") | |
| account = await self.accounts.by_email(email) | |
| if account is None or not account.password_hash or self.email is None: | |
| return None | |
| settings = get_settings() | |
| token = new_opaque_token() | |
| await self.resets.create(account_id=account.id, token_hash=hash_token(token), | |
| expires_at=datetime.now(UTC) + timedelta(seconds=settings.password_reset_ttl_s)) | |
| minutes = settings.password_reset_ttl_s // 60 | |
| link = f"{settings.password_reset_url}?token={token}" | |
| sender, to = self.email, account.email | |
| async def send() -> None: | |
| try: | |
| await sender.send( | |
| to, "Reset your Cognivision password", | |
| f"Someone asked to reset the password for this account.\n\nSet a new password here: {link}\n\n" | |
| f"The link works once and expires in {minutes} minutes. If it wasn't you, ignore this email.", | |
| ) | |
| except Exception: # the reset row stays; the user can ask again | |
| log.exception("password reset email failed") | |
| return send | |
| async def reset_password(self, token: str, password: str) -> None: | |
| now = datetime.now(UTC) | |
| reset = await self.resets.by_hash_for_update(hash_token(token)) | |
| if reset is None or reset.used_at is not None or reset.expires_at <= now: | |
| raise ValidationFailed("This reset link is invalid or has expired.", code="TOKEN_INVALID") | |
| account = await self.accounts.get_or_404(reset.account_id) | |
| await self.resets.update(reset, used_at=now) | |
| await self.accounts.update(account, password_hash=hash_password(password)) | |
| await self.refresh_tokens.revoke_all(account.id, now) | |
| # Helpers | |
| async def _create_account(self, **values) -> Account: | |
| try: | |
| async with self.db.begin_nested(): | |
| return await self.accounts.create(**values) | |
| except IntegrityError as exc: # a concurrent sign-up took the email | |
| raise _email_taken() from exc | |
| async def _issue_tokens(self, account_id: uuid.UUID, family_id: uuid.UUID | None = None) -> TokensOut: | |
| refresh = new_opaque_token() | |
| await self.refresh_tokens.create( | |
| account_id=account_id, token_hash=hash_token(refresh), family_id=family_id or uuid.uuid4(), | |
| expires_at=datetime.now(UTC) + timedelta(days=get_settings().refresh_token_ttl_days)) | |
| access, expires_in = create_access_token(account_id) | |
| return TokensOut(access_token=access, refresh_token=refresh, expires_in=expires_in) | |
| async def _auth_body(self, account: Account) -> AuthOut: | |
| team_code = await self.accounts.team_code(account.team_id) if account.role == "player" else None | |
| return AuthOut(user=UserOut.build(account, team_code), tokens=await self._issue_tokens(account.id)) | |