Documentation
¶
Overview ¶
Package identity is the identity battery: accounts with a password or an OAuth provider, the access tokens that prove them, the middleware that checks those tokens, the administration of users and an audit log.
type Config struct {
chok.Base
DB db.Config `yaml:"db"`
Auth identity.Config `yaml:"auth"`
}
d := db.MustOpen(cfg.DB, db.Tables(db.Table(&Post{})))
auth := identity.MustNew(cfg.Auth, d)
app.Use(d, auth) // mounts /auth/*
api := app.Group("/api/v1", auth.Authn()) // admits valid tokens only
Routes ¶
Mount registers register, login, refresh-token, change-password and me under auth.prefix (/auth), forgot-password and reset-password with a Sender, passwordless/start and passwordless/verify with auth.passwordless, logout in cookie mode, and the OAuth routes with Providers. The public ones are documented without security in the OpenAPI document. Request and response bodies are v2's: register takes {email, password, name} and answers 201 {token, expires_at}; login takes {email, password}.
Mail and passwordless sign-in ¶
With Sender(fn), identity asks the application to send mail: a password-reset token from forgot-password, and — with auth.passwordless.enabled — a sign-in code. fn gets the address, the template's name — the Mail's Kind — and the Mail as its data, so the mail battery plugs in as identity.Sender(mailer.SendTemplate); the send runs in the background and Close waits for it. POST {prefix}/passwordless/start {email} always answers 202 and mails a code and a magic-link token, unless an unused one went out within auth.passwordless.resend_after; POST {prefix}/passwordless/verify with {email, code} or {token} answers what login does, creating the account of an unknown address unless auto_register is off. The code that first proves an existing account's address takes the account over: the password set before it stops working and its tokens are revoked. Codes are kept as HMACs in auth_login_codes, tried at most max_attempts times. With auth.passwordless.only the password routes are not mounted at all.
Cookie mode ¶
With auth.cookie.enabled, every route that issues a token also sets it in an HttpOnly session cookie — with auth.cookie.only, in the cookie alone — Authn reads that cookie from a request without an Authorization header, and POST {prefix}/logout clears it. A browser sends the cookie with every request to the API, so serve the front end from the same origin and keep http.csrf on (the default; the App warns at startup when it is off); SameSite lax, the default, keeps it off other sites' POSTs. The OAuth callbacks are exempt from http.csrf: Apple posts its callback from its own site, and the state parameter defends it.
Tokens and the principal ¶
A token is an HS256 JWT signed with auth.signing_key, valid for auth.token_ttl; refresh-token trades it for a fresh one until the session is auth.refresh_ttl old. Authn checks the token and the account behind it on every request — a disabled user, or one whose password or roles changed, is refused at once — and stores a chok.Principal whose UserID is the user's id (usr_…). store's owner scope writes that id to owner_id.
Tables ¶
New registers users, identities, audit_logs and auth_login_codes under the owner "identity": migrate auto creates them from the models, versioned applies the SQL files embedded in this package (one directory per dialect), off checks they were applied.
OAuth ¶
identity/google, identity/github, identity/apple and identity/facebook each return a Provider from their New. A sign-in starts at {prefix}/{name}/start, comes back to the provider's callback and ends with the front end trading a one-time code for a token at {prefix}/exchange, from the browser that holds the binding cookie. The state of the sign-ins in flight lives in this process.
Audit ¶
With auth.audit.enabled, Audit().Log records who did what, in the background; records are only ever added, and purged after auth.audit.retention.
Example ¶
The battery is a value: build it on the database, register it with the App, and guard the application's routes with Authn.
package main
import (
"context"
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"github.com/zynthara/chok"
"github.com/zynthara/chok/db"
"github.com/zynthara/chok/identity"
)
func main() {
d := db.MustOpen(db.Config{Driver: "sqlite", SQLite: db.SQLiteConfig{Path: ":memory:"}})
auth := identity.MustNew(identity.Config{SigningKey: strings.Repeat("k", 32)}, d)
app := chok.New(chok.MustLoad[chok.Base]("example", chok.Args(nil)), chok.Logger(slog.New(slog.DiscardHandler)))
app.Use(d, auth)
chok.GET(app.Group("/api", auth.Authn()), "/me", func(ctx context.Context, _ *chok.None) (string, error) {
p, _ := chok.PrincipalFrom(ctx)
return p.Email, nil
})
rec := httptest.NewRecorder()
app.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/me", nil))
fmt.Println(rec.Code)
}
Output: 401
Index ¶
- Constants
- type Audit
- type AuditConfig
- type Config
- type CookieConfig
- type Event
- type Identity
- func (idn *Identity) Audit() *Audit
- func (idn *Identity) Authn() chok.Middleware
- func (idn *Identity) Close(ctx context.Context) error
- func (idn *Identity) Health(context.Context) error
- func (idn *Identity) Mount(r chok.Router)
- func (idn *Identity) Name() string
- func (idn *Identity) Users() *UserService
- type Mail
- type Option
- type PasswordlessConfig
- type Provider
- type ProviderConfig
- type User
- type UserService
- func (s *UserService) Create(ctx context.Context, email, password, name string) (*User, error)
- func (s *UserService) Get(ctx context.Context, id string) (*User, error)
- func (s *UserService) GetByEmail(ctx context.Context, email string) (*User, error)
- func (s *UserService) ListFromQuery(ctx context.Context, q url.Values) (*chok.Page[User], error)
- func (s *UserService) MarkEmailVerified(ctx context.Context, id string) error
- func (s *UserService) QueryFields() []string
- func (s *UserService) ResetPassword(ctx context.Context, id, password string) error
- func (s *UserService) RevokeTokens(ctx context.Context, id string) error
- func (s *UserService) SetActive(ctx context.Context, id string, active bool) error
- func (s *UserService) SetRoles(ctx context.Context, id string, roles []string) error
Examples ¶
Constants ¶
const ( ResultSuccess = "success" ResultFailure = "failure" ResultDenied = "denied" ActorUser = "user" ActorSystem = "system" ActorAPIKey = "api_key" )
The results and actor types an Event records. The values are stored and filtered on; they never change.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Audit ¶
type Audit struct {
// contains filtered or unexported fields
}
Audit is the audit log: records are written in the background and only ever added — the log has no update or delete, and the records older than auth.audit.retention are purged every hour. With auth.audit off, Log and LogSync do nothing.
func (*Audit) ListFromQuery ¶
ListFromQuery returns a page of records, newest first: q holds page and size (default 50, at most 500), order=field:asc|desc, from and to (RFC 3339, inclusive bounds on occurred_at) and equality filters on the fields QueryFields lists. An unknown or malformed parameter is a 400. The caller must hold admin or audit/read. It can serve a chok.List route.
func (*Audit) Log ¶
Log queues e for the writer and returns. When the queue is full it waits for room, or drops e if the caller's context ends first; with auth.audit.drop_on_full it drops e at once. A dropped event is logged as a warning. Log does not join the caller's transaction: it records what was attempted even when the transaction rolls back.
Example ¶
An audit event names what happened; Log fills in who did it from the request.
package main
import (
"context"
"github.com/zynthara/chok/identity"
)
func main() {
var auth *identity.Identity // from identity.New, with auth.audit.enabled
publish := func(ctx context.Context, postID string) {
auth.Audit().Log(ctx, identity.Event{
Action: "post.publish", Resource: "post", ResourceID: postID,
Before: map[string]string{"status": "draft"}, After: map[string]string{"status": "published"},
})
}
_ = publish
}
Output:
func (*Audit) LogSync ¶
LogSync writes e before it returns, inside the caller's transaction if ctx carries one: use it when the record must exist for the operation to count.
func (*Audit) QueryFields ¶
QueryFields lists the fields ListFromQuery filters and orders on.
type AuditConfig ¶
type AuditConfig struct {
// Enabled turns the audit log on; off, Log does nothing.
Enabled bool `yaml:"enabled"`
// Retention is how long a record is kept; older ones are purged every
// hour. 0 keeps records forever.
Retention time.Duration `yaml:"retention" default:"4320h"`
// AsyncBuffer is how many records Log queues for the writer.
AsyncBuffer int `yaml:"async_buffer" default:"1024"`
// DropOnFull drops a record when the queue is full, instead of making
// Log wait for room (or for the caller's context to end).
DropOnFull bool `yaml:"drop_on_full"`
// AdminAPI mounts GET /audit/logs for administrators: the principal
// needs the admin role, or the audit/read permission once
// identity/rbac is in use.
AdminAPI bool `yaml:"admin_api" default:"true"`
}
AuditConfig is auth.audit: the audit log of who did what, written in the background and kept for Retention.
type Config ¶
type Config struct {
// Prefix is where the routes mount: {prefix}/register, {prefix}/login, ...
Prefix string `yaml:"prefix" default:"/auth"`
// SigningKey signs the access and password-reset tokens (HS256); at
// least 32 bytes.
SigningKey string `yaml:"signing_key" secret:"true"`
// TokenTTL is how long an access token is valid.
TokenTTL time.Duration `yaml:"token_ttl" default:"2h"`
// RefreshTTL bounds a session: refresh-token issues fresh tokens until
// RefreshTTL after the login that started the session, then the user
// logs in again. Every session ends: 0 takes the default.
RefreshTTL time.Duration `yaml:"refresh_ttl" default:"168h"`
// ResetTTL is how long a password-reset token is valid.
ResetTTL time.Duration `yaml:"reset_ttl" default:"15m"`
// ResetURL is the front end's password-reset page, an absolute URL:
// given, the password-reset Mail's Link is ResetURL?token=<token>, for
// the page to post to {prefix}/reset-password; without it the
// application builds the link from Mail.Token.
ResetURL string `yaml:"reset_url"`
// LoginRateWindow and LoginRateLimit throttle failed sign-ins and the
// mails asked for: once an email or a user has failed to sign in, or
// asked forgot-password or confirm-email/start for a mail,
// LoginRateLimit times within the window, that route answers 429
// until the window slides. LoginRateLimitPerIP is the limit of a
// client address, by chok.ClientIP, within the same window: its failed
// logins and passwordless/verify calls, and every forgot-password and
// passwordless/start it makes. Everyone behind a NAT, a carrier or a
// proxy that http.trusted_proxies does not list shares one address, so
// its default is wider; 0 counts no address, and emails and users
// count all the same. LoginRateWindow and LoginRateLimit both 0 turn
// the throttle off, and LoginRateLimitPerIP is then ignored.
LoginRateWindow time.Duration `yaml:"login_rate_window" default:"15m"`
LoginRateLimit int `yaml:"login_rate_limit" default:"10"`
LoginRateLimitPerIP int `yaml:"login_rate_limit_per_ip" default:"100"`
// DisableRegister drops the register route: accounts come from
// Users().Create.
DisableRegister bool `yaml:"disable_register"`
// LinkByEmail lets a first OAuth sign-in join the local account with
// the same email, when that account's email is verified and the
// provider vouches for the address and does not alias it. Facebook,
// which does not say whether an address is confirmed, never joins. An
// account Facebook made, its address only assumed, is taken over by
// the join: the providers linked before are unlinked, the password is
// cleared and the tokens are revoked.
LinkByEmail bool `yaml:"link_by_email"`
// AllowedRedirectBacks lists the absolute URLs an OAuth sign-in may
// return to through ?redirect_back: an entry ending in / allows its
// subtree, any other entry that page. Relative paths are always allowed.
AllowedRedirectBacks []string `yaml:"allowed_redirect_backs"`
// OAuthCallbackFrontendURL is the front-end page an OAuth callback
// sends the browser to with a one-time ?code, which the page trades
// for a token at {prefix}/exchange. Required with providers.
OAuthCallbackFrontendURL string `yaml:"oauth_callback_frontend_url"`
// Providers configures the OAuth providers by name; the code decides
// which ones run: identity.Providers(google.New(cfg.Providers["google"])).
Providers map[string]ProviderConfig `yaml:"providers"`
// Passwordless signs users in with a code mailed to them.
Passwordless PasswordlessConfig `yaml:"passwordless"`
// Cookie carries the access token in an HttpOnly cookie as well, for
// browsers.
Cookie CookieConfig `yaml:"cookie"`
// Audit configures the audit log.
Audit AuditConfig `yaml:"audit"`
// Admins lists the email addresses of the first administrators: a
// user whose address is listed, and verified, gets the admin role the
// next time a token is issued to it or Authn reads it. The grant is
// written once and never undone here: removing an address revokes
// nothing (Users().SetRoles does). An unverified address gets nothing,
// so whoever registers a listed address first gains no power by it,
// and loses the account once the owner proves the address with a
// mailed reset token or code. Facebook, which does not say whether an
// address is confirmed, cannot create the account of a listed one, and
// an account it made before the address was listed gets nothing until
// its user confirms the address with a mailed code in a session.
// Users().MarkEmailVerified keeps the registrant's password: an
// application that verifies addresses that way should have the owners
// register the listed ones, or turn registration off.
Admins []string `yaml:"admins"`
}
Config is the auth section of an application's configuration:
auth:
token_ttl: 2h
providers:
google:
client_id: 1234.apps.googleusercontent.com
redirect_url: https://api.example.com/auth/google/callback
oauth_callback_frontend_url: https://app.example.com/signed-in
SigningKey is a secret: set it from the environment (BLOG_AUTH_SIGNING_KEY for an app loaded as "blog"), never in a file. New gives an empty Prefix and a zero TokenTTL, RefreshTTL, ResetTTL or Audit.AsyncBuffer the defaults below, whether the Config comes from a file or from code; a zero login throttle is off, a zero LoginRateLimitPerIP counts no client address and a zero Audit.Retention keeps records forever.
type CookieConfig ¶
type CookieConfig struct {
// Enabled turns cookie mode on.
Enabled bool `yaml:"enabled"`
// Name is the cookie's name.
Name string `yaml:"name" default:"chok_token"`
// Domain shares the cookie with the domain's subdomains; empty, it is
// the API host's alone.
Domain string `yaml:"domain"`
// Path is where the browser sends the cookie.
Path string `yaml:"path" default:"/"`
// Secure sends the cookie over https only; nil means true. Turn it off
// for plain http on localhost alone.
Secure *bool `yaml:"secure"`
// SameSite is lax (the cookie stays home on another site's POST),
// strict or none; none needs Secure.
SameSite string `yaml:"same_site" default:"lax" validate:"omitempty,oneof=lax strict none"`
// Only leaves the token out of the response bodies: {expires_at} alone,
// the cookie the whole session, out of the page's scripts' reach.
Only bool `yaml:"only"`
}
CookieConfig is auth.cookie: the session in an HttpOnly cookie. Every route that issues a token — register, login, refresh-token, passwordless verify, the OAuth exchange — sets the cookie too, Authn reads it from a request without an Authorization header, and POST {prefix}/logout clears it. A cookie rides along with every request the browser makes: serve the front end from the same origin and keep http.csrf on (the default).
type Event ¶
type Event struct {
// ID is the record's id (aud_…), set when it is written.
ID string `json:"id"`
OccurredAt time.Time `json:"occurred_at"`
// Action names what happened, verb last: "post.publish", "user.role.set".
Action string `json:"action"`
// Result is ResultSuccess, ResultFailure or ResultDenied.
Result string `json:"result"`
Resource string `json:"resource,omitzero"`
ResourceID string `json:"resource_id,omitzero"`
// ActorID is who acted: a user id, or an API key's id with ActorType
// ActorAPIKey; ActorType defaults to ActorUser when ActorID is set.
ActorID string `json:"actor_id,omitzero"`
ActorType string `json:"actor_type,omitzero"`
ActorIP string `json:"actor_ip,omitzero"`
// Before and After are the resource's state around the change, stored
// as JSON; leave out what must not be kept, the log stores it all.
Before any `json:"before,omitzero"`
After any `json:"after,omitzero"`
// Reason is a note for auditors, at most 512 bytes.
Reason string `json:"reason,omitzero"`
Metadata map[string]any `json:"metadata,omitzero"`
TraceID string `json:"trace_id,omitzero"`
RequestID string `json:"request_id,omitzero"`
}
Event is one audit record: who did what to which resource, and how it ended. Log takes one — Action is required, the rest optional — and fills the blanks it can: the actor from the request's principal, its address and request id, the trace id when the binary links telemetry, Result "success", OccurredAt now. ListFromQuery returns events with ID and OccurredAt set.
type Identity ¶
type Identity struct {
// contains filtered or unexported fields
}
Identity is the identity battery: accounts with passwords and OAuth sign-in, the tokens that prove them, the middleware that checks those tokens, and the audit log. Register it with app.Use: it mounts its routes, reports health and closes.
func New ¶
New builds the identity battery on d: it registers the users, identities, audit_logs and auth_login_codes tables under the owner "identity" (created now in migrate: auto; from its embedded SQL files in migrate: versioned) and checks cfg and every provider. A Config from chok.Load carries the defaults; one built in code gets them for its zero fields.
func (*Identity) Authn ¶
func (idn *Identity) Authn() chok.Middleware
Authn is the middleware that admits a request with a valid access token: a Bearer JWT this Identity signed — in cookie mode, the session cookie's, when the request has no Authorization header — whose user still exists, is active and has not had its tokens revoked since (a password change, a role change, a disable, Users().RevokeTokens). It reads the user on every request, so a revocation takes effect at once. The request then carries the chok.Principal — UserID is the user's id (usr_…), which a store's owner scope writes to owner_id — and anything else is a 401 envelope.
The OpenAPI document lists the routes behind it with the schemes it accepts: bearerAuth, and in cookie mode cookieAuth.
func (*Identity) Close ¶
Close waits, within ctx, for the mails in flight and writes the queued audit events, and stops the background work: the login code sweep, the login throttle's sweeps and the OAuth session store's.
func (*Identity) Health ¶
Health fails while the audit log cannot write: its latest write failed less than a minute ago and none has gone through since. A write that fails once its caller's context has ended does not count.
func (*Identity) Mount ¶
Mount registers the routes under the prefix (/auth by default):
POST {prefix}/register public; not with disable_register
POST {prefix}/login public, throttled
POST {prefix}/forgot-password public, throttled; with a Sender
POST {prefix}/reset-password public; with a Sender
POST {prefix}/refresh-token bearer
PUT {prefix}/change-password bearer
GET {prefix}/me bearer
With auth.passwordless.enabled, sign-in by a mailed code:
POST {prefix}/passwordless/start public, throttled: mail a code, 202
POST {prefix}/passwordless/verify public, throttled: the code or token for a token
and with auth.passwordless.only no password routes: register, login, forgot-password, reset-password and change-password are left out.
With auth.cookie.enabled the routes that issue a token set the session cookie too, and one more route clears it:
POST {prefix}/logout bearer or cookie: 204
With providers, the OAuth routes too:
GET {prefix}/{name}/start public; GET or POST /{name}/callback after it
POST {prefix}/exchange public: the one-time code for a token
GET {prefix}/identities bearer: the user's login methods
POST {prefix}/identities/link bearer: link another provider, the email verified
DELETE {prefix}/identities/{id} bearer: unlink one
and, with a Sender and a provider that only implies its addresses are verified (Facebook), where a signed-in user confirms the address:
POST {prefix}/confirm-email/start bearer, throttled: mail a code, 202
POST {prefix}/confirm-email bearer, throttled: the code, 204
and with auth.audit.enabled and admin_api, GET /audit/logs. The OpenAPI document lists the routes behind Authn with its schemes and the others without security. A throttled route answers 429 past auth.login_rate_limit for an email or a user, or auth.login_rate_limit_per_ip for a client address, within auth.login_rate_window: login, passwordless/verify and confirm-email count the failures, the others every call.
func (*Identity) Users ¶
func (idn *Identity) Users() *UserService
Users is the administration of accounts.
type Mail ¶
type Mail struct {
// Kind is what the mail is for: "password-reset", "login-code" or
// "confirm-email", the code a signed-in user confirms the address with.
Kind string
// To is the address to send it to.
To string
// Token is the password-reset token, which the reset page posts to
// {prefix}/reset-password with the new password, or the login code's
// magic-link token, which the sign-in page posts to
// {prefix}/passwordless/verify.
Token string
// Code is the login or confirmation code,
// auth.passwordless.code_length digits; empty for a password reset.
Code string
// Link is the page that takes Token: auth.reset_url or
// auth.passwordless.magic_link_url with ?token= added. Empty without
// them, and the application builds its own from Token. A confirmation
// has neither: its code is entered in the session that asked for it.
Link string
// ExpiresAt is when Token, and Code, stop working, in UTC.
ExpiresAt time.Time
}
Mail is a mail identity asks the application to send: the Sender gets it as the data of the template named after its Kind.
type Option ¶
type Option func(*options)
Option configures New.
func Logger ¶
Logger is where identity logs outside requests; the default is slog.Default(). On a request it logs with chok.LoggerFrom.
func Providers ¶
Providers enables OAuth sign-in through the given providers, from identity/google, identity/github, identity/apple and identity/facebook.
func Sender ¶
Sender gives identity a way to mail: it enables the forgot-password and reset-password routes, which are not mounted without it, and passwordless sign-in needs it. For each mail identity calls fn(ctx, m.To, m.Kind, m): the template is named after the Mail's Kind and the Mail is its data ({{.Code}}, {{.Link}}, {{.ExpiresAt}}), which is the shape of the mail battery's SendTemplate:
identity.Sender(mailer.SendTemplate)
identity calls fn in the background, so a response never waits on it; an error is logged as a warning, and Close waits for the sends in flight. ctx carries the request's values, not its cancellation, and ends a minute into the send, or sooner when Close stops waiting: fn should return when ctx is done. The minute is a backstop for a Sender without a timeout of its own; SendTemplate keeps to mail.timeout.
type PasswordlessConfig ¶
type PasswordlessConfig struct {
// Enabled mounts the two routes; it needs a Sender to mail the codes.
Enabled bool `yaml:"enabled"`
// Only leaves passwordless sign-in the only way in, for an application
// whose accounts are their addresses: register, login, forgot-password,
// reset-password and change-password are not mounted. refresh-token,
// me, logout, OAuth and the identities routes stay, and
// Users().Create and ResetPassword still work. It needs Enabled.
Only bool `yaml:"only"`
// CodeTTL is how long a code, and its magic-link token, is valid.
CodeTTL time.Duration `yaml:"code_ttl" default:"10m"`
// CodeLength is how many digits a code has, 6 to 10.
CodeLength int `yaml:"code_length" default:"6" validate:"omitempty,min=6,max=10"`
// MaxAttempts is how many wrong codes a code survives; after them the
// user asks for a new one.
MaxAttempts int `yaml:"max_attempts" default:"5"`
// ResendAfter is the least time between two codes for one address
// while the first is unused: a start within it answers the same 202
// and mails nothing.
ResendAfter time.Duration `yaml:"resend_after" default:"60s"`
// MagicLinkURL is the front end's sign-in page, an absolute URL:
// given, the login-code Mail's Link is MagicLinkURL?token=<token>, for
// the page to post to {prefix}/passwordless/verify.
MagicLinkURL string `yaml:"magic_link_url"`
// AutoRegister lets the first sign-in of an unknown address create its
// account, email verified, without a password; nil means true. False,
// only existing accounts sign in.
AutoRegister *bool `yaml:"auto_register"`
}
PasswordlessConfig is auth.passwordless: signing in with a code mailed to the address, no password. POST {prefix}/passwordless/start mails a code, and a magic-link token; POST {prefix}/passwordless/verify trades either for a session. New gives the zero durations and counts the defaults below.
type Provider ¶
type Provider interface {
// Name is the provider's key in auth.providers and its URL segment:
// {prefix}/{name}/start.
Name() string
// Check reports a configuration the provider refuses; New fails with it.
Check() error
// Capabilities is how the provider's sign-in runs.
Capabilities() oauth.Capabilities
// BeginAuth returns the provider's authorization URL for one sign-in.
BeginAuth(ctx context.Context, req *oauth.BeginRequest) (string, error)
// CompleteAuth trades the callback's code for the user's identity.
CompleteAuth(ctx context.Context, req *oauth.CompleteRequest) (*oauth.Identity, error)
}
Provider is an OAuth identity provider: what identity/google, identity/github, identity/apple and identity/facebook return from their New. Pass it to New with Providers; identity drives the sign-in through these methods, whose types belong to identity, so the four packages are the providers there are.
type ProviderConfig ¶
type ProviderConfig struct {
// ClientID is the OAuth client: Google's client ID, GitHub's and
// Facebook's app ID, Apple's Services ID.
ClientID string `yaml:"client_id"`
// ClientSecret is the client's secret; for Apple, the PEM contents of
// the .p8 signing key.
ClientSecret string `yaml:"client_secret" secret:"true"`
// RedirectURL is the callback registered with the provider:
// https://api.example.com/auth/google/callback.
RedirectURL string `yaml:"redirect_url"`
// Scopes replaces the provider's default scopes.
Scopes []string `yaml:"scopes"`
// Endpoint replaces the provider's base URL: a GitHub Enterprise
// server, a Graph API version for Facebook, the issuer for Google and
// Apple (a test server, mostly).
Endpoint string `yaml:"endpoint"`
// HostedDomain accepts only accounts of one Google Workspace domain.
HostedDomain string `yaml:"hosted_domain"`
// TeamID and KeyID identify Apple's signing key: the developer team
// and the key, ten characters each.
TeamID string `yaml:"team_id"`
KeyID string `yaml:"key_id"`
}
ProviderConfig is one OAuth provider's section, auth.providers.<name>. A provider uses the fields its package documents and refuses the rest.
type User ¶
type User struct {
db.SoftDeleteModel
Email string `json:"email" store:"query,update" gorm:"size:200;not null"`
// EmailVerified records that the address is the user's: a mailed reset
// token or code proved it, an OAuth provider vouched for it, or the
// application called UserService.MarkEmailVerified.
EmailVerified bool `json:"email_verified" store:"query,update" gorm:"column:email_verified;default:false;not null"`
// EmailAssumed marks an EmailVerified that rests on a provider's word
// alone: Facebook returns an address without saying it is confirmed.
// The address serves as verified, but auth.admins grants it nothing,
// and the first proof of it from outside the account — a mailed reset
// token or code, a link_by_email sign-in through a provider that states
// it — takes the account over as for an unverified one. The user keeps
// the account as it is by confirming the address in a session: a code
// mailed by POST {prefix}/confirm-email/start, or a linked provider
// that states the same address.
EmailAssumed bool `json:"email_assumed" store:"query,update" gorm:"column:email_assumed;default:false;not null"`
// PasswordHash is the bcrypt hash; an account created through OAuth
// holds the hash of a random secret nobody knows.
PasswordHash string `json:"-" store:"update" gorm:"column:password_hash;size:128;not null"`
// HasPassword records that the user set a password, so the password
// login is theirs; false for an account created through OAuth until a
// password reset.
HasPassword bool `json:"-" store:"update" gorm:"column:has_password;default:false;not null"`
// PasswordVersion is in every token; bumping it revokes them all.
PasswordVersion int `json:"-" store:"update" gorm:"column:password_version;default:0;not null"`
Name string `json:"name" store:"query,update" gorm:"size:100;default:'';not null"`
// Roles is the comma-separated role list; RoleList splits it.
Roles string `json:"-" store:"update" gorm:"size:500;default:'';not null"`
Active bool `json:"-" store:"query,update" gorm:"default:true;not null"`
}
User is an account. Its ID (the RID, usr_…) is the stable user id: the UserID of the chok.Principal Authn stores, and so the owner_id of the rows a store fences to the user. The password hash, the token version, the roles and the active flag never leave the server.
type UserService ¶
type UserService struct {
// contains filtered or unexported fields
}
UserService is the administration of accounts — what an operator does to a user, as opposed to what users do through the routes. A missing user is a 404 error; every change that affects the user's tokens (password, roles, active flag) revokes them, so the next request logs in again and picks the change up.
Example ¶
The administration of accounts, for a deployment that provisions them.
package main
import (
"context"
"fmt"
"strings"
"github.com/zynthara/chok/db"
"github.com/zynthara/chok/identity"
)
func main() {
d := db.MustOpen(db.Config{Driver: "sqlite", SQLite: db.SQLiteConfig{Path: ":memory:"}})
auth := identity.MustNew(identity.Config{SigningKey: strings.Repeat("k", 32), DisableRegister: true}, d)
ctx := context.Background()
u, err := auth.Users().Create(ctx, "ops@example.com", "Initial-pass1", "Ops")
if err != nil {
fmt.Println(err)
return
}
// Each change revokes the user's tokens: the next login carries it.
_ = auth.Users().SetRoles(ctx, u.RID, []string{"admin"})
fmt.Println(strings.HasPrefix(u.RID, "usr_"))
}
Output: true
func (*UserService) Create ¶
Create makes an active account with a password, as register does: for a deployment that turns registration off and provisions accounts.
func (*UserService) GetByEmail ¶
GetByEmail returns the user with the email address, compared as identity stores addresses: trimmed and in lower case.
func (*UserService) ListFromQuery ¶
ListFromQuery returns a page of every account, for an administration page: q holds page and size (default 20, at most 100), cursor, order=field:asc|desc and equality filters on the fields QueryFields lists — email compared as identity stores it, email_verified, email_assumed and active as true or false. An unknown or malformed parameter is a 400. The items are User's JSON, which leaves out the roles and the active flag.
It lets the UserService serve a chok.List route, and it answers only the principal in ctx that holds the admin role or, with identity/rbac, is granted user/read: any other principal gets a 403 and a context without one a 401, so a route mounted behind Authn alone lists no one to the users it lets in. A caller outside a request puts its principal in ctx with chok.WithPrincipal.
chok.List(app.Group("/admin", auth.Authn()), "/users", auth.Users())
func (*UserService) MarkEmailVerified ¶
func (s *UserService) MarkEmailVerified(ctx context.Context, id string) error
MarkEmailVerified records that the user proved the email address, after the application's own verification (a link, a code). As with a mailed reset token or code, the first verification unlinks the providers linked before it: identity links none to an unverified account, but data from v2 may. Unlike a mailed code it keeps the password and the tokens, taking the verification for the registrant's own — a link clicked right after registering — so an address in auth.admins should be registered by its owner, or registration turned off. Calling it again is a no-op.
An address only Facebook's word backs (User.EmailAssumed) stays assumed: the application cannot tell who opened its mail, and the account may be someone else's — taking it over would lock its holder out, keeping it would hand the address to whoever holds it. The user confirms the address in a session ({prefix}/confirm-email), or its owner takes the account over with a mailed reset token or code.
func (*UserService) QueryFields ¶
func (s *UserService) QueryFields() []string
QueryFields lists the fields ListFromQuery filters and orders on.
func (*UserService) ResetPassword ¶
func (s *UserService) ResetPassword(ctx context.Context, id, password string) error
ResetPassword sets a new password, held to the register route's rules, and revokes the user's tokens.
func (*UserService) RevokeTokens ¶
func (s *UserService) RevokeTokens(ctx context.Context, id string) error
RevokeTokens makes every token issued to the user stop working, and changes nothing else: for a leaked token, or a log-out everywhere.
func (*UserService) SetActive ¶
SetActive enables or disables the account. Either way its tokens stop working: a disabled user is out at once, a re-enabled one logs in anew.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package apple is Sign in with Apple for identity: OpenID Connect with a nonce, the callback posted as a form, and a client secret the provider signs itself.
|
Package apple is Sign in with Apple for identity: OpenID Connect with a nonce, the callback posted as a form, and a client secret the provider signs itself. |
|
Package facebook is Facebook Login for identity: OAuth 2.0 with PKCE, the user read from the Graph API.
|
Package facebook is Facebook Login for identity: OAuth 2.0 with PKCE, the user read from the Graph API. |
|
Package github is Sign in with GitHub for identity: OAuth 2.0 with PKCE, the user read from the REST API.
|
Package github is Sign in with GitHub for identity: OAuth 2.0 with PKCE, the user read from the REST API. |
|
Package google is Sign in with Google for identity: OpenID Connect, with a nonce and PKCE.
|
Package google is Sign in with Google for identity: OpenID Connect, with a nonce and PKCE. |
|
internal
|
|
|
authz
Package authz connects identity/rbac to identity without widening identity's API: rbac installs its decision on an Identity, which asks it before the audit log's admin API answers.
|
Package authz connects identity/rbac to identity without widening identity's API: rbac installs its decision on an Identity, which asks it before the audit log's admin API answers. |
|
idptest
Package idptest is an OpenID Connect provider in process, for the provider packages' tests: discovery, the signing keys, an authorize stub and a token endpoint that answers the ID token a test staged for a code, signed with RS256.
|
Package idptest is an OpenID Connect provider in process, for the provider packages' tests: discovery, the signing keys, an authorize stub and a token endpoint that answers the ID token a test staged for a code, signed with RS256. |
|
oauth
Package oauth holds what identity and its provider packages share: the shape of a sign-in as identity drives it, and the helpers every provider uses.
|
Package oauth holds what identity and its provider packages share: the shape of a sign-in as identity drives it, and the helpers every provider uses. |
|
oidc
Package oidc is the OpenID Connect a provider needs and no more: the issuer's discovery document, and the verification of its ID tokens against the keys the issuer publishes.
|
Package oidc is the OpenID Connect a provider needs and no more: the issuer's discovery document, and the verification of its ID tokens against the keys the issuer publishes. |
|
Package rbac is role-based access control for identity's users, on casbin: what each role may do, stored in the application's database and decided per request by Require.
|
Package rbac is role-based access control for identity's users, on casbin: what each role may do, stored in the application's database and decided per request by Require. |