Files
sales-trainer/backend/app/auth/users.py
T

575 lines
23 KiB
Python

"""User + organization store and auth logic (JWT, password hashing, roles).
Login identity is the user's `username` (stable id). `email` is an optional
separate field that admins/users can set; the default admin must set an email
+before first real use (enforced via `must_setup`).
"""
from __future__ import annotations
import datetime
import math
import re
from pathlib import Path
from typing import Any, TypeGuard
import jwt
from werkzeug.security import check_password_hash, generate_password_hash
from ..config import Config
from ..storage.store import (
JsonStore,
StoreError,
contains_control_characters,
new_id,
)
EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
USERNAME_RE = re.compile(r"^[a-zA-Z0-9_.-]{2,64}$")
MAX_LOGIN_IDENTIFIER_LENGTH = 254
_UNSET = object()
PUBLIC_USER_FIELDS = (
"id",
"username",
"email",
"org_id",
"org_name",
"name",
"role",
"must_setup",
"created_at",
"active",
"accepted_terms",
"accepted_terms_at",
)
class AuthError(Exception):
pass
class SetupAlreadyCompletedError(AuthError):
"""Raised when setup is attempted after the one-time transition."""
pass
def is_valid_tenant_id(value: object) -> TypeGuard[str]:
"""Accept only canonical, nonblank tenant identifiers."""
if (
not isinstance(value, str)
or not value
or len(value) > 200
or value != value.strip()
or "/" in value
or "\\" in value
or value == "."
or ".." in value
or contains_control_characters(value)
):
return False
try:
if len(value.encode("utf-8")) > 200:
return False
except UnicodeError:
return False
return True
def normalize_identifier(value: object) -> str:
"""Normalize a login/storage identifier without allowing unsafe path input."""
if not isinstance(value, str):
raise AuthError("invalid identifier")
normalized = value.strip().lower()
if (
not normalized
or len(normalized) > MAX_LOGIN_IDENTIFIER_LENGTH
or "/" in normalized
or "\\" in normalized
or ".." in normalized
or contains_control_characters(normalized)
):
raise AuthError("invalid identifier")
try:
if len(normalized.encode("utf-8")) > 200:
raise AuthError("invalid identifier")
except UnicodeError as exc:
raise AuthError("invalid identifier") from exc
return normalized
class UserStore:
def __init__(self, data_dir: Path) -> None:
self.users = JsonStore(data_dir / "users")
self.orgs = JsonStore(data_dir / "orgs")
# ── org ────────────────────────────────────────────────────────────
def create_org(self, name: str, *, org_id: str | None = None) -> dict[str, Any]:
oid = new_id("org") if org_id is None else org_id
if not is_valid_tenant_id(oid):
raise AuthError("invalid organization id")
return self.orgs.create(
{
"name": name,
"id": oid,
"plan": "trial",
"seats": 5,
"active": True,
"created_at": __import__("time").strftime("%Y-%m-%dT%H:%M:%SZ"),
},
key=oid,
)
def get_org(self, org_id: str) -> dict[str, Any]:
return self.orgs.get(org_id)
def get_org_or_none(self, org_id: str | None) -> dict[str, Any] | None:
"""Return an organization without turning a missing tenant into a default."""
if not is_valid_tenant_id(org_id):
return None
return self.orgs.get_or_none(org_id)
# ── users ──────────────────────────────────────────────────────────
@staticmethod
def _norm(username: str) -> str:
try:
return normalize_identifier(username)
except AuthError as exc:
raise AuthError("invalid username") from exc
@staticmethod
def validate_password(password: object) -> str:
"""Validate credentials before any caller performs a mutation."""
if not isinstance(password, str) or not password:
raise AuthError("password is required")
if len(password) < Config.MIN_PASSWORD_LENGTH:
raise AuthError(
f"password must be at least {Config.MIN_PASSWORD_LENGTH} characters"
)
return password
@staticmethod
def _next_auth_version(user: dict[str, Any]) -> int:
"""Return the next session version for password-bearing mutations."""
return UserStore._auth_version(user) + 1
@staticmethod
def _auth_version(user: dict[str, Any]) -> int:
if "auth_version" not in user:
return 0 # Legacy records without the field use the initial version.
current = user.get("auth_version")
if isinstance(current, bool) or not isinstance(current, int) or current < 0:
raise AuthError("invalid account state")
return current
@staticmethod
def _password_matches(password_hash: object, password: str) -> bool:
"""Treat malformed persisted hashes as invalid credentials, never 500."""
if not isinstance(password_hash, str) or not password_hash:
return False
try:
return check_password_hash(password_hash, password)
except (TypeError, ValueError):
return False
@staticmethod
def _token_identity(user: dict[str, Any]) -> tuple[str, str, str]:
username = user.get("username")
user_id = user.get("id")
org_id = user.get("org_id")
role = user.get("role")
try:
normalized_username = normalize_identifier(username)
normalized_user_id = normalize_identifier(user_id)
except AuthError as exc:
raise AuthError("invalid account state") from exc
if (
not isinstance(username, str)
or not username.strip()
or USERNAME_RE.fullmatch(username) is None
or normalized_username != username
or not isinstance(user_id, str)
or not user_id.strip()
or normalized_user_id != user_id
or user_id != username
or not is_valid_tenant_id(org_id)
or not isinstance(role, str)
or role not in Config.ROLES
):
raise AuthError("invalid account state")
persisted_email = user.get("email")
if persisted_email is not None:
try:
canonical_email = UserStore.validate_email(
persisted_email, allow_empty=False
)
except AuthError as exc:
raise AuthError("invalid account state") from exc
if canonical_email != persisted_email:
raise AuthError("invalid account state")
return username, org_id, role
def validate_persisted_identity(self, user: dict[str, Any]) -> None:
"""Fail closed when an existing account record loses canonical identity."""
self._token_identity(user)
@staticmethod
def validate_email(email: object, *, allow_empty: bool = True) -> str | None:
"""Normalize an email and reject malformed/non-string values safely."""
if email is None or (isinstance(email, str) and not email.strip()):
if allow_empty:
return None
raise AuthError("invalid email")
if not isinstance(email, str):
raise AuthError("invalid email")
try:
normalized = normalize_identifier(email)
except AuthError as exc:
raise AuthError("invalid email") from exc
if not EMAIL_RE.fullmatch(normalized):
raise AuthError("invalid email")
return normalized
def create_user(
self,
*,
org_id: str,
username: str,
password: str,
name: str,
role: str = "user",
email: str | None = None,
must_setup: bool = False,
) -> dict[str, Any]:
if not is_valid_tenant_id(org_id):
raise AuthError("invalid organization id")
if not isinstance(role, str) or role not in Config.ROLES:
raise AuthError(f"invalid role: {role}")
if not isinstance(must_setup, bool):
raise AuthError("must_setup must be boolean")
username = self._norm(username)
if not username or not password:
raise AuthError("username and password are required")
password = self.validate_password(password)
if USERNAME_RE.fullmatch(username) is None:
raise AuthError("invalid username (letters/numbers/._- only, 2-64 chars)")
if not isinstance(name, str):
raise AuthError("name must be a string")
email = self.validate_email(email)
# Username/email uniqueness and seat capacity are collection-wide
# invariants. Keep their checks with the create so setup/profile writes
# cannot reserve the same email concurrently in another worker.
# Seat capacity and org activation must share a lock with org updates;
# otherwise an admin can deactivate/shrink a tenant between this check
# and the user write.
try:
with self.orgs.record_lock(org_id):
org = self.orgs.get_or_none(org_id)
if org is None:
raise AuthError("organization not found")
if org.get("active") is not True:
raise AuthError("organization is inactive")
raw_seats = org.get("seats", 5)
if type(raw_seats) is not int or raw_seats < 0:
raise AuthError("invalid organization state")
seats = raw_seats
if seats <= 0:
raise AuthError("organization has no available seats")
with self.users.collection_lock():
existing = [u for u in self.users.all() if u.get("org_id") == org_id]
if len(existing) >= seats:
raise AuthError("organization seat limit reached")
if self.users.get_or_none(username) is not None:
raise AuthError("a user with this username already exists")
if email and self.email_exists(email):
raise AuthError("a user with this email already exists")
user = {
"id": username,
"username": username,
"email": email,
"org_id": org_id,
"org_name": org.get("name", ""),
"name": name.strip() or username,
"password_hash": generate_password_hash(password),
"role": role,
"must_setup": must_setup,
"auth_version": 0,
"created_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
"active": True,
}
return self.users.create(user, key=username)
except AuthError:
raise
except (OSError, StoreError, TypeError, UnicodeError, ValueError, OverflowError) as exc:
raise AuthError("account storage unavailable") from exc
def get_user(self, username: str) -> dict[str, Any]:
return self.users.get(self._norm(username))
def get_user_or_none(self, username: str) -> dict[str, Any] | None:
return self.users.get_or_none(self._norm(username))
def by_email(self, email: object) -> dict[str, Any] | None:
email = self.validate_email(email)
if email is None:
return None
for u in self.users.all():
stored_email = u.get("email")
if stored_email is None:
continue
try:
canonical_email = self.validate_email(stored_email, allow_empty=False)
except AuthError as exc:
raise AuthError("invalid account state") from exc
if canonical_email != stored_email:
raise AuthError("invalid account state")
if canonical_email == email:
return u
return None
def email_exists(self, email: str) -> bool:
return self.by_email(email) is not None
def list_users(self, *, org_id: str | None = None) -> list[dict[str, Any]]:
if org_id is not None and not is_valid_tenant_id(org_id):
return []
users = self.users.all()
if org_id is None:
return [self.public_user(user) for user in users]
users = [u for u in users if u.get("org_id") == org_id]
return [self.public_user(user) for user in users]
def set_active(self, username: str, active: bool) -> dict[str, Any]:
return self.update_user_fields(username, active=active)
def set_role(self, username: str, role: str) -> dict[str, Any]:
return self.update_user_fields(username, role=role)
def set_password(self, username: str, new_password: str) -> dict[str, Any]:
return self.update_user_fields(username, password=new_password)
def change_password(
self,
username: str,
current_password: object,
new_password: object,
) -> dict[str, Any]:
"""Change one user's password after verifying the current password."""
username = self._norm(username)
if not isinstance(current_password, str) or not current_password:
raise AuthError("current password is invalid")
new_password = self.validate_password(new_password)
with self.users.record_lock(username):
current = self.users.get_or_none(username)
if current is None or current.get("active") is not True:
raise AuthError("current password is invalid")
if not self._password_matches(current.get("password_hash"), current_password):
raise AuthError("current password is invalid")
return self.users.update(
username,
password_hash=generate_password_hash(new_password),
auth_version=self._next_auth_version(current),
)
def set_email(self, username: str, email: str) -> dict[str, Any]:
return self.update_user_fields(username, email=email)
def set_name(self, username: str, name: str) -> dict[str, Any]:
return self.update_user_fields(username, name=name)
def update_user_fields(
self,
username: str,
*,
name: object = _UNSET,
email: object = _UNSET,
password: object = _UNSET,
role: object = _UNSET,
active: object = _UNSET,
) -> dict[str, Any]:
"""Validate and apply related user fields as one locked mutation."""
username = self._norm(username)
fields: dict[str, Any] = {}
if name is not _UNSET:
if not isinstance(name, str) or not name.strip():
raise AuthError("name is required")
fields["name"] = name.strip()
normalized_email: str | None = None
if email is not _UNSET:
normalized_email = self.validate_email(email, allow_empty=False)
if normalized_email is None: # defensive: required email validation above
raise AuthError("invalid email")
fields["email"] = normalized_email
if password is not _UNSET:
password = self.validate_password(password)
fields["password_hash"] = generate_password_hash(password)
if role is not _UNSET:
if not isinstance(role, str) or role not in Config.ROLES:
raise AuthError("invalid role")
fields["role"] = role
if active is not _UNSET:
if not isinstance(active, bool):
raise AuthError("active must be a boolean")
fields["active"] = active
with self.users.collection_lock():
with self.users.record_lock(username):
current = self.users.get_or_none(username)
if current is None:
raise AuthError("user not found")
if normalized_email is not None:
existing = self.by_email(normalized_email)
if existing and existing["id"] != username:
raise AuthError("a user with this email already exists")
if password is not _UNSET or role is not _UNSET or active is not _UNSET:
fields["auth_version"] = self._next_auth_version(current)
if not fields:
return current
return self.users.update(username, **fields)
def complete_setup(
self,
username: str,
email: str,
new_password: str,
*,
accepted_terms: object,
accepted_terms_at: str,
) -> dict[str, Any]:
"""Complete setup for a user that is still marked ``must_setup``.
Keep the setup fields in one store update so a caller cannot leave an
account half-configured after changing only its email or password.
"""
username = self._norm(username)
if accepted_terms is not True:
raise AuthError("terms acceptance is required")
new_password = self.validate_password(new_password)
email = self.validate_email(email, allow_empty=False)
if email is None: # defensive: required email validation above
raise AuthError("invalid email")
password_hash = generate_password_hash(new_password)
with self.users.collection_lock():
with self.users.record_lock(username):
current = self.users.get_or_none(username)
if current is None:
raise AuthError("user not found")
if current.get("must_setup") is not True:
raise SetupAlreadyCompletedError("setup already completed")
existing = self.by_email(email)
if existing and existing["id"] != username:
raise AuthError("a user with this email already exists")
updated = self.users.update_if(
username,
lambda latest: latest.get("must_setup") is True,
email=email,
password_hash=password_hash,
must_setup=False,
accepted_terms=True,
accepted_terms_at=accepted_terms_at,
auth_version=self._next_auth_version(current),
)
if updated is None:
raise SetupAlreadyCompletedError("setup already completed")
return updated
# ── auth ───────────────────────────────────────────────────────────
def verify(self, ident: str, password: str) -> dict[str, Any]:
# Resolve by EITHER username OR email (the login form doesn't distinguish,
# and users naturally type their email after setup). Fall back to username.
if not isinstance(ident, str) or not isinstance(password, str):
raise AuthError("invalid credentials")
try:
normalized_ident = normalize_identifier(ident)
except AuthError as exc:
raise AuthError("invalid credentials") from exc
try:
user = self.get_user_or_none(normalized_ident) or self.by_email(normalized_ident)
except (AuthError, OSError, StoreError, TypeError, UnicodeError, ValueError) as exc:
raise AuthError("invalid credentials") from exc
if not user or user.get("active") is not True:
raise AuthError("invalid credentials")
if not isinstance(user.get("must_setup"), bool):
raise AuthError("invalid credentials")
# SaaS gate: orphaned or inactive organizations cannot sign in.
if not isinstance(user.get("role"), str) or user.get("role") not in Config.ROLES:
raise AuthError("invalid credentials")
oid = user.get("org_id")
try:
org = self.get_org_or_none(oid)
except (OSError, StoreError, TypeError, UnicodeError, ValueError) as exc:
raise AuthError("invalid credentials") from exc
if not org or org.get("active") is not True:
raise AuthError("invalid credentials")
try:
self._auth_version(user)
except AuthError as exc:
raise AuthError("invalid credentials") from exc
try:
self._token_identity(user)
except AuthError as exc:
raise AuthError("invalid credentials") from exc
if not self._password_matches(user.get("password_hash"), password):
raise AuthError("invalid credentials")
return user
def issue_token(self, user: dict[str, Any]) -> str:
now = datetime.datetime.now(datetime.timezone.utc)
subject, org_id, role = self._token_identity(user)
if user.get("active") is not True:
raise AuthError("invalid account state")
payload = {
"sub": subject,
"org_id": org_id,
"role": role,
"auth_version": self._auth_version(user),
"iat": now,
"exp": now + datetime.timedelta(hours=Config.JWT_EXPIRES_HOURS),
}
return jwt.encode(payload, Config.SECRET_KEY, algorithm=Config.JWT_ALGO)
def decode_token(self, token: str) -> dict[str, Any]:
try:
payload = jwt.decode(
token,
Config.SECRET_KEY,
algorithms=[Config.JWT_ALGO],
options={"require": ["sub", "org_id", "role", "auth_version", "iat", "exp"]},
)
if not isinstance(payload, dict):
raise AuthError("invalid or expired token")
subject = payload.get("sub")
try:
normalized_subject = normalize_identifier(subject)
except AuthError as exc:
raise AuthError("invalid or expired token") from exc
if (
not isinstance(subject, str)
or normalized_subject != subject
or USERNAME_RE.fullmatch(subject) is None
or not is_valid_tenant_id(payload.get("org_id"))
or not isinstance(payload.get("role"), str)
or payload["role"] not in Config.ROLES
or isinstance(payload.get("auth_version"), bool)
or not isinstance(payload.get("auth_version"), int)
or payload["auth_version"] < 0
or isinstance(payload.get("iat"), bool)
or not isinstance(payload.get("iat"), (int, float))
or not math.isfinite(payload["iat"])
or isinstance(payload.get("exp"), bool)
or not isinstance(payload.get("exp"), (int, float))
or not math.isfinite(payload["exp"])
or payload["iat"] >= payload["exp"]
):
raise AuthError("invalid or expired token")
return payload
except AuthError:
raise
except (jwt.PyJWTError, OverflowError, TypeError, ValueError) as exc:
raise AuthError("invalid or expired token") from exc
def public_user(self, user: dict[str, Any]) -> dict[str, Any]:
return {
field: user[field]
for field in PUBLIC_USER_FIELDS
if field in user
}