account

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package account provides a ready-to-use user module with registration, login, token refresh, and password management.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Table

func Table() db.TableSpec

Table returns the migration spec for the User model. Use with db.Migrate:

db.Migrate(ctx, gdb, account.Table(), db.Table(&Product{}))

Types

type Module

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

Module manages user accounts.

func New

func New(gdb *gorm.DB, logger log.Logger, opts ...Option) (*Module, error)

New creates an account module.

func Setup

func Setup(gdb *gorm.DB, logger log.Logger, opts *config.AccountOptions, r RouteGroup, modOpts ...Option) (*Module, error)

Setup creates the account module from config, migrates the User table, and registers routes — all in one call.

Returns (nil, nil) if opts is nil or opts.Enabled is false. Extra modOpts (e.g. WithSender) are applied on top of config values.

acct, err := account.Setup(gdb, logger, &cfg.Account, srv.Group("/auth"))

func (*Module) ActiveCheck

func (m *Module) ActiveCheck() gin.HandlerFunc

ActiveCheck returns a gin middleware that verifies the authenticated user still exists and is active by hitting the database on every request.

PrincipalResolver is stateless by design (no DB per request). Apply ActiveCheck to routes where real-time revocation matters:

api := srv.Group("/api/v1")
api.Use(middleware.Authn(acct.TokenParser(), acct.PrincipalResolver()))
api.Use(acct.ActiveCheck())

func (*Module) Close

func (m *Module) Close() error

Close releases the module's background resources. The login rate limiter spawns short-lived cleanup goroutines on every Nth failure; Close waits for any in-flight cleanup so the App's shutdown budget covers them rather than leaving the goroutine running until the process terminates. Safe to call multiple times.

func (*Module) LoginRateLimitEnabled

func (m *Module) LoginRateLimitEnabled() bool

LoginRateLimitEnabled reports whether per-email login throttling is active. Useful for diagnostics, /healthz reporting, and tests that need to confirm a builder propagated the LoginRateWindow / LoginRateLimit configuration without poking at internal state.

func (*Module) PrincipalResolver

func (m *Module) PrincipalResolver() middleware.PrincipalResolver

PrincipalResolver returns a resolver that builds a Principal from JWT claims. Roles are read from the "roles" claim in the token — no DB lookup required.

func (*Module) RegisterRoutes

func (m *Module) RegisterRoutes(r RouteGroup)

RegisterRoutes registers account API routes on the given router.

Public routes (no auth required):

POST /register
POST /login
POST /forgot-password   (only if WithSender is configured)
POST /reset-password    (only if WithSender is configured)

Authenticated routes:

POST /refresh-token
PUT  /change-password

func (*Module) TokenParser

func (m *Module) TokenParser() middleware.TokenParser

TokenParser returns the JWT manager for use with middleware.Authn.

type Option

type Option func(*moduleConfig)

Option configures a Module.

func WithExpiration

func WithExpiration(d time.Duration) Option

WithExpiration sets the access token lifetime. Defaults to 2 hours.

func WithLoginRateLimit

func WithLoginRateLimit(window time.Duration, maxAttempts int) Option

WithLoginRateLimit enables per-email login attempt rate limiting. When the threshold is exceeded within the window, the login endpoint returns 429 Too Many Requests. Defaults to disabled (zero values).

Recommended production values: window=15m, maxAttempts=10.

func WithResetExpiration

func WithResetExpiration(d time.Duration) Option

WithResetExpiration sets the password-reset token lifetime. Defaults to 15 minutes.

func WithSender

func WithSender(s Sender) Option

WithSender enables the forgot/reset-password flow.

func WithSigningKey

func WithSigningKey(key string) Option

WithSigningKey sets the JWT signing key (required, >= 32 bytes).

type RouteGroup

type RouteGroup interface {
	POST(string, ...gin.HandlerFunc) gin.IRoutes
	PUT(string, ...gin.HandlerFunc) gin.IRoutes
	Group(string, ...gin.HandlerFunc) *gin.RouterGroup
}

RouteGroup is the minimal interface for registering routes. *gin.RouterGroup satisfies this (use srv.Group("/path") to obtain one).

type Sender

type Sender interface {
	Send(ctx context.Context, to string, code string) error
}

Sender delivers a password-reset code to the user (email, SMS, etc.). The module does not impose a delivery mechanism — callers provide their own.

type User

type User struct {
	db.SoftDeleteModel
	Email           string `json:"email"    gorm:"size:200;not null"`
	PasswordHash    string `json:"-"        gorm:"column:password_hash;size:128;not null"`
	PasswordVersion int    `json:"-"        gorm:"column:password_version;default:0;not null"`
	Name            string `json:"name"     gorm:"size:100;default:'';not null"`
	Roles           string `json:"-"        gorm:"column:roles;size:500;default:'';not null"`
	Active          bool   `json:"-"        gorm:"default:true;not null"`
}

User is the built-in user model for the account module.

func (User) RIDPrefix

func (User) RIDPrefix() string

RIDPrefix returns the prefix for user resource IDs (e.g. "usr_abc123").

func (*User) RoleList

func (u *User) RoleList() []string

RoleList returns the roles as a string slice.

func (*User) SetRoles

func (u *User) SetRoles(roles []string)

SetRoles stores the given roles as a comma-separated string.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL