user

package module
v0.0.24 Latest Latest
Warning

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

Go to latest
Published: Mar 7, 2026 License: MIT Imports: 22 Imported by: 0

README

tinywasm/user

Project Badges

User management library for the tinywasm ecosystem. Handles user entities, password authentication, OAuth providers (Google, Microsoft), LAN (local network) authentication by RUT + IP, and session management. Applications import tinywasm/user directly to configure session behaviour, and use its isomorphic UI modules for authentication workflows.

Documentation

Note: RBAC is now integrated into the User module (see ARCHITECTURE.md).

Diagrams

Initialization

import "github.com/tinywasm/user"

// ...

// Initialize the user module directly with an ORM db instance
err := user.Init(db, user.Config{
    CookieName: "session_id", // default: "session"
    TokenTTL:   86400,        // default: 86400 (24h)
    TrustProxy: true,         // default: false
    OAuthProviders: []user.OAuthProvider{
        &user.GoogleProvider{
            ClientID:     os.Getenv("GOOGLE_CLIENT_ID"),
            ClientSecret: os.Getenv("GOOGLE_CLIENT_SECRET"),
            RedirectURL:  "https://example.com/oauth/callback",
        },
    },
})
if err != nil {
    // handle error
}

For detailed API usage and module integration guidance, refer to docs/SKILL.md.

Status

Implementation pending. Documentation complete.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidCredentials = fmt.Err("access", "denied")             // EN: Access Denied                    / ES: Acceso Denegado
	ErrSuspended          = fmt.Err("user", "suspended")            // EN: User Suspended                   / ES: Usuario Suspendido
	ErrEmailTaken         = fmt.Err("email", "registered")          // EN: Email Registered                 / ES: Correo electrónico Registrado
	ErrWeakPassword       = fmt.Err("password", "weak")             // EN: Password Weak                    / ES: Contraseña Débil
	ErrSessionExpired     = fmt.Err("token", "expired")             // EN: Token Expired                    / ES: Token Expirado
	ErrNotFound           = fmt.Err("user", "not", "found")         // EN: User Not Found                   / ES: Usuario No Encontrado
	ErrProviderNotFound   = fmt.Err("provider", "not", "found")     // EN: Provider Not Found               / ES: Proveedor No Encontrado
	ErrInvalidOAuthState  = fmt.Err("state", "invalid")             // EN: State Invalid                    / ES: Estado Inválido
	ErrCannotUnlink       = fmt.Err("identity", "cannot", "unlink") // EN: Identity Cannot Unlink           / ES: Identidad No puede Desvincular
	ErrInvalidRUT         = fmt.Err("rut", "invalid")               // EN: Rut Invalid                      / ES: Rut Inválido
	ErrRUTTaken           = fmt.Err("rut", "registered")            // EN: Rut Registered                   / ES: Rut Registrado
	ErrIPTaken            = fmt.Err("ip", "registered")             // EN: Ip Registered                    / ES: Ip Registrado
)
View Source
var ErrInvalidToken = fmt.Err("token", "invalid")
View Source
var Identity_ = struct {
	TableName  string
	ID         string
	UserID     string
	Provider   string
	ProviderID string
	Email      string
	CreatedAt  string
}{
	TableName:  "user_identities",
	ID:         "id",
	UserID:     "user_id",
	Provider:   "provider",
	ProviderID: "provider_id",
	Email:      "email",
	CreatedAt:  "created_at",
}
View Source
var LANIP_ = struct {
	TableName string
	ID        string
	UserID    string
	IP        string
	Label     string
	CreatedAt string
}{
	TableName: "user_lan_ips",
	ID:        "id",
	UserID:    "user_id",
	IP:        "ip",
	Label:     "label",
	CreatedAt: "created_at",
}
View Source
var OAuthState_ = struct {
	TableName string
	State     string
	Provider  string
	ExpiresAt string
	CreatedAt string
}{
	TableName: "user_oauth_states",
	State:     "state",
	Provider:  "provider",
	ExpiresAt: "expires_at",
	CreatedAt: "created_at",
}
View Source
var PasswordHashCost = bcrypt.DefaultCost
View Source
var Permission_ = struct {
	TableName string
	ID        string
	Name      string
	Resource  string
	Action    string
}{
	TableName: "rbac_permissions",
	ID:        "id",
	Name:      "name",
	Resource:  "resource",
	Action:    "action",
}
View Source
var RolePermission_ = struct {
	TableName    string
	RoleID       string
	PermissionID string
}{
	TableName:    "rbac_role_permissions",
	RoleID:       "role_id",
	PermissionID: "permission_id",
}
View Source
var Role_ = struct {
	TableName   string
	ID          string
	Code        string
	Name        string
	Description string
}{
	TableName:   "rbac_roles",
	ID:          "id",
	Code:        "code",
	Name:        "name",
	Description: "description",
}
View Source
var Session_ = struct {
	TableName string
	ID        string
	UserID    string
	ExpiresAt string
	IP        string
	UserAgent string
	CreatedAt string
}{
	TableName: "user_sessions",
	ID:        "id",
	UserID:    "user_id",
	ExpiresAt: "expires_at",
	IP:        "ip",
	UserAgent: "user_agent",
	CreatedAt: "created_at",
}
View Source
var UserRole_ = struct {
	TableName string
	UserID    string
	RoleID    string
}{
	TableName: "rbac_user_roles",
	UserID:    "user_id",
	RoleID:    "role_id",
}
View Source
var User_ = struct {
	TableName string
	ID        string
	Email     string
	Name      string
	Phone     string
	Status    string
	CreatedAt string
}{
	TableName: "users",
	ID:        "id",
	Email:     "email",
	Name:      "name",
	Phone:     "phone",
	Status:    "status",
	CreatedAt: "created_at",
}

Functions

func GenerateJWT added in v0.0.17

func GenerateJWT(secret []byte, userID string, ttl int) (string, error)

func UIModules added in v0.0.15

func UIModules() []any

UIModules returns all standard authentication UI flow handlers. Isomorphic: available in both WASM and non-WASM builds.

func ValidateJWT added in v0.0.17

func ValidateJWT(secret []byte, token string) (string, error)

Types

type AuthMode added in v0.0.17

type AuthMode uint8

AuthMode selects the session strategy.

const (
	// AuthModeCookie stores a session ID in an HttpOnly cookie.
	// Stateful: requires user_sessions table. Supports immediate revocation.
	AuthModeCookie AuthMode = iota // default

	// AuthModeJWT stores a signed JWT in an HttpOnly cookie.
	// Stateless: no DB lookup per request. No immediate revocation.
	// Ideal for SPA/PWA and multi-server deployments.
	AuthModeJWT

	// AuthModeBearer reads a signed JWT from the "Authorization: Bearer <token>" header.
	// Stateless: for API clients (MCP servers, IDEs, LLMs) that cannot use cookies.
	// Structurally implements mcp.Authorizer via InjectIdentity + CanExecute methods.
	// Requires JWTSecret.
	AuthModeBearer
)

type Config added in v0.0.2

type Config struct {
	AuthMode AuthMode // default: AuthModeCookie

	// Shared by all modes
	CookieName string // default: "session"
	TokenTTL   int    // default: 86400 (seconds). Session TTL in cookie mode, JWT expiry in JWT mode.

	// Required when AuthMode == AuthModeJWT or AuthMode == AuthModeBearer.
	// Also required to call GenerateAPIToken regardless of AuthMode.
	JWTSecret []byte

	TrustProxy     bool
	OAuthProviders []OAuthProvider

	// Optional hook for receiving security events (e.g. tampering, brute force)
	OnSecurityEvent func(SecurityEvent)

	// OnPasswordValidate is called by SetPassword before hashing.
	// Return a non-nil error to reject the password.
	// If nil, only the built-in len >= 8 check applies.
	OnPasswordValidate func(password string) error
}

type Executor added in v0.0.2

type Executor interface {
	Exec(query string, args ...any) error
	Query(query string, args ...any) (Rows, error)
	QueryRow(query string, args ...any) Scanner
	Prepare(query string) (*sql.Stmt, error)
	Begin() (*sql.Tx, error)
}

Executor interface abstracts database operations.

type GoogleProvider added in v0.0.2

type GoogleProvider struct {
	ClientID     string
	ClientSecret string
	RedirectURL  string
	// contains filtered or unexported fields
}

func (*GoogleProvider) AuthCodeURL added in v0.0.2

func (p *GoogleProvider) AuthCodeURL(state string) string

func (*GoogleProvider) ExchangeCode added in v0.0.2

func (p *GoogleProvider) ExchangeCode(ctx context.Context, code string) (*oauth2.Token, error)

func (*GoogleProvider) GetUserInfo added in v0.0.2

func (p *GoogleProvider) GetUserInfo(ctx context.Context, token *oauth2.Token) (OAuthUserInfo, error)

func (*GoogleProvider) Name added in v0.0.2

func (p *GoogleProvider) Name() string

type Identity added in v0.0.2

type Identity struct {
	ID         string `json:"id" db:"pk"`
	UserID     string `json:"user_id" db:"ref=users"`
	Provider   string `json:"provider"`
	ProviderID string `json:"provider_id"`
	Email      string `json:"email,omitempty"`
	CreatedAt  int64  `json:"created_at"`
}

Identity

func ReadAllIdentity added in v0.0.6

func ReadAllIdentity(qb *orm.QB) ([]*Identity, error)

func ReadOneIdentity added in v0.0.6

func ReadOneIdentity(qb *orm.QB, model *Identity) (*Identity, error)

func (*Identity) Pointers added in v0.0.6

func (m *Identity) Pointers() []any

func (*Identity) Schema added in v0.0.6

func (m *Identity) Schema() []orm.Field

func (Identity) TableName added in v0.0.6

func (Identity) TableName() string

func (*Identity) Values added in v0.0.6

func (m *Identity) Values() []any

type LANIP added in v0.0.2

type LANIP struct {
	ID        string `json:"id" db:"pk"`
	UserID    string `json:"user_id" db:"ref=users"`
	IP        string `json:"ip"`
	Label     string `json:"label"`
	CreatedAt int64  `json:"created_at"`
}

LANIP

func ReadAllLANIP added in v0.0.6

func ReadAllLANIP(qb *orm.QB) ([]*LANIP, error)

func ReadOneLANIP added in v0.0.6

func ReadOneLANIP(qb *orm.QB, model *LANIP) (*LANIP, error)

func (*LANIP) Pointers added in v0.0.6

func (m *LANIP) Pointers() []any

func (*LANIP) Schema added in v0.0.6

func (m *LANIP) Schema() []orm.Field

func (LANIP) TableName added in v0.0.6

func (LANIP) TableName() string

func (*LANIP) Values added in v0.0.6

func (m *LANIP) Values() []any

type LoginData added in v0.0.2

type LoginData struct {
	Email    string
	Password string
}

LoginData is validated by LoginModule on both frontend and backend.

type MicrosoftProvider added in v0.0.2

type MicrosoftProvider struct {
	ClientID     string
	ClientSecret string
	RedirectURL  string
	// contains filtered or unexported fields
}

func (*MicrosoftProvider) AuthCodeURL added in v0.0.2

func (p *MicrosoftProvider) AuthCodeURL(state string) string

func (*MicrosoftProvider) ExchangeCode added in v0.0.2

func (p *MicrosoftProvider) ExchangeCode(ctx context.Context, code string) (*oauth2.Token, error)

func (*MicrosoftProvider) GetUserInfo added in v0.0.2

func (p *MicrosoftProvider) GetUserInfo(ctx context.Context, token *oauth2.Token) (OAuthUserInfo, error)

func (*MicrosoftProvider) Name added in v0.0.2

func (p *MicrosoftProvider) Name() string

type Module added in v0.0.15

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

Module is the user/auth/rbac handle. All backend operations are methods on this type. Created exclusively via New().

func New

func New(db *orm.DB, cfg Config) (*Module, error)

New initializes the user/rbac schema, warms the cache, and returns a Module handle. This is the ONLY entry point for this package on the backend.

func (*Module) AccessCheck added in v0.0.15

func (m *Module) AccessCheck(resource string, action byte, data ...any) bool

AccessCheck is the bridge function for tinywasm/crudp and tinywasm/site. Reads the *http.Request from data, validates the session, and checks RBAC permissions. Satisfies the site.SetAccessCheck(fn) signature directly.

Usage: site.SetAccessCheck(m.AccessCheck)

func (*Module) Add added in v0.0.15

func (m *Module) Add() []any

Add returns all admin-managed CRUDP handlers for registration. The concrete types are private — pass directly to crudp.RegisterHandlers.

Usage: cp.RegisterHandlers(m.Add()...)

func (*Module) AssignLANIP added in v0.0.15

func (m *Module) AssignLANIP(userID, ip, label string) error

func (*Module) AssignPermission added in v0.0.15

func (m *Module) AssignPermission(roleID, permissionID string) error

func (*Module) AssignRole added in v0.0.15

func (m *Module) AssignRole(userID, roleID string) error

func (*Module) BeginOAuth added in v0.0.15

func (m *Module) BeginOAuth(providerName string) (string, error)

func (*Module) CanExecute added in v0.0.24

func (m *Module) CanExecute(ctx context.Context, resource string, action byte) bool

CanExecute implements mcp.Authorizer. Reads identity injected by InjectIdentity and checks RBAC.

func (*Module) CompleteOAuth added in v0.0.15

func (m *Module) CompleteOAuth(providerName string, r *http.Request, ip, ua string) (User, bool, error)

func (*Module) CreatePermission added in v0.0.15

func (m *Module) CreatePermission(id, name, resource string, action string) error

func (*Module) CreateRole added in v0.0.15

func (m *Module) CreateRole(id string, code string, name, description string) error

func (*Module) CreateSession added in v0.0.15

func (m *Module) CreateSession(userID, ip, userAgent string) (Session, error)

func (*Module) DeletePermission added in v0.0.15

func (m *Module) DeletePermission(id string) error

func (*Module) DeleteRole added in v0.0.15

func (m *Module) DeleteRole(id string) error

func (*Module) DeleteSession added in v0.0.15

func (m *Module) DeleteSession(id string) error

func (*Module) FromContext added in v0.0.15

func (m *Module) FromContext(ctx context.Context) (*User, bool)

FromContext extracts the authenticated *User injected by Middleware or RegisterMCP. Returns (nil, false) if the context carries no authenticated user.

func (*Module) GenerateAPIToken added in v0.0.24

func (m *Module) GenerateAPIToken(userID string, ttl int) (string, error)

GenerateAPIToken creates a signed JWT for API access (MCP clients, IDEs, LLMs). Requires Config.JWTSecret — independent of the configured AuthMode. ttl=0 → 100 years (effectively no expiry). The returned token is used as a Bearer token in Authorization headers.

func (*Module) GetLANIPs added in v0.0.15

func (m *Module) GetLANIPs(userID string) ([]LANIP, error)

func (*Module) GetPermission added in v0.0.15

func (m *Module) GetPermission(id string) (*Permission, error)

func (*Module) GetRole added in v0.0.15

func (m *Module) GetRole(id string) (*Role, error)

func (*Module) GetRoleByCode added in v0.0.15

func (m *Module) GetRoleByCode(code string) (*Role, error)

func (*Module) GetSession added in v0.0.15

func (m *Module) GetSession(id string) (Session, error)

func (*Module) GetUser added in v0.0.15

func (m *Module) GetUser(id string) (User, error)

func (*Module) GetUserIdentities added in v0.0.15

func (m *Module) GetUserIdentities(userID string) ([]Identity, error)

func (*Module) GetUserRoles added in v0.0.15

func (m *Module) GetUserRoles(userID string) ([]Role, error)

func (*Module) HasPermission added in v0.0.15

func (m *Module) HasPermission(userID, resource string, action byte) (bool, error)

func (*Module) InjectIdentity added in v0.0.24

func (m *Module) InjectIdentity(ctx context.Context, r *http.Request) context.Context

InjectIdentity implements mcp.Authorizer. Delegates to validateSession (respects configured AuthMode). On failure: returns ctx unchanged — CanExecute will deny.

func (*Module) Login added in v0.0.15

func (m *Module) Login(email, password string) (User, error)

func (*Module) LoginLAN added in v0.0.15

func (m *Module) LoginLAN(rut string, r *http.Request) (User, error)

func (*Module) Middleware added in v0.0.15

func (m *Module) Middleware(next http.Handler) http.Handler

Middleware protects HTTP routes. Validates the session cookie and injects the authenticated *User into the request context. Returns HTTP 401 if the session is missing or expired.

Example:

mux.Handle("/admin", m.Middleware(adminHandler))

func (*Module) PurgeExpiredOAuthStates added in v0.0.15

func (m *Module) PurgeExpiredOAuthStates() error

func (*Module) PurgeExpiredSessions added in v0.0.15

func (m *Module) PurgeExpiredSessions() error

func (*Module) PurgeSessionsByUser added in v0.0.22

func (m *Module) PurgeSessionsByUser(userID string) error

PurgeSessionsByUser deletes all sessions belonging to userID from cache and DB.

func (*Module) ReactivateUser added in v0.0.22

func (m *Module) ReactivateUser(id string) error

ReactivateUser sets Status = "active". Evicts user from cache.

func (*Module) Register added in v0.0.15

func (m *Module) Register(handlers ...RBACObject) error

func (*Module) RegisterLAN added in v0.0.15

func (m *Module) RegisterLAN(userID, rut string) error

func (*Module) RegisterMCP added in v0.0.15

func (m *Module) RegisterMCP(next http.Handler) http.Handler

RegisterMCP envuelve el handler MCP con middleware de sesión. Alternativa limpia a registrar hooks en el MCPServer (que no existe en tinywasm/mcp).

Ejemplo:

mcpHandler := mcp.NewStreamableHTTPServer(srv)
mux.Handle("/mcp", m.RegisterMCP(mcpHandler))

func (*Module) RevokeLANIP added in v0.0.15

func (m *Module) RevokeLANIP(userID, ip string) error

func (*Module) RevokeRole added in v0.0.15

func (m *Module) RevokeRole(userID, roleID string) error

func (*Module) RotateSession added in v0.0.22

func (m *Module) RotateSession(oldID, ip, userAgent string) (Session, error)

RotateSession atomically deletes the old session and creates a new one with the same userID, updated IP/UserAgent, and a fresh TTL. Prevents session fixation attacks when called post-login.

func (*Module) SetLog added in v0.0.15

func (m *Module) SetLog(fn func(...any))

SetLog configures optional logging. Call immediately after New(). Default: no-op. Follows the tinywasm ecosystem SetLog convention (same as rbac).

Example:

m.SetLog(func(msg ...any) { log.Println(msg...) })

func (*Module) SetPassword added in v0.0.15

func (m *Module) SetPassword(userID, password string) error

func (*Module) SuspendUser added in v0.0.22

func (m *Module) SuspendUser(id string) error

SuspendUser sets Status = "suspended". Evicts user from cache.

func (*Module) UIModules added in v0.0.15

func (m *Module) UIModules() []any

UIModules returns all standard authentication UI flow handlers bound to this module. Isomorphic: The signature exists in both WASM and backend. On the backend, it links to the DB.

func (*Module) UnlinkIdentity added in v0.0.15

func (m *Module) UnlinkIdentity(userID, provider string) error

func (*Module) UnregisterLAN added in v0.0.15

func (m *Module) UnregisterLAN(userID string) error

func (*Module) VerifyPassword added in v0.0.15

func (m *Module) VerifyPassword(userID, password string) error

type OAuthProvider added in v0.0.2

type OAuthProvider interface {
	Name() string
	AuthCodeURL(state string) string
	ExchangeCode(ctx context.Context, code string) (*oauth2.Token, error)
	GetUserInfo(ctx context.Context, token *oauth2.Token) (OAuthUserInfo, error)
}

type OAuthState added in v0.0.6

type OAuthState struct {
	State     string `json:"state" db:"pk"`
	Provider  string `json:"provider"`
	ExpiresAt int64  `json:"expires_at"`
	CreatedAt int64  `json:"created_at"`
}

OAuthState

func ReadAllOAuthState added in v0.0.6

func ReadAllOAuthState(qb *orm.QB) ([]*OAuthState, error)

func ReadOneOAuthState added in v0.0.6

func ReadOneOAuthState(qb *orm.QB, model *OAuthState) (*OAuthState, error)

func (*OAuthState) Pointers added in v0.0.6

func (m *OAuthState) Pointers() []any

func (*OAuthState) Schema added in v0.0.6

func (m *OAuthState) Schema() []orm.Field

func (OAuthState) TableName added in v0.0.6

func (OAuthState) TableName() string

func (*OAuthState) Values added in v0.0.6

func (m *OAuthState) Values() []any

type OAuthUserInfo added in v0.0.2

type OAuthUserInfo struct {
	ID    string
	Email string
	Name  string
}

type PasswordData added in v0.0.2

type PasswordData struct {
	Current string
	New     string
	Confirm string
}

PasswordData is validated by ProfileModule (password change sub-form).

type Permission added in v0.0.6

type Permission struct {
	ID       string `json:"id" db:"pk"`
	Name     string `json:"name"`
	Resource string `json:"resource"`
	Action   string `json:"action"`
}

Permission

func ReadAllPermission added in v0.0.6

func ReadAllPermission(qb *orm.QB) ([]*Permission, error)

func ReadOnePermission added in v0.0.6

func ReadOnePermission(qb *orm.QB, model *Permission) (*Permission, error)

func (*Permission) Pointers added in v0.0.6

func (m *Permission) Pointers() []any

func (*Permission) Schema added in v0.0.6

func (m *Permission) Schema() []orm.Field

func (Permission) TableName added in v0.0.6

func (Permission) TableName() string

func (*Permission) Values added in v0.0.6

func (m *Permission) Values() []any

type ProfileData added in v0.0.2

type ProfileData struct {
	Name  string
	Phone string
}

ProfileData is validated by ProfileModule (name/phone update).

type RBACObject added in v0.0.6

type RBACObject interface {
	HandlerName() string
	AllowedRoles(action byte) []byte
}

type RegisterData added in v0.0.2

type RegisterData struct {
	Name     string
	Email    string
	Password string
	Phone    string
}

RegisterData is validated by RegisterModule.

type Role added in v0.0.6

type Role struct {
	ID          string `json:"id" db:"pk"`
	Code        string `json:"code"`
	Name        string `json:"name"`
	Description string `json:"description"`
}

Role

func ReadAllRole added in v0.0.6

func ReadAllRole(qb *orm.QB) ([]*Role, error)

func ReadOneRole added in v0.0.6

func ReadOneRole(qb *orm.QB, model *Role) (*Role, error)

func (*Role) Pointers added in v0.0.6

func (m *Role) Pointers() []any

func (*Role) Schema added in v0.0.6

func (m *Role) Schema() []orm.Field

func (Role) TableName added in v0.0.6

func (Role) TableName() string

func (*Role) Values added in v0.0.6

func (m *Role) Values() []any

type RolePermission added in v0.0.6

type RolePermission struct {
	RoleID       string `json:"role_id"`
	PermissionID string `json:"permission_id"`
}

RolePermission

func ReadAllRolePermission added in v0.0.6

func ReadAllRolePermission(qb *orm.QB) ([]*RolePermission, error)

func ReadOneRolePermission added in v0.0.6

func ReadOneRolePermission(qb *orm.QB, model *RolePermission) (*RolePermission, error)

func (*RolePermission) Pointers added in v0.0.6

func (m *RolePermission) Pointers() []any

func (*RolePermission) Schema added in v0.0.6

func (m *RolePermission) Schema() []orm.Field

func (RolePermission) TableName added in v0.0.6

func (RolePermission) TableName() string

func (*RolePermission) Values added in v0.0.6

func (m *RolePermission) Values() []any

type Rows added in v0.0.2

type Rows interface {
	Scan(dest ...any) error
	Next() bool
	Close() error
	Err() error
}

Rows interface abstracts scanning multiple rows.

type Scanner added in v0.0.2

type Scanner interface {
	Scan(dest ...any) error
}

Scanner interface abstracts scanning a row.

type SecurityEvent added in v0.0.22

type SecurityEvent struct {
	Type      SecurityEventType
	IP        string // client IP, empty if not available
	UserID    string // empty if user not yet identified
	Provider  string // OAuth provider name, for OAuth events
	Resource  string // RBAC resource, for EventAccessDenied
	Timestamp int64  // time.Now().Unix()
}

type SecurityEventType added in v0.0.22

type SecurityEventType uint8
const (
	EventJWTTampered        SecurityEventType = iota // ValidateJWT: HMAC mismatch
	EventOAuthReplay                                 // consumeState: state already consumed (2nd use)
	EventOAuthExpiredState                           // consumeState: state found but past ExpiresAt
	EventOAuthCrossProvider                          // consumeState: provider mismatch (state preserved)
	EventIPMismatch                                  // LoginLAN: IP not registered
	EventNonActiveAccess                             // Login/LoginLAN: status != "active"
	EventUnauthorizedAccess                          // validateSession: cookie present but session invalid
	EventAccessDenied                                // AccessCheck: RBAC denied with valid session
)

type Session added in v0.0.2

type Session struct {
	ID        string `json:"id" db:"pk"`
	UserID    string `json:"user_id" db:"ref=users"`
	ExpiresAt int64  `json:"expires_at"`
	IP        string `json:"ip,omitempty"`
	UserAgent string `json:"user_agent,omitempty"`
	CreatedAt int64  `json:"created_at"`
}

Session

func ReadAllSession added in v0.0.6

func ReadAllSession(qb *orm.QB) ([]*Session, error)

func ReadOneSession added in v0.0.6

func ReadOneSession(qb *orm.QB, model *Session) (*Session, error)

func (*Session) Pointers added in v0.0.6

func (m *Session) Pointers() []any

func (*Session) Schema added in v0.0.6

func (m *Session) Schema() []orm.Field

func (Session) TableName added in v0.0.6

func (Session) TableName() string

func (*Session) Values added in v0.0.6

func (m *Session) Values() []any

type User

type User struct {
	ID          string       `json:"id" db:"pk"`
	Email       string       `json:"email,omitempty" db:"unique"`
	Name        string       `json:"name"`
	Phone       string       `json:"phone,omitempty"`
	Status      string       `json:"status"` // "active", "suspended"
	CreatedAt   int64        `json:"created_at"`
	Roles       []Role       `json:"roles,omitempty" db:"-"`
	Permissions []Permission `json:"permissions,omitempty" db:"-"`
}

User

func ReadAllUser added in v0.0.6

func ReadAllUser(qb *orm.QB) ([]*User, error)

func ReadOneUser added in v0.0.6

func ReadOneUser(qb *orm.QB, model *User) (*User, error)

func (*User) Pointers added in v0.0.6

func (m *User) Pointers() []any

func (*User) Schema added in v0.0.6

func (m *User) Schema() []orm.Field

func (User) TableName added in v0.0.6

func (User) TableName() string

func (*User) Values added in v0.0.6

func (m *User) Values() []any

type UserRole added in v0.0.6

type UserRole struct {
	UserID string `json:"user_id"`
	RoleID string `json:"role_id"`
}

UserRole

func ReadAllUserRole added in v0.0.6

func ReadAllUserRole(qb *orm.QB) ([]*UserRole, error)

func ReadOneUserRole added in v0.0.6

func ReadOneUserRole(qb *orm.QB, model *UserRole) (*UserRole, error)

func (*UserRole) Pointers added in v0.0.6

func (m *UserRole) Pointers() []any

func (*UserRole) Schema added in v0.0.6

func (m *UserRole) Schema() []orm.Field

func (UserRole) TableName added in v0.0.6

func (UserRole) TableName() string

func (*UserRole) Values added in v0.0.6

func (m *UserRole) Values() []any

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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