askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
object_signup.py · 24.2 KB · 613 lines
| 1 | """Self-service signup, email verification and password reset. |
| 2 | |
| 3 | This module owns three things; object_server wires the browser routes |
| 4 | (/signup, /verify, /reset, /reset/confirm) to them. |
| 5 | |
| 6 | 1. One-time email tokens, in ``identity/email_tokens.tsv`` (mode 0600). |
| 7 | A token is ``secrets.token_urlsafe(32)`` and only its |
| 8 | ``object_identity.hash_token`` is stored -- the session-token pattern. |
| 9 | Each is single use and expires (verification 48 h, reset 1 h). Issuing a |
| 10 | new link for a user and purpose retires the previous one. Each is bound |
| 11 | to the user's password as it was when the link went out (a digest of the |
| 12 | stored hash, or "none"): a password set or removed after that, by anyone, |
| 13 | retires the link. |
| 14 | Bounded: every write drops used and expired rows, so the file holds at |
| 15 | most one live row per user and purpose. |
| 16 | |
| 17 | 2. The checks that decide whether signup and reset may run here. A |
| 18 | capability that is absent refuses rather than pretends: |
| 19 | - no way to send the email: refuse; |
| 20 | - no configured public address for the link: refuse. Never the request's |
| 21 | Host header, which would let anyone point a reset link at their own |
| 22 | domain; |
| 23 | - a policy that gives every signed-in user unscoped access: refuse signup. |
| 24 | That grant is fine for operator-invited users and wrong for strangers. |
| 25 | |
| 26 | 3. The account itself. A signup creates its own account and a user in the |
| 27 | ``pending`` status, which cannot log in or hold a session until the |
| 28 | emailed link is used (object_identity.PENDING_STATUS). The signup form |
| 29 | takes no password: a stranger could type someone else's address with a |
| 30 | password of their own, and the owner who clicked the link would then |
| 31 | have confirmed the stranger's login. Nor does it take a name, which the |
| 32 | stranger could make an impersonation. The password and the name are |
| 33 | chosen on the confirmation page, by whoever holds the mailbox |
| 34 | (``confirm_signup``). |
| 35 | |
| 36 | No enumeration: a signup for an address that already has an account, and a |
| 37 | reset for an address that has none, answer the person at the form exactly as |
| 38 | the ordinary case does. Only the mailbox's owner learns which it was. |
| 39 | """ |
| 40 | |
| 41 | from __future__ import annotations |
| 42 | |
| 43 | import csv |
| 44 | import hashlib |
| 45 | import hmac |
| 46 | import os |
| 47 | import re |
| 48 | import secrets |
| 49 | import threading |
| 50 | import unicodedata |
| 51 | import urllib.parse |
| 52 | from datetime import datetime, timedelta, timezone |
| 53 | from pathlib import Path |
| 54 | from typing import Any, Mapping |
| 55 | |
| 56 | import object_credentials |
| 57 | import object_email |
| 58 | import object_identity |
| 59 | import object_permissions |
| 60 | import object_schemas |
| 61 | from object_versions import DEFAULT_DATA_DIR |
| 62 | |
| 63 | SIGNUP_ENV = "DBBASIC_ENABLE_SIGNUP" |
| 64 | PASSWORD_RESET_ENV = "DBBASIC_ENABLE_PASSWORD_RESET" |
| 65 | PUBLIC_URL_ENV = "DBBASIC_PUBLIC_URL" |
| 66 | |
| 67 | VERIFY_EMAIL = "verify_email" |
| 68 | PASSWORD_RESET = "password_reset" |
| 69 | PURPOSES = frozenset({VERIFY_EMAIL, PASSWORD_RESET}) |
| 70 | TOKEN_TTL = { |
| 71 | VERIFY_EMAIL: timedelta(hours=48), |
| 72 | PASSWORD_RESET: timedelta(hours=1), |
| 73 | } |
| 74 | |
| 75 | TOKENS_FILE = "email_tokens.tsv" |
| 76 | TOKEN_FIELDS = ("token_hash", "purpose", "user_id", "email", "credential", "created_at", "expires_at", "used_at") |
| 77 | NO_CREDENTIAL = "none" |
| 78 | |
| 79 | MAX_EMAIL_LENGTH = 254 |
| 80 | MAX_DISPLAY_NAME_LENGTH = 120 |
| 81 | _EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$") |
| 82 | # control, format (zero-width, bidi), surrogate, private use, line and paragraph separators |
| 83 | _HIDDEN_CATEGORIES = frozenset({"Cc", "Cf", "Cs", "Co", "Zl", "Zp"}) |
| 84 | _TRUE_VALUES = {"1", "true", "yes", "on"} |
| 85 | _LOCAL_HOSTS = {"localhost", "127.0.0.1", "::1"} |
| 86 | |
| 87 | _TOKENS_LOCK = threading.Lock() |
| 88 | # Check-then-create for one email address is not atomic in object_identity |
| 89 | # (it locks per file, per call). One process-wide lock keeps two signups for |
| 90 | # the same address from both passing the "no account yet" check. |
| 91 | _REGISTER_LOCK = threading.Lock() |
| 92 | |
| 93 | |
| 94 | class SignupError(ValueError): |
| 95 | """A signup or reset form value the person has to fix (the message says what).""" |
| 96 | |
| 97 | |
| 98 | # -------------------------------------------------------------------------- |
| 99 | # Whether signup and reset may run |
| 100 | |
| 101 | |
| 102 | def env_enabled(name: str, env: Mapping[str, str] | None = None) -> bool: |
| 103 | env = os.environ if env is None else env |
| 104 | return (env.get(name) or "").strip().lower() in _TRUE_VALUES |
| 105 | |
| 106 | |
| 107 | def public_url(env: Mapping[str, str] | None = None) -> str | None: |
| 108 | """The configured public origin for emailed links, or None. |
| 109 | |
| 110 | Must be https, except on a local host (a developer's own machine).""" |
| 111 | env = os.environ if env is None else env |
| 112 | value = (env.get(PUBLIC_URL_ENV) or "").strip().rstrip("/") |
| 113 | if not value: |
| 114 | return None |
| 115 | parsed = urllib.parse.urlsplit(value) |
| 116 | if not parsed.netloc or parsed.query or parsed.fragment: |
| 117 | return None |
| 118 | if parsed.scheme == "https": |
| 119 | return value |
| 120 | if parsed.scheme == "http" and (parsed.hostname or "") in _LOCAL_HOSTS: |
| 121 | return value |
| 122 | return None |
| 123 | |
| 124 | |
| 125 | def email_blockers( |
| 126 | *, |
| 127 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 128 | env: Mapping[str, str] | None = None, |
| 129 | ) -> list[str]: |
| 130 | """What stops this server from emailing a link, or [] if nothing.""" |
| 131 | blockers: list[str] = [] |
| 132 | if not object_email.smtp_config_from_env(os.environ if env is None else env).configured: |
| 133 | blockers.append("Outbound email is not configured: set DBBASIC_SMTP_MODE=live and DBBASIC_SMTP_HOST (or DBBASIC_SMTP_MODE=log to test).") |
| 134 | try: |
| 135 | object_schemas.get_schema(object_email.OUTBOX_COLLECTION, base_dir=base_dir) |
| 136 | except (object_schemas.SchemaNotFoundError, OSError, ValueError): |
| 137 | blockers.append("The app-email package is not installed, so there is no outbox to queue the email in.") |
| 138 | if not object_email.email_pass_enabled(base_dir=base_dir): |
| 139 | blockers.append("Outbound email is switched off (feature flag email_enabled).") |
| 140 | if public_url(env) is None: |
| 141 | blockers.append(f"{PUBLIC_URL_ENV} is not set to this server's https address, which emailed links must use.") |
| 142 | return blockers |
| 143 | |
| 144 | |
| 145 | def unscoped_registered_rules(policy: object_permissions.PermissionPolicy) -> list[str]: |
| 146 | """Allow rules that give every signed-in user something on everything. |
| 147 | |
| 148 | A rule for the ``registered`` principal with no collection, no object and |
| 149 | no row filter applies to all data and every object -- the starter policy's |
| 150 | "signed-in users can read and run objects" is one. With open signup, |
| 151 | "signed-in" means "anyone with an email address".""" |
| 152 | found = [] |
| 153 | for rule in policy.rules: |
| 154 | if rule.effect != "allow" or rule.principal != "registered": |
| 155 | continue |
| 156 | if rule.collection or rule.object_id or rule.row_filter: |
| 157 | continue |
| 158 | actions = ", ".join(sorted(rule.actions)) |
| 159 | found.append(f"registered: {actions}" + (f" ({rule.reason})" if rule.reason else "")) |
| 160 | return found |
| 161 | |
| 162 | |
| 163 | def signup_blockers( |
| 164 | *, |
| 165 | policy: object_permissions.PermissionPolicy, |
| 166 | enforcement_enabled: bool, |
| 167 | password_login_enabled: bool, |
| 168 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 169 | env: Mapping[str, str] | None = None, |
| 170 | ) -> list[str]: |
| 171 | """Everything that keeps signup off here, or [] when it may run.""" |
| 172 | blockers: list[str] = [] |
| 173 | if not env_enabled(SIGNUP_ENV, env): |
| 174 | blockers.append(f"Signup is off: set {SIGNUP_ENV}=true.") |
| 175 | if not password_login_enabled: |
| 176 | blockers.append("Password login is off, so a new user could never sign in: set DBBASIC_ENABLE_PASSWORD_LOGIN=true.") |
| 177 | if not enforcement_enabled: |
| 178 | blockers.append("Permission enforcement is off, so a stranger's account would not be limited to their own data: set DBBASIC_ENABLE_PERMISSION_ENFORCEMENT=true.") |
| 179 | for rule in unscoped_registered_rules(policy): |
| 180 | blockers.append(f"The permission policy gives every signed-in user unscoped access ({rule}); scope or remove it before opening signup.") |
| 181 | return blockers + email_blockers(base_dir=base_dir, env=env) |
| 182 | |
| 183 | |
| 184 | def reset_blockers( |
| 185 | *, |
| 186 | password_login_enabled: bool, |
| 187 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 188 | env: Mapping[str, str] | None = None, |
| 189 | ) -> list[str]: |
| 190 | """Everything that keeps password reset off here, or [] when it may run.""" |
| 191 | blockers: list[str] = [] |
| 192 | if not env_enabled(PASSWORD_RESET_ENV, env): |
| 193 | blockers.append(f"Password reset is off: set {PASSWORD_RESET_ENV}=true.") |
| 194 | if not password_login_enabled: |
| 195 | blockers.append("Password login is off: set DBBASIC_ENABLE_PASSWORD_LOGIN=true.") |
| 196 | return blockers + email_blockers(base_dir=base_dir, env=env) |
| 197 | |
| 198 | |
| 199 | # -------------------------------------------------------------------------- |
| 200 | # One-time tokens |
| 201 | |
| 202 | |
| 203 | def tokens_path(base_dir: Path | str = DEFAULT_DATA_DIR) -> Path: |
| 204 | return Path(base_dir) / object_identity.IDENTITY_DIR / TOKENS_FILE |
| 205 | |
| 206 | |
| 207 | def issue_token( |
| 208 | purpose: str, |
| 209 | user_id: str, |
| 210 | email: str, |
| 211 | *, |
| 212 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 213 | now: datetime | None = None, |
| 214 | ) -> str: |
| 215 | """Store a new single-use token and return it raw (the only time it exists raw).""" |
| 216 | return _issue(purpose, user_id, email, base_dir=base_dir, now=now, store=True) |
| 217 | |
| 218 | |
| 219 | def issue_decoy_token( |
| 220 | purpose: str, |
| 221 | *, |
| 222 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 223 | now: datetime | None = None, |
| 224 | ) -> str: |
| 225 | """Do all the work of issue_token and store nothing: the returned token opens nothing. |
| 226 | |
| 227 | For a request whose address has no account that may have a link (a reset |
| 228 | for an unknown or disabled address). Answering it with less work than a |
| 229 | real one would let anyone time the form to learn which addresses have |
| 230 | accounts, so it runs the same steps -- a random token, its hash, the |
| 231 | credential lookup, the token file read and rewritten -- and only leaves |
| 232 | the new row out.""" |
| 233 | return _issue(purpose, _DECOY_USER_ID, "", base_dir=base_dir, now=now, store=False) |
| 234 | |
| 235 | |
| 236 | # A user id the identity store can never hold (ids may not start with "_"), so the decoy's |
| 237 | # credential lookup reads the whole credentials file and finds nothing, as an unknown id does. |
| 238 | _DECOY_USER_ID = "__no_such_user__" |
| 239 | |
| 240 | |
| 241 | def _issue( |
| 242 | purpose: str, |
| 243 | user_id: str, |
| 244 | email: str, |
| 245 | *, |
| 246 | base_dir: Path | str, |
| 247 | now: datetime | None, |
| 248 | store: bool, |
| 249 | ) -> str: |
| 250 | if purpose not in PURPOSES: |
| 251 | raise ValueError(f"Unknown token purpose: {purpose}") |
| 252 | now = now or _now() |
| 253 | token = secrets.token_urlsafe(32) |
| 254 | row = { |
| 255 | "token_hash": object_identity.hash_token(token), |
| 256 | "purpose": purpose, |
| 257 | "user_id": user_id, |
| 258 | "email": email, |
| 259 | "credential": _credential_state(user_id, base_dir), |
| 260 | "created_at": _stamp(now), |
| 261 | "expires_at": _stamp(now + TOKEN_TTL[purpose]), |
| 262 | "used_at": "", |
| 263 | } |
| 264 | path = tokens_path(base_dir) |
| 265 | with _TOKENS_LOCK: |
| 266 | rows = [ |
| 267 | r for r in _live_rows(_read_tokens(path), now) |
| 268 | if not (r["user_id"] == user_id and r["purpose"] == purpose) |
| 269 | ] |
| 270 | if store: |
| 271 | rows.append(row) |
| 272 | _write_tokens(path, rows) |
| 273 | return token |
| 274 | |
| 275 | |
| 276 | def peek_token( |
| 277 | token: str | None, |
| 278 | purpose: str, |
| 279 | *, |
| 280 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 281 | now: datetime | None = None, |
| 282 | ) -> dict[str, str] | None: |
| 283 | """The live row for a raw token, without using it up; None if not live.""" |
| 284 | if not token: |
| 285 | return None |
| 286 | row = _find_live(_read_tokens(tokens_path(base_dir)), token, purpose, now or _now()) |
| 287 | return row if row is not None and _credential_unchanged(row, base_dir) else None |
| 288 | |
| 289 | |
| 290 | def consume_token( |
| 291 | token: str | None, |
| 292 | purpose: str, |
| 293 | *, |
| 294 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 295 | now: datetime | None = None, |
| 296 | ) -> dict[str, str] | None: |
| 297 | """Use a raw token up and return its row; None if unknown, used, expired or another purpose.""" |
| 298 | if not token: |
| 299 | return None |
| 300 | now = now or _now() |
| 301 | path = tokens_path(base_dir) |
| 302 | with _TOKENS_LOCK: |
| 303 | rows = _read_tokens(path) |
| 304 | found = _find_live(rows, token, purpose, now) |
| 305 | if found is None or not _credential_unchanged(found, base_dir): |
| 306 | return None |
| 307 | found["used_at"] = _stamp(now) |
| 308 | # the used row goes too: a used token is never looked at again |
| 309 | _write_tokens(path, [r for r in _live_rows(rows, now) if r is not found]) |
| 310 | return found |
| 311 | |
| 312 | |
| 313 | def _find_live(rows: list[dict[str, str]], token: str, purpose: str, now: datetime) -> dict[str, str] | None: |
| 314 | wanted = object_identity.hash_token(token) |
| 315 | for row in rows: |
| 316 | if not hmac.compare_digest(row.get("token_hash", ""), wanted): |
| 317 | continue |
| 318 | if row.get("purpose") != purpose or row.get("used_at"): |
| 319 | return None |
| 320 | try: |
| 321 | if _parse(row["expires_at"]) <= now: |
| 322 | return None |
| 323 | except (KeyError, ValueError): |
| 324 | return None |
| 325 | return row |
| 326 | return None |
| 327 | |
| 328 | |
| 329 | def _credential_state(user_id: str, base_dir: Path | str) -> str: |
| 330 | """The user's password as a link is bound to it: a digest of the stored hash (new salt on every set), |
| 331 | or NO_CREDENTIAL. Never the hash itself, which stays in credentials.tsv.""" |
| 332 | stored = object_credentials._find_credential(user_id.strip(), base_dir=base_dir) |
| 333 | if stored is None: |
| 334 | return NO_CREDENTIAL |
| 335 | return "sha256:" + hashlib.sha256(stored.password_hash.encode("utf-8")).hexdigest() |
| 336 | |
| 337 | |
| 338 | def _credential_unchanged(row: Mapping[str, str], base_dir: Path | str) -> bool: |
| 339 | """False when the password was set or removed since the link went out, or the row predates binding.""" |
| 340 | bound = row.get("credential") or "" |
| 341 | if not bound: |
| 342 | return False |
| 343 | return hmac.compare_digest(bound.encode("utf-8"), _credential_state(row.get("user_id") or "", base_dir).encode("utf-8")) |
| 344 | |
| 345 | |
| 346 | def _live_rows(rows: list[dict[str, str]], now: datetime) -> list[dict[str, str]]: |
| 347 | live = [] |
| 348 | for row in rows: |
| 349 | if row.get("used_at"): |
| 350 | continue |
| 351 | try: |
| 352 | if _parse(row["expires_at"]) <= now: |
| 353 | continue |
| 354 | except (KeyError, ValueError): |
| 355 | continue |
| 356 | live.append(row) |
| 357 | return live |
| 358 | |
| 359 | |
| 360 | def _read_tokens(path: Path) -> list[dict[str, str]]: |
| 361 | if not path.exists(): |
| 362 | return [] |
| 363 | with path.open(newline="") as handle: |
| 364 | return [dict(row) for row in csv.DictReader(handle, delimiter="\t") if row] |
| 365 | |
| 366 | |
| 367 | def _write_tokens(path: Path, rows: list[dict[str, str]]) -> None: |
| 368 | path.parent.mkdir(parents=True, exist_ok=True) |
| 369 | temp = path.with_name(f".{path.name}.tmp") |
| 370 | fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) |
| 371 | with os.fdopen(fd, "w", newline="") as handle: |
| 372 | writer = csv.DictWriter(handle, fieldnames=TOKEN_FIELDS, delimiter="\t", extrasaction="ignore") |
| 373 | writer.writeheader() |
| 374 | for row in rows: |
| 375 | writer.writerow(row) |
| 376 | os.chmod(temp, 0o600) |
| 377 | temp.replace(path) |
| 378 | |
| 379 | |
| 380 | # -------------------------------------------------------------------------- |
| 381 | # Accounts |
| 382 | |
| 383 | |
| 384 | def normalize_email(value: str | None) -> str: |
| 385 | """The address as typed, trimmed, once it looks like one; SignupError otherwise. |
| 386 | |
| 387 | An address with a control character or an invisible format character |
| 388 | (zero-width space or joiner, a bidi override, a soft hyphen) is refused: |
| 389 | those make one address display as another. Lookalike forms that Unicode |
| 390 | NFKC folds together are not refused here but matched as one address |
| 391 | (object_identity.email_key).""" |
| 392 | email = (value or "").strip() |
| 393 | if len(email) > MAX_EMAIL_LENGTH or not _EMAIL_RE.match(email): |
| 394 | raise SignupError("Enter a valid email address.") |
| 395 | if any(unicodedata.category(char) in _HIDDEN_CATEGORIES for char in email): |
| 396 | raise SignupError("That email address has an invisible or control character in it. Type it again.") |
| 397 | return email |
| 398 | |
| 399 | |
| 400 | def check_password(password: str | None) -> str: |
| 401 | password = password or "" |
| 402 | if len(password) < object_credentials.MIN_PASSWORD_LENGTH: |
| 403 | raise SignupError(f"Use at least {object_credentials.MIN_PASSWORD_LENGTH} characters for the password.") |
| 404 | if len(password) > object_credentials.MAX_PASSWORD_LENGTH: |
| 405 | raise SignupError("That password is too long.") |
| 406 | return password |
| 407 | |
| 408 | |
| 409 | def register( |
| 410 | email: str, |
| 411 | *, |
| 412 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 413 | now: datetime | None = None, |
| 414 | ) -> dict[str, Any]: |
| 415 | """Create a pending user, with no password and no name, in a new account, unless the address already has one. |
| 416 | |
| 417 | Returns ``{"outcome": "created" | "pending" | "exists", "user": {...}}``. |
| 418 | "pending": the address signed up before and never confirmed (send the |
| 419 | link again). "exists": it has an account (tell the mailbox, not the form). |
| 420 | """ |
| 421 | email = normalize_email(email) |
| 422 | with _REGISTER_LOCK: |
| 423 | # every spelling of the address counts, lookalike forms included: an address that folds to one an |
| 424 | # existing user has is that user's, and gets the "already has an account" email, not a second account |
| 425 | existing = object_identity.find_users_by_address(email, base_dir=base_dir) |
| 426 | if existing: |
| 427 | pending = [u for u in existing if u["status"] == object_identity.PENDING_STATUS] |
| 428 | if pending and len(existing) == len(pending): |
| 429 | return {"outcome": "pending", "user": pending[0]} |
| 430 | return {"outcome": "exists", "user": existing[0]} |
| 431 | account = object_identity.create_account( |
| 432 | {"name": email, "status": object_identity.ACTIVE_STATUS}, |
| 433 | base_dir=base_dir, |
| 434 | now=now, |
| 435 | ) |
| 436 | user = object_identity.create_user( |
| 437 | { |
| 438 | "account_id": account["account_id"], |
| 439 | "email": email, |
| 440 | "display_name": "", |
| 441 | "status": object_identity.PENDING_STATUS, |
| 442 | "roles": [], |
| 443 | }, |
| 444 | base_dir=base_dir, |
| 445 | now=now, |
| 446 | # a pending user has no password until the mailbox chooses one: a row already under the new |
| 447 | # (random) id can only be a leftover, so it goes, with a warning in the log |
| 448 | leftover_password=object_identity.LEFTOVER_PASSWORD_CLEAR, |
| 449 | ) |
| 450 | return {"outcome": "created", "user": user} |
| 451 | |
| 452 | |
| 453 | def confirm_signup( |
| 454 | token: str | None, |
| 455 | password: str | None, |
| 456 | display_name: str | None = "", |
| 457 | *, |
| 458 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 459 | now: datetime | None = None, |
| 460 | ) -> dict[str, Any] | None: |
| 461 | """Use a verification link: the pending user gets this password (and name) and becomes active. |
| 462 | |
| 463 | None if the link is no good, or the user is not pending any more (a link |
| 464 | must never change the password of an account that is already in use). |
| 465 | Raises SignupError for a password that won't do, before the link is used, |
| 466 | so the person can try again with the same link.""" |
| 467 | password = check_password(password) |
| 468 | display_name = (display_name or "").strip()[:MAX_DISPLAY_NAME_LENGTH] |
| 469 | if peek_token(token, VERIFY_EMAIL, base_dir=base_dir, now=now) is None: |
| 470 | return None |
| 471 | row = consume_token(token, VERIFY_EMAIL, base_dir=base_dir, now=now) |
| 472 | if row is None: |
| 473 | return None |
| 474 | try: |
| 475 | user = object_identity.get_user(row["user_id"], base_dir=base_dir) |
| 476 | except (LookupError, ValueError): |
| 477 | return None |
| 478 | if user["status"] != object_identity.PENDING_STATUS: |
| 479 | return None |
| 480 | # the link was sent to one address; if the user's address has changed |
| 481 | # since, it no longer proves anything about this user |
| 482 | if (user.get("email") or "").strip().casefold() != (row.get("email") or "").strip().casefold(): |
| 483 | return None |
| 484 | object_credentials.set_password(user["user_id"], password, base_dir=base_dir) |
| 485 | return object_identity.set_user_status( |
| 486 | user["user_id"], object_identity.ACTIVE_STATUS, display_name=display_name, base_dir=base_dir, now=now, |
| 487 | ) |
| 488 | |
| 489 | |
| 490 | def reset_password( |
| 491 | token: str | None, |
| 492 | password: str | None, |
| 493 | *, |
| 494 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 495 | now: datetime | None = None, |
| 496 | ) -> dict[str, Any] | None: |
| 497 | """Use a reset link to set a new password. None if the link is no good. |
| 498 | |
| 499 | Raises SignupError for a password that won't do -- before the link is |
| 500 | used, so the person can try again with the same link. Every session the |
| 501 | user had is revoked: whoever knew the old password is signed out. A |
| 502 | pending user becomes active, since the link proved they hold the mailbox. |
| 503 | If the password is written but the sessions cannot be ended, this raises |
| 504 | object_credentials.SessionRevocationError (the link is used up by then).""" |
| 505 | password = check_password(password) |
| 506 | if peek_token(token, PASSWORD_RESET, base_dir=base_dir, now=now) is None: |
| 507 | return None |
| 508 | row = consume_token(token, PASSWORD_RESET, base_dir=base_dir, now=now) |
| 509 | if row is None: |
| 510 | return None |
| 511 | user = _activate_if_pending(row, base_dir=base_dir, now=now) |
| 512 | if user is None: |
| 513 | return None |
| 514 | # set_password also ends every session the user had (object_credentials) |
| 515 | object_credentials.set_password(user["user_id"], password, base_dir=base_dir, now=now) |
| 516 | return user |
| 517 | |
| 518 | |
| 519 | def reset_candidate(email: str, *, base_dir: Path | str = DEFAULT_DATA_DIR) -> dict[str, Any] | None: |
| 520 | """The one user a reset for this address would go to, or None. |
| 521 | |
| 522 | Disabled users get nothing: an operator turned them off, and a reset |
| 523 | link must not be a way back in.""" |
| 524 | try: |
| 525 | email = normalize_email(email) |
| 526 | except SignupError: |
| 527 | return None |
| 528 | users = object_identity.find_users_by_address( |
| 529 | email, statuses=(object_identity.ACTIVE_STATUS, object_identity.PENDING_STATUS), base_dir=base_dir, |
| 530 | ) |
| 531 | return users[0] if len(users) == 1 else None |
| 532 | |
| 533 | |
| 534 | def _activate_if_pending(row: Mapping[str, str], *, base_dir: Path | str, now: datetime | None) -> dict[str, Any] | None: |
| 535 | try: |
| 536 | user = object_identity.get_user(row["user_id"], base_dir=base_dir) |
| 537 | except (LookupError, ValueError): |
| 538 | return None |
| 539 | # the link was sent to one address; if the user's address has changed |
| 540 | # since, it no longer proves anything about this user |
| 541 | if (user.get("email") or "").strip().casefold() != (row.get("email") or "").strip().casefold(): |
| 542 | return None |
| 543 | # only the two statuses a link may serve; disabled, and any status this version does not know, get nothing |
| 544 | if user["status"] not in (object_identity.ACTIVE_STATUS, object_identity.PENDING_STATUS): |
| 545 | return None |
| 546 | if user["status"] == object_identity.PENDING_STATUS: |
| 547 | user = object_identity.set_user_status(user["user_id"], object_identity.ACTIVE_STATUS, base_dir=base_dir, now=now) |
| 548 | return user |
| 549 | |
| 550 | |
| 551 | # -------------------------------------------------------------------------- |
| 552 | # The emails |
| 553 | |
| 554 | |
| 555 | def link(base_url: str, path: str, token: str | None = None) -> str: |
| 556 | url = base_url.rstrip("/") + path |
| 557 | if token is not None: |
| 558 | url += "?" + urllib.parse.urlencode({"token": token}) |
| 559 | return url |
| 560 | |
| 561 | |
| 562 | def verification_email(base_url: str, token: str) -> tuple[str, str]: |
| 563 | hours = int(TOKEN_TTL[VERIFY_EMAIL].total_seconds() // 3600) |
| 564 | return ( |
| 565 | "Confirm your email address", |
| 566 | "Someone (hopefully you) created an account with this email address.\n\n" |
| 567 | f"To confirm it and choose your password, open this link within {hours} hours:\n\n" |
| 568 | f"{link(base_url, '/verify', token)}\n\n" |
| 569 | "If it wasn't you, ignore this email: nobody can sign in to the account without a link sent to this address.\n", |
| 570 | ) |
| 571 | |
| 572 | |
| 573 | def already_registered_email(base_url: str, reset_available: bool) -> tuple[str, str]: |
| 574 | body = ( |
| 575 | "Someone (hopefully you) tried to create an account with this email address, " |
| 576 | "but it already has one.\n\n" |
| 577 | f"Sign in here: {link(base_url, '/login')}\n" |
| 578 | ) |
| 579 | if reset_available: |
| 580 | body += f"Forgot your password? Reset it here: {link(base_url, '/reset')}\n" |
| 581 | body += "\nIf it wasn't you, ignore this email: nothing has changed.\n" |
| 582 | return ("You already have an account", body) |
| 583 | |
| 584 | |
| 585 | def reset_email(base_url: str, token: str) -> tuple[str, str]: |
| 586 | minutes = int(TOKEN_TTL[PASSWORD_RESET].total_seconds() // 60) |
| 587 | return ( |
| 588 | "Reset your password", |
| 589 | "Someone (hopefully you) asked to reset the password for this email address.\n\n" |
| 590 | f"To choose a new password, open this link within {minutes} minutes:\n\n" |
| 591 | f"{link(base_url, '/reset/confirm', token)}\n\n" |
| 592 | "If it wasn't you, ignore this email: your password stays as it is.\n", |
| 593 | ) |
| 594 | |
| 595 | |
| 596 | def send(to: str, subject_and_body: tuple[str, str], *, base_dir: Path | str = DEFAULT_DATA_DIR) -> str: |
| 597 | subject, body = subject_and_body |
| 598 | return object_email.enqueue(to, subject, body, source_object_id="object_signup", base_dir=base_dir) |
| 599 | |
| 600 | |
| 601 | # -------------------------------------------------------------------------- |
| 602 | |
| 603 | |
| 604 | def _stamp(value: datetime) -> str: |
| 605 | return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") |
| 606 | |
| 607 | |
| 608 | def _parse(value: str) -> datetime: |
| 609 | return datetime.fromisoformat(value.replace("Z", "+00:00")) |
| 610 | |
| 611 | |
| 612 | def _now() -> datetime: |
| 613 | return datetime.now(timezone.utc) |