user

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2026 License: MIT Imports: 18 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

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)
//                                applyRBAC() → rbac.Init(dbExecutor)

// After user registration/OAuth, assign default role:
// site.AssignRole(u.ID, 'v')  // rbac — completely independent of user lib

Status

Implementation pending. Documentation complete.

Documentation

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 PasswordHashCost = bcrypt.DefaultCost

Functions

func AssignLANIP added in v0.0.2

func AssignLANIP(userID, ip, label 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 DeleteSession added in v0.0.2

func DeleteSession(id string) error

func Init added in v0.0.2

func Init(exec Executor, 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 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 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"`
	UserID     string `json:"user_id"`
	Provider   string `json:"provider"`
	ProviderID string `json:"provider_id"`
	Email      string `json:"email,omitempty"`
	CreatedAt  int64  `json:"created_at"`
}

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)

type LANIP added in v0.0.2

type LANIP struct {
	ID        string
	UserID    string
	IP        string
	Label     string
	CreatedAt int64
}

func GetLANIPs added in v0.0.2

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

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

type ProfileData struct {
	Name  string
	Phone string
}

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

type RegisterData added in v0.0.2

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

RegisterData is validated by RegisterModule.

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"`
	UserID    string `json:"user_id"`
	ExpiresAt int64  `json:"expires_at"`
	IP        string `json:"ip,omitempty"`
	UserAgent string `json:"user_agent,omitempty"`
	CreatedAt int64  `json:"created_at"`
}

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)

type Store added in v0.0.2

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

type User

type User struct {
	ID        string `json:"id"`
	Email     string `json:"email,omitempty"`
	Name      string `json:"name"`
	Phone     string `json:"phone,omitempty"`
	Status    string `json:"status"` // "active", "suspended"
	CreatedAt int64  `json:"created_at"`
}

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)

Jump to

Keyboard shortcuts

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