authority

package
v0.0.13 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Migrate added in v0.0.10

func Migrate(conn ddl.Execer, ddlCompiler ddl.Compiler) error

Migrate reconciles the database schema this package owns: User, Identity, LANIP, OAuthState and Session, in dependency order.

It is deliberately NOT called by New. Schema reconciliation is deploy-time work — running it per process start costs a network round trip per model, which in a Cloudflare Worker is paid again on every isolate cold start (measured at 8.5–10.4 s across ~14 models in veltylabs/iam). Call this once from a migration binary, then let New assume the schema exists.

conn is a ddl.Execer, not an *orm.DB, so a deploy-time transport that can only execute DDL satisfies it — goflare.NewD1Migrator returns exactly that. An *orm.DB's RawConn() also satisfies it, for local/test callers:

// deploy time, against D1's HTTP API:
conn, _ := goflare.NewD1Migrator(accountID, databaseID, apiToken)
err := authority.Migrate(conn, sqlt.NewCompiler())

// local dev / tests, against an in-memory or sqlite DB:
err := authority.Migrate(db.RawConn(), db.RawConn().(ddl.Compiler))

Types

type Module

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 auth.Config) (*Module, error)

New conecta la estrategia de sesion por defecto (una cookie opaca sobre la tabla de sesiones de este Module) y devuelve el modulo listo para usar.

A proposito NO consulta la base. El esquema lo aplica Migrate, una vez en tiempo de despliegue, y el cache de sesiones es de lectura-a-traves: GetSession resuelve un fallo consultando esa sesion por id. Precalentarlo costaria un escaneo completo de la tabla en cada arranque de isolate, que en un Worker se paga muchas veces y no se amortiza nunca.

func (*Module) Add

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

Add returns all admin-managed CRUDP handlers for registration. Usage: cp.RegisterHandlers(m.Add()...)

func (*Module) AssignLANIP

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

func (*Module) Authenticate

func (m *Module) Authenticate() router.Middleware

Authenticate returns a router.Middleware that asks the active SessionStrategy to identify the caller. If valid, sets UserId in the context via ctx.SetUserID(id). If invalid, UserId remains empty (anonymous).

authority identifies; it never authorizes — that is rbac.Service.Can (see ARCHITECTURE.md). A composition root wires Authenticate() as Authn and rbac.Service.Can as Authorize, two separate ports.

func (*Module) ConsumeState

func (m *Module) ConsumeState(state, provider string) error

func (*Module) CreateSession

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

func (*Module) CreateState

func (m *Module) CreateState(provider string) (string, error)

func (*Module) CreateUser

func (m *Module) CreateUser(email, name, phone string) (auth.User, error)

func (*Module) DeleteSession

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

func (*Module) Enable

func (m *Module) Enable(auths ...auth.Authenticator)

Enable registers the authentication modes this app supports — 1 or N. authority never constructs a mode itself: the consumer builds each one (injecting whichever ports of m it needs) and hands it here.

func (*Module) GetLANIPs

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

func (*Module) GetOrCreateSubject

func (m *Module) GetOrCreateSubject(id user.SubjectID, email, name, avatar string) (user.Subject, error)

func (*Module) GetSession

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

func (*Module) GetUser

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

func (*Module) GetUserByEmail

func (m *Module) GetUserByEmail(email string) (auth.User, error)

func (*Module) GetUserIdentities

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

func (*Module) IdentityByProvider

func (m *Module) IdentityByProvider(provider, providerID string) (auth.Identity, error)

func (*Module) IdentityFor

func (m *Module) IdentityFor(userID, provider string) (auth.Identity, error)

func (*Module) IsTrustedIP

func (m *Module) IsTrustedIP(userID, ip string) bool

func (*Module) IssueSession

func (m *Module) IssueSession(ctx router.Context, userID string) error

func (*Module) Login

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

Login verifies email+password directly (no HTTP) — used by email_password/credentials tests and any admin flow that needs to verify a user's password without going through the mounted route.

func (*Module) LoginLAN

func (m *Module) LoginLAN(rut string, ctx router.Context) (auth.User, error)

LoginLAN verifies a RUT + the caller's IP directly (no HTTP) — used by tests and any admin flow. Mirrors exactly what trusted_ip's Mount handler does, using the same ValidateRUT algorithm — see §7's doc comment on ValidateRUT.

func (*Module) ModelName

func (m *Module) ModelName() string

func (*Module) MountAPI

func (m *Module) MountAPI(r router.Router)

MountAPI mounts the one session-termination endpoint centrally — logout ends a session the same way no matter which mode started it (strategy.Revoke) — then lets every enabled Authenticator mount its own login route. authority never inspects what a mode mounts.

func (*Module) MountOps

func (m *Module) MountOps(reg router.OpRegistry)

func (*Module) Notify

func (m *Module) Notify(e auth.SecurityEvent)

func (*Module) PurgeExpiredOAuthStates

func (m *Module) PurgeExpiredOAuthStates() error

PurgeExpiredOAuthStates is maintenance, not part of any port — call it periodically from a cron-like task in the consuming app.

func (*Module) PurgeExpiredSessions

func (m *Module) PurgeExpiredSessions() error

func (*Module) PurgeSessionsByUser

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

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

func (*Module) ReactivateUser

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

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

func (*Module) RegisterLAN

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

RegisterLAN links a RUT to userID as their trusted_ip identity.

func (*Module) RevokeLANIP

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

func (*Module) RotateSession

func (m *Module) RotateSession(oldID, ip, userAgent string) (auth.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

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

SetLog configures optional logging. Call immediately after New(). Default: no-op.

func (*Module) SetPassword

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

SetPassword hashes and stores password as userID's email_password credential.

func (*Module) SetStrategy

func (m *Module) SetStrategy(s auth.SessionStrategy)

SetStrategy overrides how sessions are carried. Call before mounting. A nil argument is ignored — the default set by New is already production-ready; this exists to opt into session/jwt or a custom strategy, never to unset it.

func (*Module) SuspendUser

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

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

func (*Module) UnlinkIdentity

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

func (*Module) UnregisterLAN

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

UnregisterLAN removes userID's trusted_ip identity and all their allowed IPs.

func (*Module) UpdateUserAvatar

func (m *Module) UpdateUserAvatar(userID, avatar string) error

func (*Module) UpsertIdentity

func (m *Module) UpsertIdentity(userID, provider, providerID, email string) error

func (*Module) UserByEmail

func (m *Module) UserByEmail(email string) (auth.User, error)

func (*Module) UserByID

func (m *Module) UserByID(id string) (auth.User, error)

func (*Module) VerifyPassword

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

VerifyPassword checks password against userID's stored email_password hash.

Jump to

Keyboard shortcuts

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