In-Memory User Authentication and Profile Service
Medium · Software Engineering Fundamentals · Software Engineer · Onsite
Problem Statement
Build an in-memory backend service AuthProfileAPI that exposes user registration, session-based login and logout, and profile management behind a clean HTTP-shaped interface:
AuthProfileAPI(clock: Callable[[], float] = time.time, token_ttl: float = 3600.0)handle(method: str, path: str, body: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None) -> Tuple[int, Optional[Dict[str, Any]]]
All request and response payloads are already-parsed Python dictionaries (or None when no body is sent or returned), and no external database is used. Password storage may use a fast salted placeholder hash in place of a production slow hash.
Endpoints
HTTP method names are matched case-insensitively ("post" behaves like "POST"):
POST /users(no auth): Accepts{"email": str, "password": str, "display_name"?: str}. Creates a user account with a monotonically increasing integeridstarting at1(never reused after deletion), a normalized email, a strippeddisplay_name(defaulting to""),"bio": "", andcreated_at = updated_at = clock(). Returns(201, public_profile).POST /sessions(no auth): Accepts{"email": str, "password": str}. Verifies the credentials against the normalized email and issues a fresh opaque bearer token valid on[t, t + token_ttl), returning(200, {"token": str, "token_type": "Bearer", "expires_in": token_ttl, "user_id": int}).DELETE /sessions(Bearer token): Revokes only the presented bearer token while leaving the user's other active tokens intact, returning(204, None).GET /users/me(Bearer token): Returns(200, public_profile)for the authenticated user.PATCH /users/me(Bearer token): Accepts a JSON object with optional"display_name"and/or"bio". Validates the entire payload before mutating any field (all-or-nothing), updates provided fields with outer whitespace stripped, setsupdated_at = clock(), and returns(200, public_profile).DELETE /users/me(Bearer token): Removes the user account, revokes every active session token owned by that user, frees the normalized email for future signups, and returns(204, None).
Schemas, Validation, and Errors
- Public profile:
{"id": int, "email": str, "display_name": str, "bio": str, "created_at": float, "updated_at": float}. Password plaintext, salts, and hashes must never appear in any response. - Error envelope:
(status, {"error": {"code": str, "message": str}}). - Routing (
404/405): Return404("not_found") ifpathis not/users,/sessions, or/users/me. Return405("method_not_allowed") ifpathexists but does not supportmethod. - Bearer authentication (
401): Protected endpoints require anAuthorizationheader (matched case-insensitively) formatted asBearer <token>(scheme case-insensitive, token case-sensitive). Missing headers, wrong schemes, unknown or revoked tokens, and expired tokens (clock() >= issued_at + token_ttl, evicted immediately upon check) return401("unauthorized"). - Login failures (
401): Unregistered emails, wrong passwords, and passwords exceeding128characters onPOST /sessionsmust all return the exact same401("invalid_credentials") payload. - Payload validation (
400/409):- Non-dictionary
bodyonPOST /users,POST /sessions, orPATCH /users/me(or non-stringemail/passwordonPOST /sessions) ->400("invalid_body"). - Any unexpected key in
body->400("unknown_field"). display_nameorbionot astr, orlen(value.strip()) > 50(display_name) /> 280(bio) ->400("invalid_display_name"/"invalid_bio").- Malformed registration
email(not astr, or after.strip().lower()longer than254chars, containing whitespace, not having@once, empty before@, or a domain without., with.., or starting/ending with.) ->400("invalid_email"). - Registration
passwordnot astrorlen(password)outside8..128->400("invalid_password"). - Valid registration payload whose normalized email is already active ->
409("email_taken").
- Non-dictionary
Examples
Example 1
Setup: clock starts at 200.0, token_ttl = 120.0
1. POST /users {"email": " Maya@Velo.DEV ", "password": "river-stone-99", "display_name": " Maya "}
-> (201, {"id": 1, "email": "maya@velo.dev", "display_name": "Maya", "bio": "",
"created_at": 200.0, "updated_at": 200.0})
2. POST /sessions {"email": "MAYA@velo.dev", "password": "river-stone-99"}
-> (200, {"token": "<tok>", "token_type": "Bearer", "expires_in": 120.0, "user_id": 1})
3. At clock = 245.0:
PATCH /users/me {"bio": " Building distributed tools "} headers={"Authorization": "Bearer <tok>"}
-> (200, {"id": 1, "email": "maya@velo.dev", "display_name": "Maya",
"bio": "Building distributed tools", "created_at": 200.0, "updated_at": 245.0})
4. DELETE /sessions headers={"Authorization": "Bearer <tok>"}
-> (204, None)
5. GET /users/me headers={"Authorization": "Bearer <tok>"}
-> (401, {"error": {"code": "unauthorized", "message": "..."}})
Walk-through: Registration trims and lowercases Maya's email, strips her display name, and omits password data. Logging in works regardless of email casing, PATCH trims bio and advances updated_at to 245.0, and DELETE /sessions immediately invalidates <tok>.
Example 2
Setup: clock starts at 500.0, token_ttl = 30.0
1. POST /users {"email": "leo@velo.dev", "password": "cedar-forest-12"}
-> (201, {"id": 1, "email": "leo@velo.dev", "display_name": "", "bio": "",
"created_at": 500.0, "updated_at": 500.0})
2. POST /users {"email": " LEO@velo.dev ", "password": "another-password"}
-> (409, {"error": {"code": "email_taken", "message": "..."}})
3. POST /sessions {"email": "leo@velo.dev", "password": "cedar-forest-12"}
-> (200, {"token": "<tok>", "token_type": "Bearer", "expires_in": 30.0, "user_id": 1})
4. PATCH /users/me {"display_name": "Leo", "bio": "z" * 281} headers={"Authorization": "Bearer <tok>"}
-> (400, {"error": {"code": "invalid_bio", "message": "..."}})
(Profile stays unchanged: display_name is still "")
5. At clock = 530.0:
GET /users/me headers={"Authorization": "Bearer <tok>"}
-> (401, {"error": {"code": "unauthorized", "message": "..."}})
Walk-through: Duplicate normalized emails fail with 409, an invalid bio aborts the entire PATCH without modifying display_name, and at 530.0 == 500.0 + 30.0 the token has reached its expiry boundary and is rejected.
Constraints
- Normalized
emaillength<= 254; registrationpasswordlength8..128; strippeddisplay_namelength<= 50; strippedbiolength<= 280. token_ttl > 0; a token issued at timestamptis valid strictly whileclock() < t + token_ttl.- Standard library only, safe under concurrent
handle(...)calls, withO(1)average time per request (O(k)when deleting an account that holdskactive tokens).
Step-by-step walkthrough
Define the HTTP contract and error format
Because this prompt is open-ended, start by pinning down a clean, minimal HTTP contract before writing any code. Separating the core API logic (
handle(method, path, body, headers) -> (status, json_body)) from real sockets keeps every endpoint fast and deterministic to unit-test, while a tinyhttp.serveradapter at the bottom can still serve real HTTP traffic.Method & Path Auth Request JSON Success Response POST /usersNone {"email", "password", "display_name"?}201public profilePOST /sessionsNone {"email", "password"}200 {"token", "token_type": "Bearer", "expires_in", "user_id"}DELETE /sessionsBearer token None 204(None), revokes only this token (logout)GET /users/meBearer token None 200public profilePATCH /users/meBearer token {"display_name"?, "bio"?}200public profileDELETE /users/meBearer token None 204(None), deletes user and revokes all their tokensEvery public profile contains only safe fields:
{"id", "email", "display_name", "bio", "created_at", "updated_at"}—never the password or password hash. Every error uses one predictable shape,{"error": {"code": "...", "message": "..."}}, so frontend clients can switch onerror.codeinstead of fragile string matching:400bad input (invalid_body,unknown_field,invalid_email,invalid_password,invalid_display_name,invalid_bio)401authentication failure (invalid_credentials,unauthorized)404unknown URL path (not_found)405valid URL path called with an unsupported HTTP verb (method_not_allowed)409valid registration payload whose email already exists (email_taken)
Design the four in-memory lookup tables
If we stored users in a single list and sessions in another list, checking whether an email is already taken would scan all users (
O(U)), and deleting an account would scan every active session across the whole server (O(S)). Instead, give each lookup pattern its own dictionary so routine operations run inO(1)average time:user_id_by_email users {"maya@velo.dev": 1} ───────────▶ {1: {"id": 1, "email": "maya@velo.dev", "password_salt": "9f2a...", "password_hash": "7c10...", "display_name": "Maya", "bio": "", "created_at": 200.0, "updated_at": 200.0}} ▲ sessions │ {"Xq3...": {"user_id": 1, ───────────┘ "expires_at": 320.0}} ▲ └─────── tokens_by_user: {1: {"Xq3...", "Kp9..."}}Why keep both
sessionsandtokens_by_user? -sessionsmapstoken -> {"user_id", "expires_at"}so every authenticated request checks a bearer token inO(1). -tokens_by_usermapsuser_id -> set of tokenssoDELETE /users/merevokes all of that user's sessions inO(k)time (wherekis that user's open sessions) without touching anyone else's sessions. - Whenever a token is created, logged out, expired, or deleted with an account, we update both dictionaries together so they never drift apart.We also inject
clock(defaulting totime.time) so tests can advance time instantly without sleeping.from typing import Any, Callable, Dict, Optional, Tuple import threading import time Response = Tuple[int, Optional[Dict[str, Any]]] class AuthProfileAPI: def __init__(self, clock: Callable[[], float] = time.time, token_ttl: float = 3600.0) -> None: self.clock = clock self.token_ttl = token_ttl # users: {1: {"id": 1, "email": "maya@velo.dev", "password_salt": "...", ...}} self.users: Dict[int, Dict[str, Any]] = {} # user_id_by_email: {"maya@velo.dev": 1} for O(1) uniqueness checks and login lookup self.user_id_by_email: Dict[str, int] = {} # sessions: {"tok_abc": {"user_id": 1, "expires_at": 4600.0}} for O(1) bearer token checks self.sessions: Dict[str, Dict[str, Any]] = {} # tokens_by_user: {1: {"tok_abc", "tok_xyz"}} so deleting user 1 revokes all their tokens in O(k) self.tokens_by_user: Dict[int, set] = {} # Monotonically increasing ID counter; never reused after deletion. self.next_id = 1 self.lock = threading.Lock()Validate emails, passwords, and profile fields
Putting input validation in small, pure helper functions keeps the rules consistent across registration, login, and profile updates:
- Email normalization: strip outer spaces and lowercase the string so
" Maya@Velo.DEV "and"maya@velo.dev"refer to the same account. Reject strings longer than 254 characters, any internal whitespace, anything without exactly one@, an empty local part before@, or a domain without a dot (or with leading, trailing, or doubled dots likea@..com). - Unknown-field rejection: reject unexpected JSON keys such as
{"is_admin": true}with400 unknown_fieldinstead of silently ignoring them. This catches client typos early and blocks mass-assignment bugs (where a user tries to overwrite internal fields). - Profile field limits:
display_name(up to 50 chars) andbio(up to 280 chars) must be strings, checked after stripping outer whitespace. - Password hashing placeholder: we use salted SHA-256 (
sha256(salt + password)) as an in-memory stand-in. In production, SHA-256 is far too fast on GPUs—you would swap this helper for a deliberately slow, memory-hard password hash such as Argon2id, bcrypt, or scrypt.
import hashlib MIN_PASSWORD_LENGTH = 8 MAX_PASSWORD_LENGTH = 128 MAX_EMAIL_LENGTH = 254 PROFILE_LIMITS = {"display_name": 50, "bio": 280} def hash_password(password: str, salt: str) -> str: """Mocked placeholder. Production code must use a slow hash: argon2id, bcrypt or scrypt.""" salted_bytes = (salt + password).encode("utf-8") return hashlib.sha256(salted_bytes).hexdigest() def error(status: int, code: str, message: str) -> Response: """Build a uniform JSON error envelope so clients can switch on error.code.""" return status, {"error": {"code": code, "message": message}} def normalize_email(value: Any) -> Optional[str]: """Return a trimmed, lowercased email string, or None if malformed.""" if not isinstance(value, str): return None # Fold case and trim outer spaces so " Maya@Velo.dev " maps to "maya@velo.dev". email = value.strip().lower() if len(email) > MAX_EMAIL_LENGTH or email.count("@") != 1: return None for ch in email: if ch.isspace(): return None local, domain = email.split("@") # Require text before '@', at least one dot in the domain, and no empty domain labels. if not local or "." not in domain or ".." in domain: return None if domain.startswith(".") or domain.endswith("."): return None return email def check_allowed_fields(body: Dict[str, Any], allowed: Tuple[str, ...]) -> Optional[Response]: """Return 400 unknown_field if the request body includes any unexpected key.""" for field in body: if field not in allowed: return error(400, "unknown_field", f"field '{field}' is not accepted here") return None def check_profile_fields(body: Dict[str, Any], allowed: Tuple[str, ...]) -> Optional[Response]: """Validate allowed keys first, then check string type and length of profile fields.""" unknown_err = check_allowed_fields(body, allowed) if unknown_err is not None: return unknown_err for field, max_len in PROFILE_LIMITS.items(): if field not in body: continue value = body[field] # Measure length after stripping outer whitespace so stored text respects the cap. if not isinstance(value, str) or len(value.strip()) > max_len: return error( 400, "invalid_" + field, f"{field} must be a string of at most {max_len} characters", ) return None- Email normalization: strip outer spaces and lowercase the string so
Route requests and verify bearer tokens
Every call enters
handle, acquiresself.lock, and passes through three clear routing stages:Request ──▶ [Path in ROUTES?] ──No──▶ 404 not_found │Yes [Method allowed?] ──No──▶ 405 method_not_allowed │Yes [Public route?] ──Yes─▶ POST /users or POST /sessions │No [Valid Bearer?] ──No──▶ 401 unauthorized │Yes Dispatch DELETE /sessions or GET / PATCH / DELETE /users/meThree subtle details matter here: 1. Concurrency (
self.lock): In registration, checkingemail in self.user_id_by_emailand inserting the new user must happen as one indivisible (atomic) step; otherwise two simultaneous requests with the same email could both pass the check and create duplicate accounts. 2. Case-insensitive header parsing: HTTP header names (Authorizationvsauthorization) and auth scheme names (Bearervsbearer) are case-insensitive, while the random token string itself is case-sensitive. 3. Exact expiry boundary (>=): A token issued at timetwithtoken_ttl = 60is valid whileclock() < t + 60. Atclock() == t + 60,self.clock() >= session["expires_at"]triggers, revokes the token immediately, and returns401. Deleting it on sight ensures that even if a clock jumps backward, an expired token never comes back to life.ROUTES = { "/users": ("POST",), "/sessions": ("POST", "DELETE"), "/users/me": ("GET", "PATCH", "DELETE"), } def bearer_token(headers: Dict[str, str]) -> Optional[str]: """Extract <token> from an 'Authorization: Bearer <token>' header (case-insensitive).""" for name, value in headers.items(): if name.lower() != "authorization" or not isinstance(value, str): continue parts = value.split() # HTTP header names and auth scheme names ("Bearer") are case-insensitive; tokens are exact. if len(parts) == 2 and parts[0].lower() == "bearer": return parts[1] return None class AuthProfileAPI: def handle(self, method: str, path: str, body: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None) -> Response: # Wrap each request in one lock so check-then-insert on registration is atomic across threads. with self.lock: clean_headers = headers if headers is not None else {} return self._route(method.upper(), path, body, clean_headers) def _route(self, method: str, path: str, body: Any, headers: Dict[str, str]) -> Response: # Phase 1: check path existence (404) before checking whether the HTTP verb is supported (405). if path not in ROUTES: return error(404, "not_found", f"no route for {path}") if method not in ROUTES[path]: return error(405, "method_not_allowed", "allowed: " + ", ".join(ROUTES[path])) # Phase 2: public endpoints do not require a bearer token. if path == "/users": return self._register(body) if path == "/sessions" and method == "POST": return self._login(body) # Phase 3: protected endpoints require a valid, non-expired bearer token. token = bearer_token(headers) user_id = self._user_for_token(token) if user_id is None: return error(401, "unauthorized", "missing, invalid or expired bearer token") if path == "/sessions": self._revoke(token) # type: ignore[arg-type] return 204, None if method == "GET": return 200, self._public_profile(user_id) if method == "PATCH": return self._update_profile(user_id, body) return self._delete_account(user_id) def _user_for_token(self, token: Optional[str]) -> Optional[int]: if token is None or token not in self.sessions: return None session = self.sessions[token] # Use >= so a token issued at t with TTL 60 is valid on [t, t + 60) and expires at t + 60. if self.clock() >= session["expires_at"]: # Delete expired tokens immediately so rolling the clock backward never revives them. self._revoke(token) return None return session["user_id"] def _revoke(self, token: str) -> None: # Remove from both session maps to keep sessions and tokens_by_user consistent. session = self.sessions.pop(token) self.tokens_by_user[session["user_id"]].discard(token)Register accounts and log in safely
Registration (
POST /users) checks input format (400) before checking state collision (409 Conflict). Each user gets a fresh 16-byte random salt (secrets.token_hex(16)) so two users who pick the same password still store completely different hashes.Login (
POST /sessions) must avoid leaking whether an email address is registered: - Identical error payload: Both "no such email" and "wrong password" return(401, {"error": {"code": "invalid_credentials", ...}}). - Identical work and constant-time comparison: If we skipped hashing when an email was missing, a real slow password hash would take tens of milliseconds for valid emails and microseconds for unknown emails—letting attackers spot registered emails by measuring latency. Hashing againstDUMMY_SALTon the missing-email path equalizes that work. Likewise,hmac.compare_digestcompares hashes in constant time instead of stopping at the first mismatched character. We also cap login hashing on passwords longer thanMAX_PASSWORD_LENGTH(128) so an attacker cannot send a multi-megabyte password to stall the server. - Opaque random tokens:secrets.token_urlsafe(32)draws 256 bits of cryptographic randomness from the OS, making session tokens impossible to guess and trivial to revoke by deleting fromself.sessions.import hmac import secrets DUMMY_SALT = secrets.token_hex(16) DUMMY_PASSWORD = "x" * MIN_PASSWORD_LENGTH class AuthProfileAPI: def _register(self, body: Any) -> Response: if not isinstance(body, dict): return error(400, "invalid_body", "body must be a JSON object") # Validate field names and profile limits before checking email uniqueness. problem = check_profile_fields(body, ("email", "password", "display_name")) if problem is not None: return problem email = normalize_email(body.get("email")) if email is None: return error(400, "invalid_email", "email is missing or malformed") password = body.get("password") if not isinstance(password, str) or not MIN_PASSWORD_LENGTH <= len(password) <= MAX_PASSWORD_LENGTH: return error( 400, "invalid_password", f"password must have {MIN_PASSWORD_LENGTH}-{MAX_PASSWORD_LENGTH} characters", ) # Return 409 Conflict (not 400) because the payload is well-formed but collides with current state. if email in self.user_id_by_email: return error(409, "email_taken", "an account with this email already exists") now = self.clock() salt = secrets.token_hex(16) user_id = self.next_id self.next_id += 1 raw_display_name = body.get("display_name", "") user = { "id": user_id, "email": email, "password_salt": salt, "password_hash": hash_password(password, salt), "display_name": raw_display_name.strip(), "bio": "", "created_at": now, "updated_at": now, } # Insert into all per-user indexes together so they stay in sync. self.users[user_id] = user self.user_id_by_email[email] = user_id self.tokens_by_user[user_id] = set() return 201, self._public_profile(user_id) def _login(self, body: Any) -> Response: if not isinstance(body, dict): return error(400, "invalid_body", "body must be a JSON object") unknown_err = check_allowed_fields(body, ("email", "password")) if unknown_err is not None: return unknown_err email = body.get("email") password = body.get("password") if not isinstance(email, str) or not isinstance(password, str): return error(400, "invalid_body", "email and password must be strings") # Cap hashing work on overlong passwords so a giant string cannot stall the server, # while still returning the exact same 401 as any other bad login attempt. if len(password) > MAX_PASSWORD_LENGTH: hash_password(DUMMY_PASSWORD, DUMMY_SALT) return error(401, "invalid_credentials", "email or password is incorrect") # Return the exact same 401 message and do dummy hashing when the email is unknown, # so an attacker cannot probe which emails exist via error codes or response timing. normalized_lookup = email.strip().lower() user_id = self.user_id_by_email.get(normalized_lookup) if user_id is None: hash_password(password, DUMMY_SALT) return error(401, "invalid_credentials", "email or password is incorrect") user = self.users[user_id] candidate_hash = hash_password(password, user["password_salt"]) # compare_digest runs in constant time so character-by-character timing leaks are avoided. if not hmac.compare_digest(candidate_hash, user["password_hash"]): return error(401, "invalid_credentials", "email or password is incorrect") # 32 random bytes (~256 bits of entropy) make opaque session tokens unguessable. token = secrets.token_urlsafe(32) expires_at = self.clock() + self.token_ttl self.sessions[token] = {"user_id": user_id, "expires_at": expires_at} self.tokens_by_user[user_id].add(token) return 200, { "token": token, "token_type": "Bearer", "expires_in": self.token_ttl, "user_id": user_id, }Read, update, and delete user profiles
- Read (
GET /users/me):_public_profilebuilds a brand-new dictionary from an allow-list of safe keys (id,email,display_name,bio,created_at,updated_at). If you instead copieduserand deletedpassword_hash, any future secret field added touser(such as a two-factor secret) would accidentally leak in API responses. - Update (
PATCH /users/me): Validate all fields inbodybefore modifying any field onuser. If a caller sends{"display_name": "Leo", "bio": "z" * 281}, checking everything up front ensuresdisplay_nameis not half-saved behind a400 invalid_bioerror. - Delete (
DELETE /users/me): Pop the user fromusers, remove their normalized email fromuser_id_by_email(so they can sign up again later with a brand-new ID), and remove every token intokens_by_user[user_id]fromsessions.
Trace Example 1 with
token_ttl = 120.0starting att = 200.0:t=200.0 POST /users {"email": " Maya@Velo.DEV ", "password": "river-stone-99", "display_name": " Maya "} -> 201 {"id": 1, "email": "maya@velo.dev", "display_name": "Maya", "bio": "", "created_at": 200.0, "updated_at": 200.0} t=200.0 POST /sessions {"email": "MAYA@velo.dev", "password": "river-stone-99"} -> 200 {"token": "Xq3...", "token_type": "Bearer", "expires_in": 120.0, "user_id": 1} sessions["Xq3..."] = {"user_id": 1, "expires_at": 320.0} t=245.0 PATCH /users/me {"bio": " Building distributed tools "} (Bearer Xq3...) -> 200 {..., "bio": "Building distributed tools", "updated_at": 245.0} t=245.0 DELETE /sessions (Bearer Xq3...) -> 204 None (removes "Xq3..." from sessions) t=245.0 GET /users/me (Bearer Xq3...) -> 401 unauthorized- Read (
Complete solution
Putting all pieces together—along with a lightweight
serve()demo adapter over Python's built-inThreadingHTTPServer—gives the full implementation:from typing import Any, Callable, Dict, Optional, Tuple import hashlib import hmac import json import secrets import threading import time Response = Tuple[int, Optional[Dict[str, Any]]] MIN_PASSWORD_LENGTH = 8 MAX_PASSWORD_LENGTH = 128 MAX_EMAIL_LENGTH = 254 PROFILE_LIMITS = {"display_name": 50, "bio": 280} # Pre-generated salt and password used when an unknown email tries to log in, # so unknown-email and wrong-password paths do the same hashing work. DUMMY_SALT = secrets.token_hex(16) DUMMY_PASSWORD = "x" * MIN_PASSWORD_LENGTH # Allowed HTTP methods for each supported URL path. ROUTES = { "/users": ("POST",), "/sessions": ("POST", "DELETE"), "/users/me": ("GET", "PATCH", "DELETE"), } def hash_password(password: str, salt: str) -> str: """Mocked placeholder. Production code must use a slow hash: argon2id, bcrypt or scrypt.""" salted_bytes = (salt + password).encode("utf-8") return hashlib.sha256(salted_bytes).hexdigest() def error(status: int, code: str, message: str) -> Response: """Build a uniform JSON error envelope so clients can switch on error.code.""" return status, {"error": {"code": code, "message": message}} def normalize_email(value: Any) -> Optional[str]: """Return a trimmed, lowercased email string, or None if malformed.""" if not isinstance(value, str): return None # Fold case and trim outer spaces so " Maya@Velo.dev " maps to "maya@velo.dev". email = value.strip().lower() if len(email) > MAX_EMAIL_LENGTH or email.count("@") != 1: return None for ch in email: if ch.isspace(): return None local, domain = email.split("@") # Require text before '@', at least one dot in the domain, and no empty domain labels. if not local or "." not in domain or ".." in domain: return None if domain.startswith(".") or domain.endswith("."): return None return email def check_allowed_fields(body: Dict[str, Any], allowed: Tuple[str, ...]) -> Optional[Response]: """Return 400 unknown_field if the request body includes any unexpected key.""" for field in body: if field not in allowed: return error(400, "unknown_field", f"field '{field}' is not accepted here") return None def check_profile_fields(body: Dict[str, Any], allowed: Tuple[str, ...]) -> Optional[Response]: """Validate allowed keys first, then check string type and length of profile fields.""" unknown_err = check_allowed_fields(body, allowed) if unknown_err is not None: return unknown_err for field, max_len in PROFILE_LIMITS.items(): if field not in body: continue value = body[field] # Measure length after stripping outer whitespace so stored text respects the cap. if not isinstance(value, str) or len(value.strip()) > max_len: return error( 400, "invalid_" + field, f"{field} must be a string of at most {max_len} characters", ) return None def bearer_token(headers: Dict[str, str]) -> Optional[str]: """Extract <token> from an 'Authorization: Bearer <token>' header (case-insensitive).""" for name, value in headers.items(): if name.lower() != "authorization" or not isinstance(value, str): continue parts = value.split() # HTTP header names and auth scheme names ("Bearer") are case-insensitive; tokens are exact. if len(parts) == 2 and parts[0].lower() == "bearer": return parts[1] return None class AuthProfileAPI: def __init__(self, clock: Callable[[], float] = time.time, token_ttl: float = 3600.0) -> None: self.clock = clock self.token_ttl = token_ttl # users: {1: {"id": 1, "email": "maya@velo.dev", "password_salt": "...", ...}} self.users: Dict[int, Dict[str, Any]] = {} # user_id_by_email: {"maya@velo.dev": 1} for O(1) uniqueness checks and login lookup self.user_id_by_email: Dict[str, int] = {} # sessions: {"tok_abc": {"user_id": 1, "expires_at": 4600.0}} for O(1) bearer token checks self.sessions: Dict[str, Dict[str, Any]] = {} # tokens_by_user: {1: {"tok_abc", "tok_xyz"}} so deleting user 1 revokes all their tokens in O(k) self.tokens_by_user: Dict[int, set] = {} # Monotonically increasing ID counter; never reused after deletion. self.next_id = 1 self.lock = threading.Lock() def handle(self, method: str, path: str, body: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None) -> Response: # Wrap each request in one lock so check-then-insert on registration is atomic across threads. with self.lock: clean_headers = headers if headers is not None else {} return self._route(method.upper(), path, body, clean_headers) def _route(self, method: str, path: str, body: Any, headers: Dict[str, str]) -> Response: # Phase 1: check path existence (404) before checking whether the HTTP verb is supported (405). if path not in ROUTES: return error(404, "not_found", f"no route for {path}") if method not in ROUTES[path]: return error(405, "method_not_allowed", "allowed: " + ", ".join(ROUTES[path])) # Phase 2: public endpoints do not require a bearer token. if path == "/users": return self._register(body) if path == "/sessions" and method == "POST": return self._login(body) # Phase 3: protected endpoints require a valid, non-expired bearer token. token = bearer_token(headers) user_id = self._user_for_token(token) if user_id is None: return error(401, "unauthorized", "missing, invalid or expired bearer token") if path == "/sessions": # token is guaranteed non-None here because _user_for_token returned a user_id. self._revoke(token) # type: ignore[arg-type] return 204, None if method == "GET": return 200, self._public_profile(user_id) if method == "PATCH": return self._update_profile(user_id, body) return self._delete_account(user_id) def _register(self, body: Any) -> Response: if not isinstance(body, dict): return error(400, "invalid_body", "body must be a JSON object") # Validate field names and profile limits before checking email uniqueness. problem = check_profile_fields(body, ("email", "password", "display_name")) if problem is not None: return problem email = normalize_email(body.get("email")) if email is None: return error(400, "invalid_email", "email is missing or malformed") password = body.get("password") if not isinstance(password, str) or not MIN_PASSWORD_LENGTH <= len(password) <= MAX_PASSWORD_LENGTH: return error( 400, "invalid_password", f"password must have {MIN_PASSWORD_LENGTH}-{MAX_PASSWORD_LENGTH} characters", ) # Return 409 Conflict (not 400) because the payload is well-formed but collides with current state. if email in self.user_id_by_email: return error(409, "email_taken", "an account with this email already exists") now = self.clock() salt = secrets.token_hex(16) user_id = self.next_id self.next_id += 1 raw_display_name = body.get("display_name", "") user = { "id": user_id, "email": email, "password_salt": salt, "password_hash": hash_password(password, salt), "display_name": raw_display_name.strip(), "bio": "", "created_at": now, "updated_at": now, } # Insert into all per-user indexes together so they stay in sync. self.users[user_id] = user self.user_id_by_email[email] = user_id self.tokens_by_user[user_id] = set() return 201, self._public_profile(user_id) def _login(self, body: Any) -> Response: if not isinstance(body, dict): return error(400, "invalid_body", "body must be a JSON object") unknown_err = check_allowed_fields(body, ("email", "password")) if unknown_err is not None: return unknown_err email = body.get("email") password = body.get("password") if not isinstance(email, str) or not isinstance(password, str): return error(400, "invalid_body", "email and password must be strings") # Cap hashing work on overlong passwords so a giant string cannot stall the server, # while still returning the exact same 401 as any other bad login attempt. if len(password) > MAX_PASSWORD_LENGTH: hash_password(DUMMY_PASSWORD, DUMMY_SALT) return error(401, "invalid_credentials", "email or password is incorrect") # Return the exact same 401 message and do dummy hashing when the email is unknown, # so an attacker cannot probe which emails exist via error codes or response timing. normalized_lookup = email.strip().lower() user_id = self.user_id_by_email.get(normalized_lookup) if user_id is None: hash_password(password, DUMMY_SALT) return error(401, "invalid_credentials", "email or password is incorrect") user = self.users[user_id] candidate_hash = hash_password(password, user["password_salt"]) # compare_digest runs in constant time so character-by-character timing leaks are avoided. if not hmac.compare_digest(candidate_hash, user["password_hash"]): return error(401, "invalid_credentials", "email or password is incorrect") # 32 random bytes (~256 bits of entropy) make opaque session tokens unguessable. token = secrets.token_urlsafe(32) expires_at = self.clock() + self.token_ttl self.sessions[token] = {"user_id": user_id, "expires_at": expires_at} self.tokens_by_user[user_id].add(token) return 200, { "token": token, "token_type": "Bearer", "expires_in": self.token_ttl, "user_id": user_id, } def _user_for_token(self, token: Optional[str]) -> Optional[int]: if token is None or token not in self.sessions: return None session = self.sessions[token] # Use >= so a token issued at t with TTL 60 is valid on [t, t + 60) and expires at t + 60. if self.clock() >= session["expires_at"]: # Delete expired tokens immediately so rolling the clock backward never revives them. self._revoke(token) return None return session["user_id"] def _revoke(self, token: str) -> None: # Remove from both session maps to keep sessions and tokens_by_user consistent. session = self.sessions.pop(token) self.tokens_by_user[session["user_id"]].discard(token) def _public_profile(self, user_id: int) -> Dict[str, Any]: # Project an explicit allow-list of public fields so password_hash/salt can never leak. user = self.users[user_id] return { "id": user["id"], "email": user["email"], "display_name": user["display_name"], "bio": user["bio"], "created_at": user["created_at"], "updated_at": user["updated_at"], } def _update_profile(self, user_id: int, body: Any) -> Response: if not isinstance(body, dict): return error(400, "invalid_body", "body must be a JSON object") # Validate every field before mutating any field so a failed PATCH is all-or-nothing. problem = check_profile_fields(body, tuple(PROFILE_LIMITS)) if problem is not None: return problem user = self.users[user_id] for field, value in body.items(): user[field] = value.strip() user["updated_at"] = self.clock() return 200, self._public_profile(user_id) def _delete_account(self, user_id: int) -> Response: # Remove the user record, free their email for re-registration, and revoke every active session. user = self.users.pop(user_id) del self.user_id_by_email[user["email"]] for token in self.tokens_by_user.pop(user_id): del self.sessions[token] return 204, None def serve(api: AuthProfileAPI, port: int = 8000) -> None: """Expose the API over real HTTP with the standard library (demo only, no TLS).""" from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer class Handler(BaseHTTPRequestHandler): def dispatch(self) -> None: raw_length = self.headers.get("Content-Length") body: Any = None if raw_length: try: length = int(raw_length) if length < 0: raise ValueError("negative Content-Length") if length > 0: body = json.loads(self.rfile.read(length)) except ValueError: # Any non-dict value causes handlers to return 400 invalid_body cleanly. body = "not json" # Strip query parameters before routing. path = self.path.split("?", 1)[0] status, payload = api.handle(self.command, path, body, dict(self.headers)) self.send_response(status) if payload is None: self.send_header("Content-Length", "0") self.end_headers() else: data = json.dumps(payload).encode("utf-8") self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = dispatch ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever() if __name__ == "__main__": serve(AuthProfileAPI())✅ Submit now — all tests should pass.
Intuition & how it works
Think of an authentication and profile service like a hotel front desk. When a guest checks in for the first time (POST /users), the clerk verifies their ID format, puts their private security PIN in a locked back-office file, and creates a guest folder. When the guest logs in (POST /sessions), the clerk verifies their PIN and hands them a temporary, unguessable plastic keycard—a bearer token (a credential sent in the HTTP Authorization: Bearer <token> header that grants access to whoever holds it). Every time the guest asks to view, edit, or close their profile (GET, PATCH, or DELETE /users/me), the desk looks up the keycard in its active keycard ledger, checks that it has not expired, and returns only safe public details—never the PIN.
A naive implementation usually falls into four traps. Storing users and sessions in plain lists forces O(U) or O(S) linear scans on every signup, login, and account deletion. Returning the internal user dictionary directly leaks password_hash and password_salt to callers. Updating profile fields one by one inside a validation loop leaves half-applied changes when a later field fails validation. And skipping password hashing when an email does not exist creates a timing gap that tells attackers which emails are registered.
Walk through four requests with a 30-second token lifetime (token_ttl = 30.0) starting at t = 500.0 (matching Example 2):
1. POST /users with {"email": "leo@velo.dev", "password": "cedar-forest-12"} normalizes the email, generates a random salt (random per-user bytes mixed into a password before hashing so identical passwords produce different hashes), stores user 1 in users and user_id_by_email, and returns 201 with Leo's public profile.
2. POST /sessions with Leo's credentials verifies his password hash using a constant-time comparison (a check whose runtime depends only on string length, never on where two strings first differ) and issues an opaque token (a random string carrying no embedded data, looked up on the server) "Xq3..." expiring at t = 530.0.
3. PATCH /users/me with {"display_name": "Leo", "bio": "z" * 281} validates all fields before writing any, returning 400 invalid_bio while leaving display_name untouched at "".
4. At t = 530.0, GET /users/me with "Xq3..." sees 530.0 >= 530.0, deletes "Xq3..." from sessions and tokens_by_user, and returns 401 unauthorized.
Complexity
- Time:
O(1)average per request (plusO(L)in the capped input lengthL), andO(k)to delete an account withkactive tokens. Every route performs a constant number of Python dictionary and set lookups (users,user_id_by_email,sessions,tokens_by_user). Email normalization and password hashing scan strings whose lengths are strictly bounded (<= 254chars for email,<= 128chars for password). Deleting an account loops only over that single user'sklive tokens viatokens_by_user[user_id]instead of scanning all sessions in the service. - Space:
O(U + S)forUregistered users andSactive sessions. Each user occupies one entry inusers,user_id_by_email, andtokens_by_user(roughly ~1 KB per user in Python, or ~1 GB for 1 million users), and each live session adds one entry insessionsplus one reference intokens_by_user. Note that expired tokens that are never presented again stay in memory until lazily swept; a long-running service would add a background cleanup loop or a min-heap ordered byexpires_at.
Edge cases
- Email casing and outer whitespace:
" Maya@Velo.DEV "and"maya@velo.dev"normalize to the exact same key on both signup and login, preventing confusing duplicate accounts. - Exact expiry timestamp (
clock() == expires_at): Valid strictly whilenow < expires_atand rejected as soon asnow >= expires_at. Expired tokens are immediately evicted so clock skew cannot revive them. - Concurrent duplicate signups: Wrapping
handlein athreading.Lockmakes the email existence check and dictionary insertion atomic (indivisible to other threads); in a relational database, aUNIQUEindex enforces this guarantee. - All-or-nothing
PATCH: Sending one valid field alongside one invalid field (or a forbidden field like"email","password", or"is_admin") rejects the entire update with400and mutates nothing. - Overlong passwords on login: Passwords above
128characters are rejected on login after fixed-size dummy hashing, preventing multi-megabyte inputs from stalling the server while keeping the401response identical. - Multi-device logout vs. account deletion:
DELETE /sessionsrevokes only the presented token (e.g., logging out on a tablet keeps a desktop logged in), whereasDELETE /users/merevokes all tokens for that user, frees the email for future signup, and never reuses the old integeruser_id. - Non-dictionary request bodies: Lists, numbers,
None, or malformed JSON from the HTTP adapter cleanly return400 invalid_bodyrather than raisingAttributeErrororTypeError.
Common mistakes
- Returning the internal user dictionary directly: Leaks
password_hashandpassword_salt. Always project responses through an allow-list (an explicit list of permitted public keys). - Revealing whether an email exists on login: Returning
404 user_not_foundfor unknown emails—or returning401noticeably faster because hashing was skipped—lets attackers enumerate your user base. Always return the same401 invalid_credentialsand perform a dummy hash when the email is absent. - Using fast, unsalted hashes in production: Salted SHA-256 is acceptable only as an interview placeholder. Real services must use slow, memory-hard password hashers (Argon2id, bcrypt, or scrypt) so offline brute-force attacks become prohibitively expensive.
- Generating tokens with
randomor comparing hashes with==: Python'srandommodule is predictable; always usesecretsfor tokens and salts, andhmac.compare_digestfor comparing secret digests. - Mutating profile fields while validating: Updating
user[field]inside the validation loop leaves partial writes behind a400response when a later field is invalid. - Confusing
401 Unauthorizedwith403 Forbidden:401means "who are you?" (missing, bad, or expired credentials), whereas403means "I know who you are, and you lack permission." Where every user only accesses/users/me,401is the right status.
Alternative approaches
- Web framework + schema library (FastAPI / Pydantic or Flask): In production Python services, a framework handles URL routing, JSON parsing, and declarative schema validation automatically, while keeping the same clean separation between HTTP transport and core account logic.
- JSON Web Tokens (JWTs) instead of opaque tokens: A JWT (a cryptographically signed JSON payload containing claims like
user_idandexp) lets stateless servers verify tokens without a session-store lookup. The trade-off is revocation: logging out or deleting an account cannot immediately invalidate a stateless JWT before it expires unless you maintain a server-side deny-list anyway. - Auto-login on registration: Having
POST /usersimmediately return a session token saves one network round-trip on signup, though keeping/usersand/sessionsseparate composes cleaner once email verification is required before login.
Follow-up questions
- How would you evolve opaque sessions into a production token architecture across multiple servers? Pair a short-lived access token (say 15 minutes) with a long-lived refresh token (a credential used solely to request new access tokens without re-entering the password). Store only the SHA-256 hash of each refresh token in a shared store like Redis or PostgreSQL alongside device, IP, and
last_used_atmetadata so users can inspect and revoke individual devices. Rotate the refresh token on every refresh, and if an already-rotated token is ever presented again, treat it as token theft and revoke the entire token family. - How would you design a password-reset workflow without revealing which email addresses are registered? Expose
POST /password-resets {"email"}and always return202 Acceptedwhether or not the email exists so attackers cannot probe accounts. When the account exists, generate a high-entropy single-use token, store only its hash with a short expiry (15–30 minutes), and email the reset link. When the user submitsPOST /password-resets/confirm {"token", "new_password"}, verify the hash and expiry, update the password hash with a fresh salt, mark the reset token used, and revoke all existing sessions for that user. - How would you record tamper-resistant audit logs for authentication and account changes? Record an append-only event (
timestamp,user_id,event_typesuch aslogin_succeeded,login_failed,password_changed, oraccount_deleted,ip_address,user_agent,request_id) for every authentication and account lifecycle action—never logging raw passwords or tokens. In a database-backed service, write the audit row in the same database transaction as the state change (using an outbox table, a table written transactionally alongside business data and asynchronously shipped to immutable log storage) so no security change can commit without an audit trail.
Follow-up questions
- How would you evolve opaque sessions into a production token architecture across multiple servers?
- How would you design a password-reset workflow without revealing which email addresses are registered?
- How would you record tamper-resistant audit logs for authentication and account changes?
Similar questions
- Interactive Spoken Role-Play Practice
- Spoken Practice Platform and MVP Auth API
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging