{"id":50759994,"url":"https://github.com/deicod/auth","last_synced_at":"2026-06-11T09:01:16.569Z","repository":{"id":358667602,"uuid":"1094863327","full_name":"deicod/auth","owner":"deicod","description":"reusable auth package with postgresql, sqlite or mongodb database backends","archived":false,"fork":false,"pushed_at":"2026-05-18T12:45:56.000Z","size":332,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-05-18T14:38:35.400Z","etag":null,"topics":["auth","authentication","mongodb","postgresql","sqlite","sqlite3"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/deicod.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":"AGENTS.md","dco":null,"cla":null},"funding":{"github":"deicod"}},"created_at":"2025-11-12T09:20:07.000Z","updated_at":"2026-05-18T12:46:00.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/deicod/auth","commit_stats":null,"previous_names":["deicod/auth"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/deicod/auth","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deicod%2Fauth","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deicod%2Fauth/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deicod%2Fauth/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deicod%2Fauth/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/deicod","download_url":"https://codeload.github.com/deicod/auth/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deicod%2Fauth/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34190585,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-11T02:00:06.485Z","response_time":57,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["auth","authentication","mongodb","postgresql","sqlite","sqlite3"],"created_at":"2026-06-11T09:01:15.486Z","updated_at":"2026-06-11T09:01:16.491Z","avatar_url":"https://github.com/deicod.png","language":"Go","funding_links":["https://github.com/sponsors/deicod"],"categories":[],"sub_categories":[],"readme":"# Auth\n\n`github.com/deicod/auth` is a storage-agnostic authentication module that bundles the domain model, services and HTTP transport needed for user registration, login, email verification, password resets and email change flows. The package exposes a single `auth.Service` interface while letting you pick the persistence layer (`mgo` for MongoDB or `pgx` for PostgreSQL) at runtime.\n\n## Highlights\n- `auth.Service` defines the full authentication surface (register, login, forgot/reset password, email verification/change) and can be backed by MongoDB or PostgreSQL without touching the rest of your code.\n- `core` holds the shared commands, results, errors and user/session representations to keep handlers and services storage-neutral.\n- Ready-to-use HTTP handlers (`handlers.AuthHandlers`) turn the service into JSON endpoints for `/register`, `/login`, `/logout`, `/me`, email verification and password reset workflows.\n- Security defaults baked in: Argon2id password hashing, opaque session tokens, short-lived verification/reset/email-change tokens and SMTP integrations for transactional emails.\n- Rich configuration via `auth.Config` with sensible defaults plus knobs for session lifetime, token TTLs, Argon2 parameters and mail transport.\n- PGX backend ships with embedded SQL migrations, while the Mongo backend wires collections, indexes and repositories for you.\n\n## Package Map\n\n| Path | Description |\n| --- | --- |\n| `auth.go` | Backend switch + `auth.Service` interface definition. |\n| `core/` | Domain layer: command DTOs, public models, shared errors and result structs. |\n| `handlers/` | JSON HTTP handlers that wrap any `auth.Service`. |\n| `mgo/` | MongoDB service implementation, repositories and configuration helpers. |\n| `pgx/` | PostgreSQL (pgxpool) implementation with migrations and repositories. |\n| `sqlite/` | SQLite (CGO) implementation with migrations and repositories. |\n| `config/` | Shared configuration structs for sessions, tokens, Argon2 and SMTP. |\n| `email/` | SMTP sender implementation with a `NopSender` fallback. |\n\n## Installation\n\n```bash\ngo get github.com/deicod/auth\n```\n\n## Config Overview\n\nStart with `auth.DefaultConfig()` and override what you need. Important fields:\n\n| Field | Purpose | Default |\n| --- | --- | --- |\n| `Backend` | `auth.BackendMongo`, `auth.BackendPostgres` or `auth.BackendSQLite`. | `auth.BackendMongo` |\n| `Mongo` | Pointer to `mgo.Config` (URI, db name, collection names, operation timeout). | `mgo.DefaultConfig()` |\n| `Pgx` | Pointer to `pgx.Config` (DSN, pool sizing, health checks, timeouts). | `pgx.DefaultConfig()` |\n| `Sqlite` | Pointer to `sqlite.Config` (DSN, connection pool settings). | `sqlite.DefaultConfig()` |\n| `Session` | Controls session length (`config.Session`). | 30 days |\n| `Tokens` | TTLs for verification/reset/email-change tokens (`config.Tokens`). | 48h/1h/24h |\n| `Argon2` | Cost settings for Argon2id hashing (`config.Argon2`). | Time=3, Memory=64MiB |\n| `Email` | SMTP transport (`config.Mail`). Empty `Host` disables email sending (uses `email.NopSender`). | See `config/mail.go` |\n\n### Mongo Config (`mgo.Config`)\n- `URI`: Mongo connection string.\n- `Database`: database name.\n- `{Users,Sessions,Verification,PasswordReset,EmailChange}Collection`: collection names (defaults provided).\n- `OperationTimeout`: per call timeout for repository operations.\n- The Mongo service now ensures the essential indexes (unique `email`/`username`, unique `token_hash` values, TTL on `expires_at`) the first time it connects, so tokens and sessions expire automatically even if you forget to add indexes manually.\n\n### PostgreSQL Config (`pgx.Config`)\n- `DSN`: PostgreSQL connection string (e.g. `postgres://user:pass@localhost:5432/auth?sslmode=disable`).\n- `MaxConns`, `MinConns`, `HealthCheckInterval`, `MaxConnLifetime`, `MaxConnIdleTime`: passed to `pgxpool`.\n- `OperationTimeout`: context deadline used by repositories.\n- Embedded migrations now create helper indexes on `expires_at` for sessions and token tables, so scheduled cleanup jobs (or `DELETE ... WHERE expires_at \u003c now()`) stay efficient. PostgreSQL does not support TTL indexes natively, so you still need a periodic cleanup job if you want automatic removal.\n\n\u003e ℹ️ The pgx backend applies embedded SQL migrations automatically and expects PostgreSQL 18+ (for the `uuidv7()` default). If you're on an older version, replace the default in `pgx/migrations/0001_init.sql` or create the function manually.\n\n### SQLite Config (`sqlite.Config`)\n- `DSN`: SQLite connection string (e.g. `file:auth.db?_foreign_keys=on`). Use `:memory:` for in-memory.\n- `MaxOpenConns`, `MaxIdleConns`, `ConnMaxLifetime`: Connection pool settings.\n- `OperationTimeout`: Context deadline for queries.\n- SQL migrations are embedded and applied automatically on connection.\n\n## Example: MongoDB Backend (`mgo`)\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"log\"\n    \"net/http\"\n\n    \"github.com/deicod/auth\"\n    \"github.com/deicod/auth/handlers\"\n)\n\nfunc main() {\n    ctx := context.Background()\n\n    cfg := auth.DefaultConfig()\n    cfg.Backend = auth.BackendMongo\n    cfg.Mongo.URI = \"mongodb://localhost:27017\"\n    cfg.Mongo.Database = \"auth_demo\"\n\n    svc, err := auth.NewService(ctx, cfg)\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer closeService(ctx, svc)\n\n    authHandlers := handlers.New(svc)\n    mux := http.NewServeMux()\n    mux.Handle(\"/auth/register\", authHandlers.Register())\n    mux.Handle(\"/auth/login\", authHandlers.Login())\n    mux.Handle(\"/auth/logout\", authHandlers.Logout())\n    mux.Handle(\"/auth/me\", authHandlers.Me())\n    mux.Handle(\"/auth/verify\", authHandlers.VerifyEmail())\n    mux.Handle(\"/auth/forgot\", authHandlers.ForgotPassword())\n    mux.Handle(\"/auth/reset\", authHandlers.ResetPassword())\n    mux.Handle(\"/auth/email-change\", authHandlers.InitiateEmailChange())\n    mux.Handle(\"/auth/email-confirm\", authHandlers.ConfirmEmailChange())\n\n    log.Println(\"auth API listening on :8080\")\n    log.Fatal(http.ListenAndServe(\":8080\", mux))\n}\n\nfunc closeService(ctx context.Context, svc auth.Service) {\n    if closer, ok := svc.(interface{ Close(context.Context) error }); ok {\n        _ = closer.Close(ctx)\n    }\n}\n```\n\nSample request/response:\n\n```bash\ncurl -X POST http://localhost:8080/auth/register \\\n  -H 'Content-Type: application/json' \\\n  -d '{\"email\":\"alice@example.com\",\"username\":\"alice\",\"password\":\"Sup3rSecret\"}'\n\n# =\u003e {\"user\":{\"id\":\"...\",\"email\":\"alice@example.com\",\"username\":\"alice\"},\"session\":{\"id\":\"...\",\"expires_at\":\"...\"},\"token\":\"opaque-session-token\"}\n```\n\nEmails are sent only when `cfg.Email.Host` is set. Without SMTP configuration the service still works, but verification/reset tokens are stored and must be delivered manually for testing.\n\n## Example: PostgreSQL Backend (`pgx`)\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"log\"\n    \"net/http\"\n    \"time\"\n\n    \"github.com/deicod/auth\"\n    \"github.com/deicod/auth/handlers\"\n)\n\nfunc main() {\n    ctx := context.Background()\n\n    cfg := auth.DefaultConfig()\n    cfg.Backend = auth.BackendPostgres\n    cfg.Pgx.DSN = \"postgres://auth:auth@localhost:5432/auth?sslmode=disable\"\n    cfg.Pgx.MaxConns = 8\n    cfg.Session.Length = 14 * 24 * time.Hour\n    cfg.Tokens.ResetTTL = 15 * time.Minute\n\n    svc, err := auth.NewService(ctx, cfg)\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer closeService(ctx, svc)\n\n    router := http.NewServeMux()\n    authHandlers := handlers.New(svc)\n    router.Handle(\"/auth/register\", authHandlers.Register())\n    router.Handle(\"/auth/login\", authHandlers.Login())\n    router.Handle(\"/auth/logout\", authHandlers.Logout())\n    router.Handle(\"/auth/me\", authHandlers.Me())\n    router.Handle(\"/auth/verify\", authHandlers.VerifyEmail())\n    router.Handle(\"/auth/forgot\", authHandlers.ForgotPassword())\n    router.Handle(\"/auth/reset\", authHandlers.ResetPassword())\n    router.Handle(\"/auth/email-change\", authHandlers.InitiateEmailChange())\n    router.Handle(\"/auth/email-confirm\", authHandlers.ConfirmEmailChange())\n\n    log.Fatal(http.ListenAndServe(\":3000\", router))\n}\n\nfunc closeService(ctx context.Context, svc auth.Service) {\n    if closer, ok := svc.(interface{ Close(context.Context) error }); ok {\n        _ = closer.Close(ctx)\n    }\n}\n```\n\nThe pgx service automatically runs the embedded migration (`pgx/migrations/0001_init.sql`) when it connects. Ensure the configured database user can create tables and that the `uuid-ossp` extension or PostgreSQL 16+ UUID helpers are available.\n\n## Example: SQLite Backend (`sqlite`)\n\n```go\npackage main\n\nimport (\n\t\"context\"\n\t\"log\"\n\t\"net/http\"\n\n\t\"github.com/deicod/auth\"\n\t\"github.com/deicod/auth/handlers\"\n)\n\nfunc main() {\n\tctx := context.Background()\n\n\tcfg := auth.DefaultConfig()\n\tcfg.Backend = auth.BackendSQLite\n\tcfg.Sqlite.DSN = \"file:auth.db?_foreign_keys=on\"\n\n\tsvc, err := auth.NewService(ctx, cfg)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer closeService(ctx, svc)\n\n\t// mount handlers...\n}\n```\n\n## HTTP Handlers \u0026 JSON Contracts\n\nAll handlers accept/return JSON and bubble up `core` errors with appropriate HTTP status codes.\n\n| Handler | Method + Path | Request Body | Response | Rate Limit (per IP) |\n| --- | --- | --- | --- | --- |\n| `Register()` | `POST /auth/register` | `{email, username, password}` | `core.AuthResult` (user, session, token). | 5 req/min |\n| `Login()` | `POST /auth/login` | `{email, password}` | `core.AuthResult`. | 5 req/min |\n| `Logout()` | `POST /auth/logout` | Bearer token header | `204 No Content`. | 20 req/min |\n| `Me()` | `GET /auth/me` | Bearer token header | `{user, session}`. | 60 req/min |\n| `VerifyEmail()` | `POST /auth/verify` | `{token}` | `core.VerifyEmailResult`. | 5 req/min |\n| `ForgotPassword()` | `POST /auth/forgot` | `{email}` | `{\"status\":\"email_sent\"}`. | 5 req/min |\n| `ResetPassword()` | `POST /auth/reset` | `{token, new_password}` | `core.UserPublic`. | 5 req/min |\n| `InitiateEmailChange()` | `POST /auth/email-change` | `{user_id, password, new_email}` | `{\"status\":\"email_sent\"}`. | 5 req/min |\n| `ConfirmEmailChange()` | `POST /auth/email-confirm` | `{token}` | `core.ChangeEmailResult`. | 5 req/min |\n\nUse the helpers in `core/errors.go` to distinguish conflicts, bad requests, unauthorized cases, etc., if you need to customize error rendering.\n\n## Middleware Usage\n\n`Register` and `Login` both return an opaque session token. Store it client-side and send it as `Authorization: Bearer \u003ctoken\u003e` on requests that hit your own APIs. The service exposes `AuthenticateSession`, and the `middleware` package wraps it for you:\n\n```go\nimport (\n    \"net/http\"\n\n    \"github.com/deicod/auth/middleware\"\n)\n\nrequireAuth := middleware.RequireAuth(svc)\nmux.Handle(\"/profile\", requireAuth(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n    if user, ok := middleware.UserFromContext(r.Context()); ok {\n        respondJSON(w, http.StatusOK, user)\n        return\n    }\n    http.Error(w, \"user missing\", http.StatusInternalServerError)\n})))\n```\n\n`middleware.SessionFromContext` is also available if you need to inspect the active session (user agent, IP, expiry, etc.). No additional database wiring is required—the middleware simply calls `svc.AuthenticateSession`, which hashes the bearer token, fetches the session record via the configured backend and returns the associated user.\n\n## Tokens, Sessions and Email\n\n- Sessions store a hashed token plus metadata (IP, user-agent) and respect `config.Session.Length`.\n- Password resets revoke all of the user's existing sessions to force fresh logins.\n- Verification, password reset and email-change tokens are short-lived; customize TTLs through `cfg.Tokens`.\n- Passwords use Argon2id (via `cfg.Argon2`). Raising `Memory` or `Time` enforces stronger hashing requirements.\n- Set `cfg.Email` to an SMTP server (host, port, credentials, `UseSSL`) to enable automated verification/reset/email-change emails. With an empty host, the `email.NopSender` satisfies the interface so the flows still succeed in tests.\n\n## Error Handling\n\nService methods return errors from `core/errors.go` (`ErrEmailExists`, `ErrInvalidCredentials`, `ErrTokenExpired`, etc.). The provided handlers already translate them to HTTP status codes, but you can wrap the service with your own transport knowing the error contracts are consistent across backends.\n\n## Development Tips\n- When switching backends, reuse the same handlers and only change `cfg.Backend` plus backend-specific config.\n- For integration tests, keep SMTP disabled and read verification/reset tokens directly from the database collections/tables.\n- The service implementations expose `Close(context.Context) error`; type-assert the returned `auth.Service` if you need to cleanly close Mongo clients or pgx pools at shutdown.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdeicod%2Fauth","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdeicod%2Fauth","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdeicod%2Fauth/lists"}