auth

package
v2.15.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrTooManySettings = errors.New("too many settings")

ErrTooManySettings: the change would leave the user more keys than allowed.

Functions

func AuditMiddleware added in v2.14.0

func AuditMiddleware(store *UserStore, authMiddleware func(http.Handler) http.Handler) func(http.Handler) http.Handler

AuditMiddleware wraps an auth middleware so every non-GET request on a protected route (clears, deletes, settings, mocks…) is written to the audit log with the user, the route and the answer's status.

func DefaultScopes added in v2.14.0

func DefaultScopes(provider string) string

DefaultScopes returns the scopes to ask for when none are configured. GitHub is not OIDC: its scopes for the profile and the email list are read:user and user:email.

func LoginURL

func LoginURL() string

LoginURL returns the SSO login URL path. The frontend getter prepends REST_API_URL + "/" before this value.

func Middleware

func Middleware(tokens *TokenStore, enabled bool) func(http.Handler) http.Handler

Middleware checks the X-Auth-Token header and injects the user into context. When auth is enabled, requests without a valid token get 401. When auth is disabled, this middleware is a no-op.

func PruneLoop added in v2.14.0

func PruneLoop(store *UserStore, done <-chan struct{})

PruneLoop deletes audit entries older than 90 days and closed sessions, now and then once a day, until done is closed.

func SplitScopes

func SplitScopes(scopes string) []string

SplitScopes splits a comma-separated scopes string.

Types

type AccessPolicy added in v2.14.0

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

AccessPolicy decides who may sign in after the provider's login. Empty lists let in everyone the provider lets in.

func NewAccessPolicy added in v2.14.0

func NewAccessPolicy(emails, domains []string) AccessPolicy

NewAccessPolicy builds a policy from allowed emails and domains (case-insensitive; a leading "@" on a domain is ignored).

func (AccessPolicy) Allows added in v2.14.0

func (p AccessPolicy) Allows(u User) bool

Allows reports whether the user may sign in. With a list set, the email must be verified by the provider. A domain matches Google's `hd` claim (the Workspace the account belongs to) for provider google, the domain of the verified email for the others.

func (AccessPolicy) Restricted added in v2.14.0

func (p AccessPolicy) Restricted() bool

Restricted reports whether any allow-list is set.

type AuditEntry added in v2.14.0

type AuditEntry struct {
	ID        int64  `json:"id"`
	At        string `json:"at"`
	UserID    string `json:"user_id"`
	UserLabel string `json:"user"`
	Action    string `json:"action"`
	Target    string `json:"target"`
	Status    int    `json:"status"`
	IP        string `json:"ip"`
}

AuditEntry is one row of the audit log.

type Handlers

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

Handlers provides HTTP handlers for the auth flow.

func NewHandlers

func NewHandlers(oauth oauthProvider, tokens *TokenStore, access AccessPolicy) *Handlers

NewHandlers creates auth HTTP handlers. access limits who may sign in; an empty policy lets in everyone the provider lets in.

func (*Handlers) RegisterProtectedRoutes

func (h *Handlers) RegisterProtectedRoutes(mux *http.ServeMux, authMiddleware func(http.Handler) http.Handler)

RegisterProtectedRoutes registers routes that need auth middleware.

func (*Handlers) RegisterRoutes

func (h *Handlers) RegisterRoutes(mux *http.ServeMux)

RegisterRoutes registers auth endpoints on the mux. These routes are public (no auth middleware).

func (*Handlers) SetOnLogout added in v2.14.0

func (h *Handlers) SetOnLogout(f func())

SetOnLogout sets a function run after a logout revoked a session, e.g. closing the WebSocket connections whose token stopped working.

func (*Handlers) SetStore added in v2.14.0

func (h *Handlers) SetStore(store *UserStore, admins []string)

SetStore turns on users, server-side sessions (real Logout), per-user settings and the audit log. admins are the emails that may read the audit log; none: every signed-in user.

type OAuthClient

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

OAuthClient wraps an oauth2.Config and provider-specific user mapping.

func NewOAuthClient

func NewOAuthClient(provider, providerURL, clientID, clientSecret, callbackURL, scopes string) (*OAuthClient, error)

NewOAuthClient builds an OAuthClient from auth configuration. For OIDC-compatible providers it attempts discovery via .well-known/openid-configuration. For GitHub it uses hardcoded endpoints.

func (*OAuthClient) AuthCodeURL

func (c *OAuthClient) AuthCodeURL(state string) string

AuthCodeURL returns the URL to redirect the user to for authorization.

func (*OAuthClient) Exchange

func (c *OAuthClient) Exchange(code string) (*User, error)

Exchange trades an authorization code for tokens and fetches user info.

type ProviderEndpoints

type ProviderEndpoints struct {
	AuthURL     string
	TokenURL    string
	UserInfoURL string
	// EmailsURL lists the user's emails with their verified flag (GitHub).
	EmailsURL string
	// Issuer is the OIDC issuer from discovery; empty for GitHub.
	Issuer string
}

ProviderEndpoints holds OAuth2 endpoint URLs and user info URL.

type SessionChecker added in v2.14.0

type SessionChecker interface {
	SessionValid(sessionID string) bool
}

SessionChecker reports whether a server-side session is still open.

type TokenClaims

type TokenClaims struct {
	jwt.RegisteredClaims
	Provider string `json:"provider"`
	Username string `json:"username"`
	Email    string `json:"email"`
	Avatar   string `json:"avatar"`
	// EmailVerified and HostedDomain let the access policy re-check a token,
	// so an allow-list set later also cuts sessions issued before it.
	EmailVerified bool   `json:"email_verified,omitempty"`
	HostedDomain  string `json:"hd,omitempty"`
	// UserID and SessionID tie the token to a users row and a sessions row;
	// a revoked session (Logout) makes the token invalid.
	UserID    string `json:"uid,omitempty"`
	SessionID string `json:"sid,omitempty"`
}

TokenClaims are the JWT claims stored in internal tokens.

type TokenStore

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

TokenStore creates and validates internal JWT tokens.

func NewTokenStore

func NewTokenStore(secret string) *TokenStore

NewTokenStore creates a new TokenStore with the given HMAC secret.

func (*TokenStore) Create

func (s *TokenStore) Create(u User) (string, error)

Create issues a new JWT token for the given user.

func (*TokenStore) ExpiresAt

func (s *TokenStore) ExpiresAt(tokenStr string) (time.Time, error)

ExpiresAt validates a token and returns when it expires (zero: never).

func (*TokenStore) SetAccess added in v2.14.0

func (s *TokenStore) SetAccess(p AccessPolicy)

SetAccess makes every token check also apply the sign-in policy: a token whose user the policy refuses is invalid (HTTP API and WebSocket alike).

func (*TokenStore) SetSessions added in v2.14.0

func (s *TokenStore) SetSessions(c SessionChecker)

SetSessions makes every token check also require an open server-side session: tokens without one (issued before sessions existed) or with a revoked or expired one are invalid.

func (*TokenStore) Validate

func (s *TokenStore) Validate(tokenStr string) (*User, error)

Validate parses and validates a JWT token string, returning the user.

type User

type User struct {
	Provider string `json:"provider"`
	Username string `json:"username"`
	Email    string `json:"email"`
	Avatar   string `json:"avatar"`

	// EmailVerified is true when the provider confirms the user owns Email.
	EmailVerified bool `json:"-"`
	// HostedDomain is Google's `hd` claim: the Workspace domain of the account.
	HostedDomain string `json:"-"`
	// Subject is the OIDC `sub` claim, used to match the ID token to userinfo.
	Subject string `json:"-"`
	// ID is the users table id and SessionID the server-side session of the
	// token; both empty for a guest and for a token issued before sessions.
	ID        string `json:"-"`
	SessionID string `json:"-"`
	// contains filtered or unexported fields
}

User represents an authenticated user.

func GuestUser

func GuestUser() User

GuestUser returns the default guest user when auth is disabled.

func UserFromContext

func UserFromContext(ctx context.Context) *User

UserFromContext extracts the authenticated user from the request context.

type UserStore added in v2.14.0

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

UserStore keeps signed-in users, their sessions, their settings and the audit log in the server's database (tables from migration 000044).

func NewUserStore added in v2.14.0

func NewUserStore(db *sql.DB) *UserStore

NewUserStore returns a store over db; the tables must exist.

func (*UserStore) CreateSession added in v2.14.0

func (s *UserStore) CreateSession(userID, userAgent, ip string, exp time.Time) (string, error)

CreateSession opens a session for the user until exp and returns its id.

func (*UserStore) ListAudit added in v2.14.0

func (s *UserStore) ListAudit(limit int, before int64) ([]AuditEntry, error)

ListAudit returns up to limit entries (see auditLimit), newest first; before > 0 lists entries older than that id (the next page).

func (*UserStore) Prune added in v2.14.0

func (s *UserStore) Prune(auditBefore, sessionsBefore time.Time) error

Prune deletes audit entries older than auditBefore and sessions that expired or were revoked before sessionsBefore.

func (*UserStore) PutSettings added in v2.14.0

func (s *UserStore) PutSettings(userID string, values map[string]json.RawMessage, maxKeys int) error

PutSettings merges values into the user's settings; a JSON null removes the key. With maxKeys > 0 a change that would leave more keys is refused (ErrTooManySettings), checked in the same transaction.

func (*UserStore) Record added in v2.14.0

func (s *UserStore) Record(e AuditEntry) error

Record appends an entry to the audit log (At is set when empty).

func (*UserStore) Revoke added in v2.14.0

func (s *UserStore) Revoke(sessionID string) error

Revoke ends a session; its token stops working at once.

func (*UserStore) SessionValid added in v2.14.0

func (s *UserStore) SessionValid(sessionID string) bool

SessionValid reports whether the session exists, is not revoked and has not expired.

func (*UserStore) Settings added in v2.14.0

func (s *UserStore) Settings(userID string) (map[string]json.RawMessage, error)

Settings returns the user's stored settings, key → JSON value.

func (*UserStore) Upsert added in v2.14.0

func (s *UserStore) Upsert(u User) (string, error)

Upsert saves the provider's user (matched by provider and subject) and returns its id. Profile fields follow the provider on every sign-in.

Jump to

Keyboard shortcuts

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