Skip to content

feat(auth): make usernames and emails case-insensitive - #22

Merged
Quick104 merged 1 commit into
mainfrom
feat/case-insensitive-usernames
May 29, 2026
Merged

Quick104 merged 1 commit into
mainfrom
feat/case-insensitive-usernames

Conversation

@Quick104

@Quick104 Quick104 commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Convert users.username and users.email to PostgreSQL citext (migration 165) so login identifiers compare case-insensitively while preserving original casing for display.
  • Add auth.NormalizeUsername/NormalizeEmail (trim-only, case preserved), applied at the repository chokepoints and before validation in create paths.

Problem

Usernames/emails were case-sensitive text with case-sensitive unique constraints, so John and john were distinct accounts and a user could not log in unless the casing matched what they registered with.

Approach & why

  • citext over a LOWER() functional index or storing lowercased values: it makes the existing users_username_key / users_email_key unique indexes case-insensitive automatically and needs no change to the lookup queries (WHERE username = $1 resolves as citext), while preserving display casing.
  • Normalization lives in one auth helper, enforced at the four repository methods (Create, Update, GetByUsername, GetByEmail) where every read/write path converges. The three create handlers (Setup, Signup, admin CreateUser) also normalize before their existing required-field checks, so whitespace-only input is rejected at the boundary.
  • Email is included alongside username — same latent issue, and case-insensitive email is conventional.

Migration / rollout

  • Migration is numbered 165 deliberately: feat/audiobooks already occupies 163/164 and the runner dedupes by version number, so 163 would have been silently skipped on the (audiobooks-lineage) dev DB and collided at merge.
  • Applies automatically on server startup. The down migration reverts to text (intentionally leaves the citext extension installed).
  • Pre-flight on dev: 0 case-collisions across 69 users. ⚠️ Re-run the collision check before applying anywhere with real data — if case-variant duplicates exist, the unique-index rebuild fails inside the migration's transaction (safe rollback, but blocks the migration until resolved).

Risks / follow-up

  • No client (Android/Apple) changes: pure server-side leniency, no API contract change.
  • citext case-folding is locale-dependent for non-ASCII; ASCII identifiers are exactly case-insensitive.

Test plan

  • go build ./..., go vet, gofmt, and go test for internal/auth, internal/api/handlers, internal/jellycompat — all clean
  • Unit tests for NormalizeUsername/NormalizeEmail
  • Non-destructive dev DB dry-run: ADMIN/admin/AdMiN resolve to the same row; case-variant insert rejected by users_username_key; down migration reverts to text
  • Deploy to dev and confirm a real case-insensitive login end-to-end

AI-use disclosure

Implemented with Claude Code (Claude Opus). Design, migration, code, and dev verification were AI-assisted and human-reviewed.


Note

Medium Risk
Touches core identity storage and login matching; migration can block on pre-existing case-colliding username/email pairs when unique indexes are rebuilt.

Overview
Usernames and emails become case-insensitive for login and uniqueness while display casing is kept. Migration 165 enables PostgreSQL citext on users.username and users.email, so existing unique indexes and WHERE username = $1 / email = $1 lookups compare without caring about case.

New auth.NormalizeUsername and auth.NormalizeEmail trim surrounding whitespace only (no lowercasing). They run in UserRepository on create, update, and get-by-username/email, and on setup, signup, and admin create user before required-field validation so whitespace-only identifiers fail at the API boundary.

Unit tests cover the normalizers. Rollout risk: if production already has case-variant duplicates, rebuilding unique indexes can fail until those rows are merged or renamed.

Reviewed by Cursor Bugbot for commit ea2c637. Bugbot is set up for automated code reviews on this repo. Configure here.

Summary by CodeRabbit

Release Notes

  • New Features

    • Usernames and emails are now automatically trimmed of surrounding whitespace during account signup, initial setup, and admin user creation.
    • User login identifiers are now handled case-insensitively—usernames and emails can be entered in any case, while original casing is preserved for display.
  • Tests

    • Added comprehensive tests for username and email normalization functionality.

Review Change Stack

Login identifiers were compared case-sensitively, so "John" and "john"
were distinct accounts and a user could not log in unless they matched the
exact casing used at registration.

Convert users.username and users.email to the citext type (migration 165).
citext compares case-insensitively while preserving the originally stored
casing for display, so the existing unique constraints become
case-insensitive and `WHERE username = $1` / `email = $1` lookups match
regardless of case with no change to the query code itself.

Also add auth.NormalizeUsername/NormalizeEmail (trim-only; case preserved),
applied at the repository chokepoints (Create, Update, GetByUsername,
GetByEmail) and before validation in the create paths, so surrounding
whitespace no longer defeats matching or creates lookalike accounts.

Verified non-destructively against the dev DB: mixed-case lookups resolve
to the same row, case-variant inserts are rejected by the unique
constraint, and the down migration cleanly reverts to text.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@coderabbitai

coderabbitai Bot commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: b6f148b3-f19d-4f47-9997-0706a766bb6c

📥 Commits

Reviewing files that changed from the base of the PR and between 8353880 and ea2c637.

📒 Files selected for processing (7)
  • internal/api/handlers/admin.go
  • internal/api/handlers/auth.go
  • internal/auth/normalize.go
  • internal/auth/normalize_test.go
  • internal/auth/repository.go
  • migrations/165_case_insensitive_username_email.down.sql
  • migrations/165_case_insensitive_username_email.up.sql

📝 Walkthrough

Walkthrough

This PR adds username and email normalization across the authentication and user management flows. Three API handlers normalize user input at request parsing. Normalization functions trim surrounding whitespace while preserving case. A database migration converts username and email columns to PostgreSQL's citext type for case-insensitive comparisons. The repository layer normalizes values before all create, read, and update operations.

Changes

Username and Email Normalization

Layer / File(s) Summary
Normalization functions and tests
internal/auth/normalize.go, internal/auth/normalize_test.go
NormalizeUsername and NormalizeEmail trim surrounding whitespace using strings.TrimSpace. Tests verify trimming, internal spacing/case preservation, and whitespace-only input handling.
Database migration to citext columns
migrations/165_case_insensitive_username_email.up.sql, migrations/165_case_insensitive_username_email.down.sql
Up migration installs citext extension and converts username/email columns to citext for case-insensitive comparison. Down migration reverts columns to text while keeping the extension.
Repository normalization for reads and writes
internal/auth/repository.go
Create normalizes email and username before insert. GetByUsername and GetByEmail normalize lookup parameters. Update normalizes email/username values before SQL updates.
API handler normalization
internal/api/handlers/auth.go, internal/api/handlers/admin.go
HandleSetup, HandleSignup, and HandleCreateUser normalize incoming Username and Email fields from request bodies before validation.

Sequence Diagram(s)

No sequence diagram is needed for this change set. The normalization flow is straightforward (request input → normalize → validate → persist) and does not involve complex multi-step interactions between distinct components that would benefit from visualization beyond what the checkpoint descriptions provide.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

A rabbit hops through fields of text,
Trimming whitespace, never vexed—
Case-insensitive names take flight,
On citext columns, clean and bright. 🐰

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/case-insensitive-usernames

Comment @coderabbitai help to get the list of available commands and usage tips.

@Quick104
Quick104 merged commit b8ae273 into main May 29, 2026
1 of 2 checks passed
@Quick104
Quick104 deleted the feat/case-insensitive-usernames branch May 29, 2026 01:46
Quick104 added a commit to thezak48/silo-server that referenced this pull request Jun 7, 2026
…ive-usernames

feat(auth): make usernames and emails case-insensitive
Quick104 added a commit that referenced this pull request Jun 11, 2026
feat(auth): make usernames and emails case-insensitive
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant