diff options
| author | stuppie | 2026-08-31 16:52:15 -0600 |
|---|---|---|
| committer | stuppie | 2026-08-31 16:52:15 -0600 |
| commit | 3f8d178d38686c1a5d71d94ebccdb61701469e95 (patch) | |
| tree | 435707789cc0d1eb3c8670e4ab4bbae11d773285 /jb/models/auth.py | |
| parent | 12f6fee851b68e86af658dfa17e4a0daed457dd1 (diff) | |
| download | amt-jb-3f8d178d38686c1a5d71d94ebccdb61701469e95.tar.gz amt-jb-3f8d178d38686c1a5d71d94ebccdb61701469e95.zip | |
working on magic token and session token auth
Diffstat (limited to 'jb/models/auth.py')
| -rw-r--r-- | jb/models/auth.py | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/jb/models/auth.py b/jb/models/auth.py new file mode 100644 index 0000000..5f31bd3 --- /dev/null +++ b/jb/models/auth.py @@ -0,0 +1,65 @@ +import hashlib +import hmac + +from pydantic import ( + BaseModel, + ConfigDict, + EmailStr, + Field, + TypeAdapter, + computed_field, +) + +from jb.config import settings + + +def email_to_product_user_id(email: str) -> str: + """Return a deterministic, non-reversible product user ID for an email. + + The same normalized email and secret salt always produce the same ID. Keep + the salt private and stable; changing it changes every generated ID. + """ + salt_bytes = settings.magic_token_salt.get_secret_value().encode("utf-8") + if len(salt_bytes) < 32: + raise ValueError("salt must be at least 32 bytes") + + if not email.isascii(): + raise ValueError("email must contain ASCII characters only") + + normalized_email = str(TypeAdapter(EmailStr).validate_python(email)).lower() + return hmac.new( + key=salt_bytes, + msg=normalized_email.encode("utf-8"), + digestmod=hashlib.sha256, + ).hexdigest() + + +class AuthenticatedUser(BaseModel): + """A user that has been authenticated and exists in THL""" + + email: EmailStr = Field() + + @computed_field + def product_user_id(self) -> str: + return email_to_product_user_id(self.email) + + +class AccountCreate(BaseModel): + email: EmailStr = Field() + + +class AccountLogin(BaseModel): + email: EmailStr = Field() + + + +class MagicLinkExchangeRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + + token: str = Field(min_length=1) + + +class SessionResponse(BaseModel): + session_token: str + token_type: str = "bearer" + expires_in: int |
