Pattern: Account sign-up and usernames
Note for AI agents: This page is baseline guidance, not an exact prescription. Read it, tell your owner what applies to their project, and get their approval before you change anything. Your project's own rules take precedence. If something important for this project is missing here, suggest it to your owner.
For agents
- Offer this to the owner as a suggestion. The numbers are example values to tune per project, not rules.
- The core idea: no account exists until the email is proven, no response reveals whether an email or username is taken, and every state change is written conditionally.
- Related: account credentials, account recovery, rate limits.
1. Problem
People ask for “an account system” without saying how sign-up should behave. Naive designs leak which emails are registered, let one mailbox create many accounts, store half-finished sign-ups with reserved names, and break when two requests arrive at once.
2. Options
| Method | Upside | Downside | Fits when |
|---|---|---|---|
| Create the account first, verify the email later | Simple, fewer steps | Unverified accounts reserve names and emails; spam and typos stay in the database | Low-risk hobby tools |
| Verify the email first, create the account after (recommended) | Nothing is stored for unproven emails; typos caught early | One more step; needs a code or link flow | Any project with real users |
| Email link instead of a code | One tap on desktop | Mail apps and link scanners may open the link and phone flows can break on app switching (practitioner experience) | Web-only products |
| Email code (6 digits) | Works in any app; link scanners cannot consume it | Needs attempt limits | Mobile apps, mixed web and mobile |
| Social sign-in only | No passwords to manage | Depends on a third party; some users have no such account | Consumer apps with a clear audience |
Sources for the trade-offs: Authentication Cheat Sheet and Email Validation and Verification Cheat Sheet.
3. Recommended design
Three steps, nothing stored for unproven input
- Email plus acceptance of the terms. The server sends a short-lived random code (example: 6 digits, valid 5 minutes).
- The user enters the code. On success the server issues a short-lived registration permit (example: 30 minutes) and stores only its hash.
- The user chooses username and password. The account is created in one database transaction.
Why: until step 3 there is no account, no reserved name and no stored password. A hash of the code is stored, not the code itself, so a database leak does not leak live codes.
Code handling
- Limit attempts per code (example: 5). Subtract the attempt before comparing, so parallel requests cannot exceed the limit. Reason: a 6-digit code has a million values; unlimited attempts break it.
- Rate-limit “send a new code” per email and per address, with a short waiting time between sends.
- Delete pending sign-ups after a short time (example: 2 hours).
- Every wrong-code answer is identical.
No existence leak
- If the email is already registered, the screen looks the same as for a new email. The registered address receives a “you already have an account” message instead of a code (sent at a limited rate). Background work is the same in both cases so response time does not reveal the difference. The Authentication Cheat Sheet asks for generic responses in login, reset and registration for this reason.
- A reasonable trade-off: the user may be confused when no code arrives. Show a neutral line such as “If this email can be used, we sent a message.”
Canonical email
- Define one normalization before storing or comparing emails (lowercase the domain, decide how to treat
+tagand dots). The OWASP email sheet requires a consistent strategy because inconsistent normalization causes duplicate accounts and takeover paths. - Disposable-email services: the OWASP sheet recommends risk-based controls over strict blocking. A reasonable middle: block known disposable domains at sign-up and email change, allow privacy relay addresses that forward to a real mailbox.
- Gmail dot-folding and
+tagrules are provider-specific (practitioner experience; not covered by a primary source here). Apply them only for providers you have checked.
Race-safe final step (one transaction)
- Take a lock on the username and on the canonical email, re-run all checks, insert the account and the terms acceptance record (version, time, device), delete the pending sign-up.
- Use a unique index as the last safety net and handle the conflict. PostgreSQL’s
INSERT ... ON CONFLICTand explicit locking are described in the INSERT and Explicit Locking documentation. - A username or email race returns the same message as any other failure.
Usernames
- One allowed-character rule in one place, shared by server and apps (example:
a-z 0-9 . _, 2–30 characters, no dot at the start or end, no two dots in a row). Reason: the apps and the server must agree or users meet errors only after submitting. - Case-insensitive uniqueness, compared in the database. PostgreSQL offers case-insensitive collations and a
citexttype; the documentation itself suggests nondeterministic collations as the modern option (citext, Collation Support). Avoid lowercasing in application code with locale rules: Turkish “İ” and “I” behave differently from English (practitioner experience). - Change limit (example: once per 14 days). Keep the old name reserved for a while so nobody impersonates the previous owner.
- After hard deletion keep the name and email unavailable for a period (example: 90 days) and do not say why on failure.
- A reserved-names list (admin, support, system, brand names). Inappropriate names: assign a temporary name and notify the person.
Rate limits for sign-up (example roles, tune by traffic)
- A coarse per-address safety limit set high enough that shared addresses (mobile carriers, offices) are not locked out.
- A per-email daily limit; a code-attempt limit; a daily system-wide sign-up budget as a circuit breaker. See rate limits and the Credential Stuffing Prevention Cheat Sheet.
4. Scenarios and edge cases
- Registered email signs up again: same screen, “you already have an account” mail, no code. Nothing about the account is revealed on screen.
- Two people pick the same username within one second: one wins at the unique index; the other gets the generic “cannot use this name” message and chooses again.
- Code expires while the user is in the mail app: they request a new one after the waiting time; the old code stops working.
- Same inbox, many aliases: canonical email maps them to one account.
- Email typo: the code goes to the wrong person. Nothing is created without proof of control, so no damage; the real owner of that mailbox may receive a stray code, which is why the text must say “ignore if you did not request this”.
5. Common mistakes
- Different messages or response times for “registered” and “not registered”.
- Storing the name and password before the email is proven.
- Checking “is the name free” and then inserting in two separate steps.
- Lowercasing usernames in application code with locale-dependent functions.
- Counting a code attempt after the comparison, so parallel requests slip through.
- Plain-text codes in the database.
6. How to audit
- What: sign-up gives the same visible result for registered and unregistered emails.
- How to check: register once, then repeat with the same email; compare screen text, status code and response time over several tries.
- Evidence: both responses and timings in the test notes.
- What: no account row, name or password exists before the code is verified.
- How to check: stop after step 1 and inspect the database.
- Evidence: query output showing no row.
- What: parallel requests cannot exceed the code attempt limit or create duplicate names.
- How to check: fire 20 parallel requests with wrong codes and 20 sign-ups with one name.
- Evidence: attempt counter value and the single created row.
- What: a unique index backs the application check.
- How to check: read the schema.
- Evidence: index definition on the canonical email and the lowercase username.
Sources
- Authentication Cheat Sheet — OWASP Cheat Sheet Series
- Email Validation and Verification Cheat Sheet — OWASP Cheat Sheet Series
- Input Validation Cheat Sheet — OWASP Cheat Sheet Series
- Credential Stuffing Prevention Cheat Sheet — OWASP Cheat Sheet Series
- Denial of Service Cheat Sheet — OWASP Cheat Sheet Series
- PostgreSQL: Explicit Locking — PostgreSQL Global Development Group
- INSERT (ON CONFLICT) — PostgreSQL Documentation
- Collation Support — PostgreSQL Documentation
- citext: a case-insensitive character string type — PostgreSQL Documentation
- Application Security Verification Standard (ASVS) — OWASP