user

package module
v0.0.7 Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2026 License: MIT Imports: 19 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 register isomorphic UI modules into tinywasm/site.

Documentation

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

Diagrams

Integration

// main.go — application setup

// 1. Configure site (DB shared with user via applyUser internally)
site.SetDB(db)
site.SetUserID(extractUserID)    // reads session cookie, calls user.GetSession
site.CreateRole('a', "Admin", "full access")

// 2. Configure user via Config struct (all optional, zero values = defaults)
site.SetUserConfig(user.Config{
    SessionCookieName: "s",           // default: "session"
    SessionTTL:        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",
        },
    },
})

// 3. Register user modules alongside app modules
site.RegisterHandlers(
    user.LoginModule,     // /login    — handles auth end-to-end (validate → login → session → cookie)
    user.RegisterModule,  // /register
    user.ProfileModule,   // /profile
    user.LANModule,       // /lan
    user.OAuthCallback,   // /oauth/callback
    &myapp.Dashboard{},
)

site.Serve(":8080")
// site.Serve internally calls:  applyUser() → user.Init(dbExecutor, cfg)

// After user registration/OAuth, assign default role:
// site.AssignRole(u.ID, 'v')

Status

Implementation pending. Documentation complete.

Documentation

Overview

Code generated by ormc; DO NOT EDIT. NOTE: Schema() and Values() must always be in the same field order. String PK: set via github.com/tinywasm/unixid before calling db.Create().

Index

Constants

This section is empty.

Variables

View Source
var (
	LoginModule    *loginModule
	RegisterModule *registerModule
	ProfileModule  *profileModule
	LANModule      *lanModule
	OAuthCallback  *oauthModule
)
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 IdentityMeta = 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 LANIPMeta = 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 OAuthStateMeta = 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 PermissionMeta = 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 RoleMeta = 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 RolePermissionMeta = struct {
	TableName    string
	RoleID       string
	PermissionID string
}{
	TableName:    "rbac_role_permissions",
	RoleID:       "role_id",
	PermissionID: "permission_id",
}
View Source
var SessionMeta = 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 UserMeta = 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",
}
View Source
var UserRoleMeta = struct {
	TableName string
	UserID    string
	RoleID    string
}{
	TableName: "rbac_user_roles",
	UserID:    "user_id",
	RoleID:    "role_id",
}

Functions

func AssignLANIP added in v0.0.2

func AssignLANIP(userID, ip, label string) error

func AssignPermission added in v0.0.6

func AssignPermission(roleID, permissionID string) error

func AssignRole added in v0.0.6

func AssignRole(userID, roleID string) error

func BeginOAuth added in v0.0.2

func BeginOAuth(providerName string) (string, error)

func CreateIdentity added in v0.0.2

func CreateIdentity(userID, provider, providerID, email string) error

func CreatePermission added in v0.0.6

func CreatePermission(id, name, resource string, action string) error

func CreateRole added in v0.0.6

func CreateRole(id string, code string, name, description string) error

func DeletePermission added in v0.0.6

func DeletePermission(id string) error

func DeleteRole added in v0.0.6

func DeleteRole(id string) error

func DeleteSession added in v0.0.2

func DeleteSession(id string) error

func HasPermission added in v0.0.6

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

func Init added in v0.0.2

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

func PurgeExpiredOAuthStates added in v0.0.2

func PurgeExpiredOAuthStates() error

func PurgeExpiredSessions added in v0.0.2

func PurgeExpiredSessions() error

func ReactivateUser added in v0.0.2

func ReactivateUser(id string) error

func Register added in v0.0.6

func Register(handlers ...RBACObject) error

func RegisterLAN added in v0.0.2

func RegisterLAN(userID, rut string) error

func RevokeLANIP added in v0.0.2

func RevokeLANIP(userID, ip string) error

func RevokeRole added in v0.0.6

func RevokeRole(userID, roleID string) error

func SessionCookieName added in v0.0.2

func SessionCookieName() string

func SetPassword added in v0.0.2

func SetPassword(userID, password string) error

func SuspendUser added in v0.0.2

func SuspendUser(id string) error

func UnlinkIdentity added in v0.0.2

func UnlinkIdentity(userID, provider string) error

func UnregisterLAN added in v0.0.2

func UnregisterLAN(userID string) error

func UpdateUser added in v0.0.2

func UpdateUser(id, name, phone string) error

func VerifyPassword added in v0.0.2

func VerifyPassword(userID, password string) error

Types

type Config added in v0.0.2

type Config struct {
	SessionCookieName string // default: "session"
	SessionTTL        int    // default: 86400 (24h)
	TrustProxy        bool   // default: false
	OAuthProviders    []OAuthProvider
}

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 GetIdentityByProvider added in v0.0.2

func GetIdentityByProvider(provider, providerID string) (Identity, error)

func GetUserIdentities added in v0.0.2

func GetUserIdentities(userID string) ([]Identity, error)

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 GetLANIPs added in v0.0.2

func GetLANIPs(userID string) ([]LANIP, error)

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 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 GetPermission added in v0.0.6

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

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 GetRole added in v0.0.6

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

func GetRoleByCode added in v0.0.6

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

func GetUserRoles added in v0.0.6

func GetUserRoles(userID string) ([]Role, error)

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 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 CreateSession added in v0.0.2

func CreateSession(userID, ip, userAgent string) (Session, error)

func GetSession added in v0.0.2

func GetSession(id string) (Session, error)

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 Store added in v0.0.2

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

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 CompleteOAuth added in v0.0.2

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

func CreateUser added in v0.0.2

func CreateUser(email, name, phone string) (User, error)

func GetUser added in v0.0.2

func GetUser(id string) (User, error)

func GetUserByEmail added in v0.0.2

func GetUserByEmail(email string) (User, error)

func Login added in v0.0.2

func Login(email, password string) (User, error)

func LoginLAN added in v0.0.2

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

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