auth

package module
v0.53.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2026 License: GPL-3.0 Imports: 42 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README ยถ

Auth

Tests Status Go Report Card PkgGoDev

Batteries-included authentication library for Go with ready-to-use UI pages, API endpoints, and middleware. You bring your own database and email serviceโ€”we handle the rest.

๐Ÿ“– Documentation

Read the full documentation โ€” guides, feature docs, and peer comparisons (also browsable in docs/).

โœจ Features

  • ๐Ÿ” Four Composable Login Methods

    • Email OTP - Otp verification codes
    • Magic Link - Single-use emailed sign-in links
    • Username/Password - Traditional authentication with password storage
    • AuthKnight - Delegated hosted login (external service verifies the user)
    • Multi-method mux - combine methods via NewMultiMethodAuth; custom methods via types.Method
  • ๐Ÿ›ก๏ธ Production-Grade Security

    • Structured error handling with error codes (no internal details leaked)
    • CSRF protection via dracory/csrf integration
    • Rate limiting with per-IP/per-endpoint lockout
    • Session invalidation on password reset
    • Constant-time password comparison to prevent timing attacks
    • Secure cookie defaults (HttpOnly, SameSite, Secure on HTTPS)
    • Input validation and HTML escaping
    • Structured logging with log/slog for audit trails
  • ๐ŸŽจ Complete UI Included

    • Pre-built HTML pages (login, registration, password reset)
    • Bootstrap-styled and customizable
    • Works out of the box
  • ๐Ÿš€ JSON API Endpoints

    • Ready for SPAs and mobile apps
    • RESTful design
    • Comprehensive error handling
  • ๐Ÿ›ก๏ธ Authentication Middleware

    • WebAuthOrRedirectMiddleware - For web pages
    • ApiAuthOrErrorMiddleware - For API routes
    • WebAppendUserIdIfExistsMiddleware - Optional authentication
  • ๐ŸŽญ Impersonation

    • Opt-in administrator "login as" feature
    • Secure token swap with one-level chain guard
    • Audit hooks and observability integration
  • ๐Ÿ”ง Implementation Agnostic

    • Works with any database (SQL, NoSQL, in-memory)
    • Bring your own email service
    • Callback-based architecture for maximum flexibility
  • ๐Ÿšฆ Built-in Rate Limiting

    • Per-IP and per-endpoint limits on authentication endpoints
    • Sensible defaults (5 attempts per 15 minutes, 15-minute lockout)
    • Fully configurable or replaceable with a custom rate limiter
  • โœ… Production Ready

    • 90.2% test coverage
    • 34 comprehensive test files
    • Battle-tested security practices

๐Ÿ“ฆ Installation

go get github.com/dracory/auth

๐Ÿ“ Project Structure

The library is organized into focused packages: types/ for configuration, utils/ for utilities, internal/ for implementation, and examples/ for working applications.

For detailed information about the package organization, see docs/project-structure.html.

๐Ÿš€ Quick Start

Choose Your Flow
AuthKnight (Recommended) Otp Username/Password
import (
  "github.com/dracory/auth"
  "github.com/dracory/auth/types"
)

auth, err := auth.NewAuthKnightAuth(
  types.ConfigAuthKnight{
    ConfigShared: types.ConfigShared{
      Endpoint: "/auth",
      UrlRedirectOnSuccess: "/dashboard",
      UseCookies: true,
      // ... implement callbacks
    },
    // ... AuthKnight-specific callbacks
  },
)
import (
  "github.com/dracory/auth"
  "github.com/dracory/auth/types"
)

auth, err := auth.NewOtpAuth(
  types.ConfigOtp{
    Endpoint: "/auth",
    UrlRedirectOnSuccess: "/dashboard",
    UseCookies: true,
    // ... implement callbacks
  },
)
import (
  "github.com/dracory/auth"
  "github.com/dracory/auth/types"
)

auth, err := auth.NewUsernameAndPasswordAuth(
  types.ConfigUsernameAndPassword{
    Endpoint: "/auth",
    UrlRedirectOnSuccess: "/dashboard",
    UseCookies: true,
    // ... implement callbacks
  },
)
Attach to Router
mux := http.NewServeMux()

// Attach auth routes
mux.HandleFunc("/auth/", auth.Router().ServeHTTP)

// Public route
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Welcome! <a href='" + auth.LinkLogin() + "'>Login</a>"))
})

// Protected route
mux.Handle("/dashboard", auth.WebAuthOrRedirectMiddleware(dashboardHandler))
Get Current User
func dashboardHandler(w http.ResponseWriter, r *http.Request) {
    userID := auth.GetCurrentUserID(r)
    // Use userID to fetch user data from your database
    fmt.Fprintf(w, "Welcome, user %s!", userID)
}

๐Ÿ“š Complete Examples

Otp Flow
Step 1: Implement Required Functions
// Email sending
func emailSend(ctx context.Context, email string, subject string, body string) error {
    // Use your email service (SendGrid, AWS SES, SMTP, etc.)
    return yourEmailService.Send(email, subject, body)
}

// User lookup by email
func userFindByEmail(ctx context.Context, email string, options types.UserAuthOptions) (userID string, err error) {
    // Query your database
    user, err := db.Query("SELECT id FROM users WHERE email = ?", email)
    if err != nil {
        return "", err
    }
    return user.ID, nil
}

// User registration (optional, if EnableRegistration is true)
func userRegister(ctx context.Context, email string, firstName string, lastName string, options types.UserAuthOptions) error {
    // Insert into your database
    _, err := db.Exec("INSERT INTO users (email, first_name, last_name) VALUES (?, ?, ?)", 
        email, firstName, lastName)
    return err
}

// User logout
func userLogout(ctx context.Context, userID string, options types.UserAuthOptions) error {
    // Remove token from your session/cache store
    return sessionStore.Delete("auth_token_" + userID)
}

// Token storage
func userStoreAuthToken(ctx context.Context, token string, userID string, options types.UserAuthOptions) error {
    // Store in session/cache with expiration (e.g., 2 hours)
    return sessionStore.Set("auth_token_"+token, userID, 2*time.Hour)
}

// Token lookup
func userFindByAuthToken(ctx context.Context, token string, options types.UserAuthOptions) (userID string, err error) {
    // Retrieve from session/cache
    userID, err = sessionStore.Get("auth_token_" + token)
    return userID, err
}

// Temporary key storage (for verification codes)
func tempKeySet(key string, value string, expiresSeconds int) error {
    // Store temporarily (e.g., in Redis, cache, or database)
    return cacheStore.Set(key, value, time.Duration(expiresSeconds)*time.Second)
}

func tempKeyGet(key string) (value string, err error) {
    // Retrieve temporary key
    return cacheStore.Get(key)
}
Step 2: Configure Authentication
authInstance, err := auth.NewOtpAuth(types.ConfigOtp{
    // Required
    Endpoint:                "/auth",
    UrlRedirectOnSuccess:    "/dashboard",
    UseCookies:              true, // OR UseLocalStorage: true
    FuncUserFindByAuthToken: userFindByAuthToken,
    FuncUserFindByEmail:     userFindByEmail,
    FuncUserLogout:          userLogout,
    FuncUserStoreAuthToken:  userStoreAuthToken,
    FuncEmailSend:           emailSend,
    FuncTemporaryKeyGet:     tempKeyGet,
    FuncTemporaryKeySet:     tempKeySet,
    
    // Optional
    EnableRegistration:           true,
    FuncUserRegister:             userRegister,
    FuncEmailTemplateLoginCode:   customLoginEmailTemplate,    // optional
    FuncEmailTemplateRegisterCode: customRegisterEmailTemplate, // optional
    FuncLayout:                   customPageLayout,             // optional
    DisableRateLimit:             false,                        // optional
    MaxLoginAttempts:             5,                            // optional
    LockoutDuration:              15 * time.Minute,             // optional
    FuncCheckRateLimit:           nil,                          // optional
})
Step 3: Setup Routes
mux := http.NewServeMux()

// Auth routes
mux.HandleFunc("/auth/", authInstance.Router().ServeHTTP)

// Public routes
mux.HandleFunc("/", homeHandler)

// Protected routes (web)
mux.Handle("/dashboard", authInstance.WebAuthOrRedirectMiddleware(dashboardHandler))
mux.Handle("/profile", authInstance.WebAuthOrRedirectMiddleware(profileHandler))

// Protected routes (API)
mux.Handle("/api/data", authInstance.ApiAuthOrErrorMiddleware(apiDataHandler))

// Optional auth (works for both authenticated and guest users)
mux.Handle("/products", authInstance.WebAppendUserIdIfExistsMiddleware(productsHandler))

http.ListenAndServe(":8080", mux)
Username/Password Flow
Step 1: Implement Required Functions
// User login with password verification
func userLogin(ctx context.Context, username string, password string, options types.UserAuthOptions) (userID string, err error) {
    // Query database and verify password (use bcrypt or similar)
    user, err := db.Query("SELECT id, password_hash FROM users WHERE email = ?", username)
    if err != nil {
        return "", err
    }
    
    if !bcrypt.CompareHashAndPassword(user.PasswordHash, []byte(password)) {
        return "", errors.New("invalid credentials")
    }
    
    return user.ID, nil
}

// User registration with password
func userRegister(ctx context.Context, username string, password string, firstName string, lastName string, options types.UserAuthOptions) error {
    // Hash password
    hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
    if err != nil {
        return err
    }
    
    // Insert into database
    _, err = db.Exec("INSERT INTO users (email, password_hash, first_name, last_name) VALUES (?, ?, ?, ?)",
        username, hashedPassword, firstName, lastName)
    return err
}

// User lookup by username
func userFindByUsername(ctx context.Context, username string, firstName string, lastName string, options types.UserAuthOptions) (userID string, err error) {
    // Query database (firstName and lastName used for password reset verification)
    user, err := db.Query("SELECT id FROM users WHERE email = ? AND first_name = ? AND last_name = ?",
        username, firstName, lastName)
    if err != nil {
        return "", err
    }
    return user.ID, nil
}

// Password change
func userPasswordChange(ctx context.Context, username string, newPassword string, options types.UserAuthOptions) error {
    // Hash new password
    hashedPassword, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
    if err != nil {
        return err
    }
    
    // Update in database
    _, err = db.Exec("UPDATE users SET password_hash = ? WHERE email = ?", hashedPassword, username)
    return err
}

// Other functions same as passwordless (userLogout, userStoreAuthToken, etc.)
Step 2: Configure Authentication
authInstance, err := auth.NewUsernameAndPasswordAuth(types.ConfigUsernameAndPassword{
    // Required
    Endpoint:                "/auth",
    UrlRedirectOnSuccess:    "/dashboard",
    UseCookies:              true,
    FuncUserFindByAuthToken: userFindByAuthToken,
    FuncUserFindByUsername:  userFindByUsername,
    FuncUserLogin:           userLogin,
    FuncUserLogout:          userLogout,
    FuncUserStoreAuthToken:  userStoreAuthToken,
    FuncEmailSend:           emailSend,
    FuncTemporaryKeyGet:     tempKeyGet,
    FuncTemporaryKeySet:     tempKeySet,
    
    // Optional
    EnableRegistration:               true,
    EnableVerification:               true, // Require email verification
    FuncUserRegister:                 userRegister,
    FuncUserPasswordChange:           userPasswordChange,
    FuncEmailTemplatePasswordRestore: customPasswordResetEmailTemplate, // optional
    FuncLayout:                       customPageLayout,                  // optional
    DisableRateLimit:                 false,                             // optional
    MaxLoginAttempts:                 5,                                  // optional
    LockoutDuration:                  15 * time.Minute,                   // optional
    FuncCheckRateLimit:               nil,                                // optional
})
AuthKnight Flow

AuthKnight provides passwordless authentication via a hosted login page. The user authenticates on AuthKnight's site, and upon success is redirected back to your application with a verified email.

authInstance, err := auth.NewAuthKnightAuth(types.ConfigAuthKnight{
    ConfigShared: types.ConfigShared{
        Endpoint:                "/auth",
        UrlRedirectOnSuccess:    "/dashboard",
        UseCookies:              true,
        EnableRegistration:      true,
        FuncUserFindByAuthToken: userFindByAuthToken,
        FuncUserLogout:          userLogout,
        FuncUserStoreAuthToken:  userStoreAuthToken,
        FuncTemporaryKeyGet:     tempKeyGet,
        FuncTemporaryKeySet:     tempKeySet,
    },
    FuncUserFindByEmail: userFindByEmail,
    FuncUserRegister:    userRegister,
})

For full configuration details, URL helpers, page behavior, and security notes, see docs/authknight.html.

๐Ÿ”Œ Available Endpoints

Once configured, the following endpoints are automatically available:

API Endpoints (JSON responses)
Method Endpoint Description
POST /auth/api/login Initiate login (sends code for passwordless)
POST /auth/api/login-code-verify Verify passwordless login code
POST /auth/api/logout Logout user
POST /auth/api/register Initiate registration
POST /auth/api/register-code-verify Verify registration code
POST /auth/api/restore-password Request password reset
POST /auth/api/reset-password Complete password reset
POST /auth/api/impersonate/start Begin impersonating a user (requires config)
POST /auth/api/impersonate/stop Exit impersonation and return to admin session
GET /auth/api/authknight/callback AuthKnight redirect endpoint (receives once token)
Page Endpoints (HTML responses)
Method Endpoint Description
GET /auth/login Login page
GET /auth/login-code-verify Code verification page
GET /auth/logout Logout page
GET /auth/register Registration page
GET /auth/register-code-verify Registration verification page
GET /auth/password-restore Password restore request page
GET /auth/password-reset?t=TOKEN Password reset page

๐Ÿ›ก๏ธ Middleware Options

WebAuthOrRedirectMiddleware

For web pages - redirects to login if not authenticated:

mux.Handle("/dashboard", auth.WebAuthOrRedirectMiddleware(dashboardHandler))
ApiAuthOrErrorMiddleware

For API endpoints - returns JSON error if not authenticated:

mux.Handle("/api/profile", auth.ApiAuthOrErrorMiddleware(profileHandler))
WebAppendUserIdIfExistsMiddleware

Optional authentication - adds userID to context if authenticated, but doesn't redirect/error:

mux.Handle("/products", auth.WebAppendUserIdIfExistsMiddleware(productsHandler))

func productsHandler(w http.ResponseWriter, r *http.Request) {
    userID := auth.GetCurrentUserID(r)
    if userID != "" {
        // Show personalized products
    } else {
        // Show public products
    }
}

๐ŸŽจ Customization

Custom Email Templates
func customLoginEmailTemplate(ctx context.Context, email string, code string, options types.UserAuthOptions) string {
    return fmt.Sprintf(`
        <h1>Your Login Code</h1>
        <p>Hi %s,</p>
        <p>Your verification code is: <strong>%s</strong></p>
        <p>This code will expire in 1 hour.</p>
    `, email, code)
}

// Use in config
FuncEmailTemplateLoginCode: customLoginEmailTemplate,
Custom Page Layout
// The signature matches blogadmin/shopadmin โ€” the function renders the
// ENTIRE document, so auth pages can be embedded inside your site shell
// (nav, footer, your own <head>). options carries the assets the page
// needs (Bootstrap, jQuery, page scripts) โ€” inject them or the built-in
// forms will break. Return "" to fall back to the default page.
func customPageLayout(w http.ResponseWriter, r *http.Request, title string, body string, options types.LayoutOptions) string {
    var styles strings.Builder
    for _, s := range options.Styles {
        styles.WriteString("<style>" + s + "</style>")
    }
    for _, u := range options.StyleURLs {
        styles.WriteString(`<link rel="stylesheet" href="` + u + `">`)
    }
    var scripts strings.Builder
    for _, u := range options.ScriptURLs {
        scripts.WriteString(`<script src="` + u + `"></script>`)
    }
    for _, s := range options.Scripts {
        scripts.WriteString(s)
    }
    return fmt.Sprintf(`<!DOCTYPE html>
        <html>
        <head>
            <title>%s - My App</title>
            <link rel="stylesheet" href="/css/custom.css">
            %s
        </head>
        <body>
            <nav>My App</nav>
            <div class="container">%s</div>
            %s
        </body>
        </html>`, title, styles.String(), body, scripts.String())
}

// Use in config
FuncLayout: customPageLayout,

Every built-in page's copy can be overridden field-by-field โ€” empty fields fall back to the package defaults, so you only set what you want to change:

PageOptions: types.PageOptions{
    Login: types.LoginPageOptions{
        Title:       "Welcome back",
        SubmitLabel: "Let me in",
    },
    MagicLink: types.MagicLinkPageOptions{
        SubmitLabel: "Email me a sign-in link",
    },
},

Or push customization after construction via setters:

auth.SetLoginPageOptions(types.LoginPageOptions{Title: "Welcome back"})
auth.SetPageOptions(pageOptions) // whole aggregate in one call

Terms/Privacy links render as "By continuing, you agree to {Terms} and {Privacy Policy}." inside the form card on login/register-type pages:

LegalLinks: types.LegalLinks{
    Terms:   types.LegalLink{URL: "/terms", Target: types.LinkTargetNewTab},
    Privacy: types.LegalLink{URL: "/privacy"},
},

LinkTargetModal opens the link in an iframe overlay instead of navigating โ€” the target page must permit framing (its X-Frame-Options header / CSP frame-ancestors can block the iframe).

When using cookies, the library defaults to secure settings:

  • HttpOnly: types.CookieHttpOnly (true)
  • Secure: types.CookieSecure (true)
  • SameSite: Lax
  • Path: "/"
  • MaxAge: 7200 (2 hours)

These defaults work for production deployments behind HTTPS or a reverse proxy that terminates TLS. For local development over plain HTTP, you can override Secure without losing the other defaults:

// Production (or any HTTPS/reverse-proxy deployment)
auth.AuthCookieSet(w, r, token)
auth.AuthCookieRemove(w, r)

// Local development over HTTP
auth.AuthCookieSet(w, r, token, types.WithSecure(false))
auth.AuthCookieRemove(w, r, types.WithSecure(false))

You can also override any other cookie attribute with individual options:

auth.AuthCookieSet(w, r, token,
    types.WithSecure(false),
    types.WithHttpOnly(true),
    types.WithSameSite(http.SameSiteLaxMode),
    types.WithMaxAge(3600),
    types.WithPath("/"),
    types.WithDomain("example.com"),
)

If you already have a complete CookieConfig, use WithCookieConfig to replace the defaults entirely:

cfg := types.CookieConfig{
    HttpOnly: types.CookieHttpOnly,
    Secure:   types.CookieInsecure, // for local dev; use types.CookieSecure in production
    SameSite: http.SameSiteLaxMode,
    MaxAge:   2 * 60 * 60,
    Path:     "/",
}

auth.AuthCookieSet(w, r, token, types.WithCookieConfig(cfg))
auth.AuthCookieRemove(w, r, types.WithCookieConfig(cfg))

The same CookieConfig can also be configured once when creating the auth instance. Unset string fields ("") fall back to secure defaults, so you only need to set what you want to override:

authInstance, err := auth.NewOtpAuth(types.ConfigOtp{
    Endpoint:     "/auth",
    UseCookies:   true,
    CookieConfig: &types.CookieConfig{
        HttpOnly: types.CookieHttpOnly,
        Secure:   types.CookieInsecure, // for local dev; use types.CookieSecure in production
        SameSite: http.SameSiteLaxMode,
        MaxAge:   2 * 60 * 60,
        Path:     "/",
    },
    // ... required callbacks
})

๐Ÿ” Token Storage Options

UseCookies: true,
UseLocalStorage: false,
  • Automatically set and sent with requests
  • HttpOnly for security
  • Works with server-side rendering
LocalStorage (For SPAs)
UseCookies: false,
UseLocalStorage: true,
  • Client manages token storage
  • Must send token in Authorization header
  • Better for single-page applications

๐Ÿšฆ Rate Limiting

All authentication endpoints (login, registration, password restore/reset, verification) are protected by rate limiting.

Defaults (in-memory limiter):

  • 5 attempts per IP and endpoint within a 15-minute sliding window
  • Further attempts are blocked for 15 minutes (HTTP 429 with Retry-After header)

These options are shared by both ConfigOtp and ConfigUsernameAndPassword:

// Rate limiting options (shared by both configs)
DisableRateLimit   bool                                                                                 // Set to true to disable rate limiting (not recommended for production)
FuncCheckRateLimit func(ip string, endpoint string) (allowed bool, retryAfter time.Duration, err error) // Optional: override default rate limiter
MaxLoginAttempts   int                                                                                  // Maximum attempts before lockout (default: 5)
LockoutDuration    time.Duration                                                                        // Duration for sliding window and lockout (default: 15 minutes)

Example (username/password):

authInstance, err := auth.NewUsernameAndPasswordAuth(types.ConfigUsernameAndPassword{
    Endpoint:         "/auth",
    UrlRedirectOnSuccess: "/dashboard",

    MaxLoginAttempts: 5,
    LockoutDuration:  15 * time.Minute,

    // Optional: use your own distributed rate limiter (e.g., Redis-based)
    // FuncCheckRateLimit: func(ip, endpoint string) (bool, time.Duration, error) {
    //     // ... implement custom logic
    // },
})

๐Ÿ“– UserAuthOptions

All callback functions are context-aware and receive both a ctx context.Context and a types.UserAuthOptions value with request metadata:

type UserAuthOptions struct {
    UserIp    string  // Client IP address
    UserAgent string  // Client user agent
}

Use this together with ctx for audit logging, security checks, or analytics:

func userLogin(ctx context.Context, username string, password string, options types.UserAuthOptions) (userID string, err error) {
    // Log login attempt with structured logging (see Structured Logging section)
    slog.Info("login attempt",
        "ip", options.UserIp,
        "user_agent", options.UserAgent,
    )

    // Your login logic...
}

๐Ÿ“Š Structured Logging

The library uses Go's log/slog package for structured logging in core flows.

  • Both configuration structs accept an optional logger:

    type ConfigOtp struct {
        // ... other fields ...
        Logger *slog.Logger // Optional: structured logger
    }
    
    type ConfigUsernameAndPassword struct {
        // ... other fields ...
        Logger *slog.Logger // Optional: structured logger
    }
    
  • If Logger is nil, the constructors fall back to slog.Default().

  • The internal Auth instance keeps this logger and uses it to log:

    • Email send failures
    • Token generation/store errors
    • Password restore failures
    • Other internal errors along with email, user_id, ip, and user_agent where available
Example: JSON structured logging
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
    Level: slog.LevelInfo,
}))

authInstance, err := auth.NewUsernameAndPasswordAuth(types.ConfigUsernameAndPassword{
    Endpoint:             "/auth",
    UrlRedirectOnSuccess: "/dashboard",
    UseCookies:           true,

    Logger: logger, // Pass your structured logger here

    // ... required callbacks ...
})
if err != nil {
    log.Fatal(err)
}

๐Ÿ” Helper Methods

// Get current authenticated user ID from request context
userID := auth.GetCurrentUserID(r)

// URL helpers
loginURL := auth.LinkLogin()
registerURL := auth.LinkRegister()
logoutURL := auth.LinkLogout()
passwordRestoreURL := auth.LinkPasswordRestore()
passwordResetURL := auth.LinkPasswordReset(token)

// API URL helpers
apiLoginURL := auth.LinkApiLogin()
apiRegisterURL := auth.LinkApiRegister()
apiLogoutURL := auth.LinkApiLogout()

// Enable/disable registration dynamically
auth.RegistrationEnable()
auth.RegistrationDisable()

// Impersonation helpers
if auth.IsImpersonationEnabled() {
    // Check if current request is an impersonation session
    isImpersonating := auth.IsImpersonating(r)
    realAdminID := auth.GetImpersonatorUserID(r)
    _ = isImpersonating
    _ = realAdminID
}

// AuthKnight helpers (only available with NewAuthKnightAuth)
// loginURL := auth.LinkAuthKnightRedirect(r)    // full login URL from request
// loginURL := auth.LinkAuthKnightLogin(back, next) // manual back_url + next_url
// callbackPath := auth.LinkAuthKnightCallback()   // callback path relative to endpoint

โ“ Frequently Asked Questions

Q: Can I use email instead of username?
A: Yes! The "username" parameter accepts email addresses. Most modern apps use email for authentication.

Q: Can I run multiple auth instances?
A: Yes! You can have separate instances for different user types:

// Regular users with passwordless
userAuth, _ := auth.NewOtpAuth(...)
mux.HandleFunc("/auth/", userAuth.Router().ServeHTTP)

// Admins with username/password
adminAuth, _ := auth.NewUsernameAndPasswordAuth(...)
mux.HandleFunc("/admin/auth/", adminAuth.Router().ServeHTTP)

Q: How do I customize the UI?
A: Three levels: ThemeCSS/CustomCSS re-skin the built-in pages (e.g. a Bootlegance theme); FuncLayout renders the entire document so you can embed auth pages inside your site shell; or pass a fully custom page per method (NewPasswordMethod(auth, myPage)).

Q: What databases are supported?
A: Any! You implement the storage callbacks, so it works with PostgreSQL, MySQL, MongoDB, Redis, or even in-memory stores.

Q: Is this production-ready?
A: Yes! The library has:

  • 90.2% test coverage with comprehensive test suite
  • Structured error handling with error codes (no internal details leaked)
  • CSRF protection and rate limiting
  • Session invalidation on password reset
  • Secure cookie defaults and input validation
  • Structured logging for audit trails

Q: How do I handle password reset?
A: The library includes built-in password reset flow. Users enter their email, receive a reset link, and set a new password.

Q: Can I use this with an existing user system?
A: Absolutely! Just implement the callback functions to integrate with your existing database schema.

๐Ÿงช Testing

The library includes comprehensive tests. Run them with:

go test -v ./...

For coverage:

go test -cover ./...

๐Ÿ“ Working Examples

The examples directory contains complete working applications. Each example includes unit tests (main_test.go) and screenshots (screenshot.png, screenshot_login.png, screenshot_code_verify.png, etc.) for every step/screen of the authentication flow:

AuthKnight Example
  • Otp authentication via AuthKnight hosted login
  • New user registration with verified email
  • Screenshots: screenshot_home.png
  • Run with: cd examples/authknight && go run main.go
  • Available at: http://localhost:8084
Multi-Method Example
  • Muxes username/password, email OTP, and magic-link login on a single router
  • Screenshots: screenshot_login_password.png, screenshot_login_otp.png, screenshot_login_magiclink.png
  • Run with: cd examples/multimethod && go run main.go
  • Available at: http://localhost:8084
Otp Example
  • Email-based authentication with verification codes
  • Screenshots: screenshot_login.png, screenshot_code_verify.png, screenshot_register.png, screenshot_register_code_verify.png
  • Run with: cd examples/passwordless && go run main.go
  • Available at: http://localhost:8083
Username/Password Example
  • Traditional username/password authentication & reset flow
  • Screenshots: screenshot_login.png, screenshot_register.png, screenshot_password_restore.png, screenshot_password_reset.png
  • Run with: cd examples/usernamepassword && go run main.go
  • Available at: http://localhost:8082
  • Standalone single-use emailed sign-in links
  • Screenshots: screenshot_login.png
  • Run with: cd examples/magiclink && go run main.go
  • Available at: http://localhost:8085
Impersonation Example
  • Administrator "login as" feature with session swapping
  • Screenshots: screenshot_login.png
  • Run with: cd examples/impersonation && go run main.go
  • Available at: http://localhost:8086
Custom UI Example
  • Custom page layout (FuncLayout), branding, and custom CSS
  • Screenshots: screenshot_login.png
  • Run with: cd examples/customui && go run main.go
  • Available at: http://localhost:8087

All examples demonstrate:

  • Complete callback implementations
  • Unit tests (main_test.go) in each folder
  • Full multi-screen UI screenshots (screenshot_*.png)
  • Session management & protected routes

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

WIKI: https://dracory.github.io/auth/

๐Ÿ“„ License

See LICENSE file for details.


Made with โค๏ธ by the Dracory team

Documentation ยถ

Index ยถ

Constants ยถ

View Source
const (

	// Path constants re-exported from types for backward compatibility
	PathApiLogin              = authtypes.PathApiLogin
	PathApiLoginCodeVerify    = authtypes.PathApiLoginCodeVerify
	PathApiLogout             = authtypes.PathApiLogout
	PathApiRegister           = authtypes.PathApiRegister
	PathApiRegisterCodeVerify = authtypes.PathApiRegisterCodeVerify
	PathApiRestorePassword    = authtypes.PathApiRestorePassword
	PathApiResetPassword      = authtypes.PathApiResetPassword
	PathApiImpersonateStart   = authtypes.PathApiImpersonateStart
	PathApiImpersonateStop    = authtypes.PathApiImpersonateStop
	PathApiAuthKnightCallback = authtypes.PathApiAuthKnightCallback

	AuthKnightBaseURL = authtypes.AuthKnightBaseURL

	PathLogin              = authtypes.PathLogin
	PathLoginCodeVerify    = authtypes.PathLoginCodeVerify
	PathLogout             = authtypes.PathLogout
	PathRegister           = authtypes.PathRegister
	PathRegisterCodeVerify = authtypes.PathRegisterCodeVerify
	PathPasswordRestore    = authtypes.PathPasswordRestore
	PathPasswordReset      = authtypes.PathPasswordReset

	EndpointLogin              = authtypes.EndpointLogin
	EndpointLoginCodeVerify    = authtypes.EndpointLoginCodeVerify
	EndpointRegister           = authtypes.EndpointRegister
	EndpointRegisterCodeVerify = authtypes.EndpointRegisterCodeVerify
	EndpointPasswordReset      = authtypes.EndpointPasswordReset
	EndpointPasswordRestore    = authtypes.EndpointPasswordRestore
	EndpointImpersonateStart   = authtypes.EndpointImpersonateStart
	EndpointImpersonateStop    = authtypes.EndpointImpersonateStop
	EndpointAuthKnightCallback = authtypes.EndpointAuthKnightCallback

	// LoginCodeLength specified the length of the login code
	LoginCodeLength int = 8

	// LoginCodeGamma specifies the characters to be used for building the login code
	LoginCodeGamma string = "BCDFGHJKLMNPQRSTVXYZ"

	DefaultVerificationCodeExpiration = 1 * time.Hour
	DefaultPasswordResetExpiration    = 1 * time.Hour
	DefaultAuthTokenExpiration        = 2 * time.Hour

	DefaultMaxLoginAttempts = 5
	DefaultLockoutDuration  = 15 * time.Minute
)
View Source
const (
	ErrCodeEmailSendFailed      = "EMAIL_SEND_FAILED"
	ErrCodeTokenStoreFailed     = "TOKEN_STORE_FAILED"
	ErrCodeValidationFailed     = "VALIDATION_FAILED"
	ErrCodeAuthenticationFailed = "AUTHENTICATION_FAILED"
	ErrCodeRegistrationFailed   = "REGISTRATION_FAILED"
	ErrCodeLogoutFailed         = "LOGOUT_FAILED"
	ErrCodeInternalError        = "INTERNAL_ERROR"
	ErrCodeCodeGenerationFailed = "CODE_GENERATION_FAILED"
	ErrCodeSerializationFailed  = "SERIALIZATION_FAILED"
	ErrCodePasswordResetFailed  = "PASSWORD_RESET_FAILED"
)

Error codes for consistent error handling

View Source
const DefaultSessionTTL = 2 * time.Hour

DefaultSessionTTL is the lifetime of sessions minted by the store-derived FuncSessionCreate (remember-me issues longer-lived sessions via its own hook).

Variables ยถ

View Source
var CookieName = "authtoken"

Functions ยถ

func AuthCookieGet ยถ

func AuthCookieGet(r *http.Request) string

AuthCookieGet returns the authentication cookie value, or an empty string if missing.

func AuthCookieRemove ยถ

func AuthCookieRemove(w http.ResponseWriter, r *http.Request, opts ...types.CookieOption)

AuthCookieRemove removes the authentication cookie. Options are applied on top of defaults.

func AuthCookieSet ยถ

func AuthCookieSet(w http.ResponseWriter, r *http.Request, token string, opts ...types.CookieOption)

AuthCookieSet sets the authentication cookie. Options are applied on top of defaults.

func AuthTokenRetrieve ยถ

func AuthTokenRetrieve(r *http.Request, useCookies bool) string

AuthTokenRetrieve retrieves the auth token from the request.

func GetImpersonatorUserID ยถ added in v0.33.0

func GetImpersonatorUserID(r *http.Request) string

func IsImpersonating ยถ added in v0.33.0

func IsImpersonating(r *http.Request) bool

func NewAuthKnightAuth ยถ added in v0.35.0

func NewAuthKnightAuth(config types.ConfigAuthKnight) (types.AuthAuthKnightInterface, error)

NewAuthKnightAuth creates a new AuthKnight-based authentication instance. It validates the provided ConfigAuthKnight and returns an error if required fields are missing.

func NewAuthKnightMethod ยถ added in v0.37.0

func NewAuthKnightMethod(a types.AuthAuthKnightInterface) types.Method

NewAuthKnightMethod adapts AuthKnight login to types.Method.

func NewMagicLinkMethod ยถ added in v0.37.0

func NewMagicLinkMethod(
	page http.HandlerFunc,
	sendDeps api_magic_link_send.Dependencies,
	callbackDeps api_magic_link_callback.Dependencies,
) types.Method

NewMagicLinkMethod adapts the magic-link login to types.Method. The page handler is supplied by the caller (a simple email form posting to the send ajax is enough); sendDeps/callbackDeps are the 007 dependency sets. page must not be nil โ€” there is no package default page for this method.

func NewMagicLinkMethodFromAuth ยถ added in v0.38.0

func NewMagicLinkMethodFromAuth(
	a types.AuthSharedInterface,
	page http.HandlerFunc,
	linkCallback func(token string) string,
	opts ...func(*api_magic_link_send.Dependencies, *api_magic_link_callback.Dependencies),
) types.Method

NewMagicLinkMethodFromAuth builds the magic-link method from an AuthSharedInterface โ€” the public counterpart to NewMagicLinkMethod, which takes internal dep types that external apps cannot construct. linkCallback builds the callback URL for a token (e.g. "/auth/magiclink-callback?token=" + token). page may be nil โ€” the package's generic magic-link page is used then.

func NewOTPMethod ยถ added in v0.37.0

func NewOTPMethod(a types.AuthSharedInterface) types.Method

NewOTPMethod adapts the otp email-code login to types.Method.

func NewOTPMethodWithPage ยถ added in v0.38.0

func NewOTPMethodWithPage(a types.AuthSharedInterface, page http.HandlerFunc) types.Method

NewOTPMethodWithPage is NewOTPMethod with a caller-supplied login page โ€” for apps that want their own template over the package's generic one.

func NewOtpAuth ยถ added in v0.49.0

func NewOtpAuth(config types.ConfigOtp) (types.AuthOtpInterface, error)

func NewPasswordMethod ยถ added in v0.37.0

func NewPasswordMethod(a types.AuthSharedInterface, page http.HandlerFunc) types.Method

NewPasswordMethod adapts the username/password login to types.Method. page is the login page handler; recovery routes mount only when this method is in the list (RouteProvider).

Types ยถ

type AuthError ยถ added in v0.29.0

type AuthError struct {
	Code        string
	Message     string // User-facing message
	InternalErr error  // For logging only, never exposed to users
}

AuthError represents a structured authentication error with a code, user-facing message, and internal error details for logging.

func NewAuthenticationError ยถ added in v0.29.0

func NewAuthenticationError(err error) *AuthError

NewAuthenticationError creates an AuthError for authentication failures.

func NewCodeGenerationError ยถ added in v0.29.0

func NewCodeGenerationError(err error) *AuthError

NewCodeGenerationError creates an AuthError for code generation failures.

func NewEmailSendError ยถ added in v0.29.0

func NewEmailSendError(err error) *AuthError

NewEmailSendError creates an AuthError for email send failures.

func NewInternalError ยถ added in v0.29.0

func NewInternalError(err error) *AuthError

NewInternalError creates an AuthError for generic internal errors.

func NewLogoutError ยถ added in v0.29.0

func NewLogoutError(err error) *AuthError

NewLogoutError creates an AuthError for logout failures.

func NewPasswordResetError ยถ added in v0.29.0

func NewPasswordResetError(err error) *AuthError

NewPasswordResetError creates an AuthError for password reset failures.

func NewRegistrationError ยถ added in v0.29.0

func NewRegistrationError(err error) *AuthError

NewRegistrationError creates an AuthError for registration failures.

func NewSerializationError ยถ added in v0.29.0

func NewSerializationError(err error) *AuthError

NewSerializationError creates an AuthError for data serialization failures.

func NewTokenStoreError ยถ added in v0.29.0

func NewTokenStoreError(err error) *AuthError

NewTokenStoreError creates an AuthError for token store failures.

func (*AuthError) Error ยถ added in v0.29.0

func (e *AuthError) Error() string

Error implements the error interface, returning the user-facing message.

type AuthenticatedUserID ยถ

type AuthenticatedUserID struct{}

type CookieConfig ยถ added in v0.29.0

type CookieConfig = authtypes.CookieConfig

type LoginUsernameAndPasswordResponse ยถ

type LoginUsernameAndPasswordResponse struct {
	ErrorMessage   string
	SuccessMessage string
	Token          string
}

func LoginWithUsernameAndPassword ยถ added in v0.30.0

func LoginWithUsernameAndPassword(
	ctx context.Context,
	a types.AuthPasswordInterface,
	email string,
	password string,
	options types.UserAuthOptions,
) LoginUsernameAndPasswordResponse

LoginWithUsernameAndPassword is a standalone helper that performs the username/password login flow using the provided AuthPasswordInterface implementation.

type MultiMethodAuth ยถ added in v0.37.0

type MultiMethodAuth struct {
	// contains filtered or unexported fields
}

MultiMethodAuth composes N login methods behind a single mux: the first (primary) method mounts at <endpoint>/login, secondary methods at <endpoint>/login-<name>, method callbacks mount once each regardless of position, and method-provided extra routes (e.g. password recovery) mount only when the providing method is in the list.

Custom methods implement types.Method โ€” no library change needed.

func NewMultiMethodAuth ยถ added in v0.37.0

func NewMultiMethodAuth(endpoint string, methods []types.Method) (*MultiMethodAuth, error)

NewMultiMethodAuth builds the composed mux. Returns an error for an empty method list or duplicate method names (no silent shadowing).

func (*MultiMethodAuth) Handler ยถ added in v0.37.0

func (m *MultiMethodAuth) Handler() http.Handler

Handler returns the composed http.Handler (the underlying ServeMux).

func (*MultiMethodAuth) LoginAlternativesHTML ยถ added in v0.37.0

func (m *MultiMethodAuth) LoginAlternativesHTML(currentMethod string) string

LoginAlternativesHTML renders the "OR โ€” use another method" fragment for the given current method name. Pages (built-in or app-supplied) can embed it so users can switch between mounted methods.

func (*MultiMethodAuth) Methods ยถ added in v0.37.0

func (m *MultiMethodAuth) Methods() []types.Method

Methods returns the configured method list (primary first).

func (*MultiMethodAuth) Router ยถ added in v0.37.0

func (m *MultiMethodAuth) Router() *http.ServeMux

Router returns the composed *http.ServeMux.

type RegisterUsernameAndPasswordResponse ยถ

type RegisterUsernameAndPasswordResponse struct {
	ErrorMessage   string
	SuccessMessage string
	Token          string
}

func RegisterWithUsernameAndPassword ยถ added in v0.30.0

func RegisterWithUsernameAndPassword(
	ctx context.Context,
	a types.AuthPasswordInterface,
	email string,
	password string,
	firstName string,
	lastName string,
	options types.UserAuthOptions,
) RegisterUsernameAndPasswordResponse

RegisterWithUsernameAndPassword is a standalone helper that performs the username/password registration flow using the provided AuthPasswordInterface implementation.

Directories ยถ

Path Synopsis
examples
authknight command
background command
Background example: full-page photo backdrop behind the auth panel.
Background example: full-page photo backdrop behind the auth panel.
customui command
Custom UI example: demonstrates branding, custom CSS, and site layout embedding.
Custom UI example: demonstrates branding, custom CSS, and site layout embedding.
impersonation command
Impersonation example: demonstrates administrator "login as" feature.
Impersonation example: demonstrates administrator "login as" feature.
magiclink command
Magic link example: standalone magic link authentication flow.
Magic link example: standalone magic link authentication flow.
multimethod command
Multi-method example: mounts username/password, email OTP, and magic-link login on a single mux via auth.NewMultiMethodAuth.
Multi-method example: mounts username/password, email OTP, and magic-link login on a single mux via auth.NewMultiMethodAuth.
otp command
internal
api/api_magic_link_callback
Package api_magic_link_callback provides the single-use GET callback that redeems a magic login link.
Package api_magic_link_callback provides the single-use GET callback that redeems a magic login link.
api/api_magic_link_send
Package api_magic_link_send provides the JSON endpoint that sends a single-use magic login link to an email address.
Package api_magic_link_send provides the JSON endpoint that sends a single-use magic login link to an email address.
rules
Package rules contains the reusable verification rules shared by the code-verify flows (login and register).
Package rules contains the reusable verification rules shared by the code-verify flows (login and register).
ui/page_magic_link
Package page_magic_link renders the package's generic magic-link login page โ€” an email form posting to the same path that serves it (the method's send ajax is mounted on the same route).
Package page_magic_link renders the package's generic magic-link login page โ€” an email form posting to the same path that serves it (the method's send ajax is mounted on the same route).
Remember-me exchange middleware.
Remember-me exchange middleware.
This is a tiny JSON database
This is a tiny JSON database

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ ๆข็ฝ‘ๅ€