login

package
v1.16.0 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrEmailExists = errors.New("a user with that email already exists")

ErrEmailExists is returned by CreateUserWithPassword when a user with the requested email already exists. Admin-initiated creation must fail loudly on a duplicate rather than silently overwrite the existing row (which is what UpsertUser does for the SSO/OAuth login path).

View Source
var ErrHiddenLimit = errors.New("hide limit reached")

ErrHiddenLimit is returned by SetConnectorHidden when the user already hides entity.MaxHiddenConnectors instances that still exist.

View Source
var ErrInvalidCredentials = errors.New("invalid email or password")

Functions

func GeneratePassphrase added in v0.8.9

func GeneratePassphrase() string

GeneratePassphrase returns five dash-separated CVCVC pseudo-words drawn from crypto/rand. Each word is 5 chars, total 29 chars; entropy ≈ 5 words × log2(17²·5²·17) ≈ 78 bits — plenty for an initial admin password and easier to read aloud than a bare base32 string.

Example: "tokel-bavri-zenpu-makdo-flite"

func GetUser

func GetUser(ctx context.Context) *entity.User

GetUser retrieves the authenticated user from context. Returns nil if not logged in.

func GetUserTagIDs

func GetUserTagIDs(ctx context.Context) []string

GetUserTagIDs retrieves the filter tag IDs for the authenticated user from context. Populated by the Session middleware from the encrypted cookie.

func ImpersonatorCookieNameForTest added in v1.0.0

func ImpersonatorCookieNameForTest() string

ImpersonatorCookieNameForTest exposes the local copy so internal/admin can pin it against its own constant (that package imports this one, so the check cannot live on the other side).

func IsScopedPrincipal added in v1.2.9

func IsScopedPrincipal(ctx context.Context) bool

IsScopedPrincipal reports whether this request's principal arrived with an already-narrowed reach, and must therefore NOT be widened by ownership.

func MachineCaller added in v1.16.0

func MachineCaller(ctx context.Context) (string, bool)

MachineCaller returns the label WithMachineCaller set, if any.

func SetAfterLoginRedirect added in v0.4.0

func SetAfterLoginRedirect(w http.ResponseWriter, r *http.Request, path string)

SetAfterLoginRedirect stores a path the next successful login should land on, instead of "/". Paths must start with "/" and not "//". Used by /oauth/authorize when the user isn't logged in yet.

func WithMachineCaller added in v1.16.0

func WithMachineCaller(ctx context.Context, label string) context.Context

WithMachineCaller marks a request made in-process by a machine on a user's behalf — today a plugin calling wick's REST API through the Host API ("plugin:<key>"). Surfaces that treat token requests differently from the browser UI (the per-project ticket REST toggle, the "api" actor on webhooks) treat this mark like a bearer token. Only server code can set it: it lives on the context, never in a header.

func WithScopedUser added in v1.2.9

func WithScopedUser(ctx context.Context, user *entity.User, tagIDs []string) context.Context

WithScopedUser is WithUser for a principal whose reach was deliberately NARROWED before it got here — today that means a sub-agent token, whose tag slice is already the intersection of its triggering user's tags with its profile's allow list.

The distinction matters because tags are not the only way to reach a row: a row's creator reaches it by ownership too (see connectors.OwnsConnector). For the human who is chatting that is right — it is their own row. For a sub-agent it is not: the child would inherit every row its parent ever created regardless of the profile's allow list, which is precisely what the narrowing exists to prevent.

So ownership-based access asks IsScopedPrincipal first. Absent marker = unscoped, which keeps every pre-existing caller behaving as before.

func WithUser added in v0.4.0

func WithUser(ctx context.Context, user *entity.User, tagIDs []string) context.Context

WithUser stamps a user + filter-tag-ID set onto the context using the same keys the cookie-session middleware does. Useful for non-cookie auth paths (MCP bearer middleware, OAuth) that need downstream code (`login.GetUser`, `login.GetUserTagIDs`, `Service.CanAccessTool`) to behave identically.

Types

type Handler

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

func NewHandler

func NewHandler(svc *Service, midd *Middleware, ssoSvc *sso.Service, cfg appConfig) *Handler

NewHandler wires the login routes. The handler reads SSO config from the sso.Service on every request so admin edits take effect without a restart.

func (*Handler) Register

func (h *Handler) Register(mux *http.ServeMux, sessionMidd *Middleware)

type Middleware

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

func NewMiddleware

func NewMiddleware(svc *Service, secrets SecretProvider) *Middleware

func (*Middleware) ClearSessionCookie

func (m *Middleware) ClearSessionCookie(w http.ResponseWriter)

ClearSessionCookie wipes the session cookie.

func (*Middleware) RequireAdmin

func (m *Middleware) RequireAdmin(next http.Handler) http.Handler

RequireAdmin returns 403 if the user is not an admin.

func (*Middleware) RequireAuth

func (m *Middleware) RequireAuth(next http.Handler) http.Handler

RequireAuth redirects to /auth/login if there is no authenticated, approved user.

First-login enforcement: admins land on /profile/setup until they rotate the auto-generated password (admin_password_changed=false). The setup form itself + POST endpoint are exempt so the user can actually complete the flow.

func (*Middleware) RequireJobAccess

func (m *Middleware) RequireJobAccess(next http.Handler) http.Handler

RequireJobAccess enforces per-job visibility on /jobs/{key} requests. It reuses the ToolPermission table (stored under "/jobs/{key}") and CanAccessTool logic. Session + RequireAuth must have run first.

func (*Middleware) RequireToolAccess

func (m *Middleware) RequireToolAccess(tools []ToolMeta) func(http.Handler) http.Handler

RequireToolAccess enforces per-tool visibility on requests under /tools/. For each request it finds the tool whose Path is the longest prefix of the request URL, then calls Service.CanAccessTool. Public tools let anyone through; Private tools require an approved login, plus a matching tag when the tool has required tags set. Session must have already populated the user in context.

func (*Middleware) Session

func (m *Middleware) Session(next http.Handler) http.Handler

Session decrypts the AES-GCM session cookie and populates the user and their filter tag IDs into the request context. Tampered or expired cookies are wiped. For guests (no session), it reads the guest theme cookie.

func (*Middleware) SetSessionCookie

func (m *Middleware) SetSessionCookie(w http.ResponseWriter, userID string, tagIDs []string, secure bool)

SetSessionCookie encrypts {userID, tagIDs} with AES-256-GCM and writes the result as an HttpOnly cookie. Callers should fetch filter tag IDs via svc.GetUserFilterTagIDs before calling this.

type SecretProvider

type SecretProvider interface {
	SessionSecret() string
	AdminPasswordChanged() bool
}

SecretProvider is the minimal interface Middleware needs to read the current session-signing secret + first-login state. configs.Service satisfies it.

type Service

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

func NewService

func NewService(db *gorm.DB, adminEmailsCSV string) *Service

func (*Service) AdminCreateUser added in v0.16.0

func (s *Service) AdminCreateUser(ctx context.Context, email, name string) (*entity.User, string, error)

AdminCreateUser provisions a new, already-approved user from the admin panel and returns the generated password in plaintext. The password is a server-side 5-word passphrase (same generator as the first-boot admin seed); only its bcrypt hash is stored, so this return value is the single time the plaintext is recoverable. The caller is responsible for surfacing it to the admin exactly once.

Returns ErrEmailExists when the email already belongs to a user.

func (*Service) BootstrapAdmin

func (s *Service) BootstrapAdmin(ctx context.Context, defaultPassword string, alreadyChanged bool) (generated string)

BootstrapAdmin seeds (or re-seeds) the default admin password while admin_password_changed is still false. Two cases:

  • No admin yet → create one per configured admin email and set the password.
  • Admin exists but flag is false → reset the password (the operator never completed first-login setup, so whatever hash is on disk is either "admin" or another stale auto-generated value the operator no longer has).

Once admin_password_changed=true, this function is a no-op so a live rotated password is never overwritten on boot.

If defaultPassword is empty, a 5-word passphrase is generated and returned so callers can surface it (logs, tray, INITIAL_CREDENTIALS file). The returned password is "" when nothing changed — either setup is already done or the explicit defaultPassword was used (and the caller already knows it from env).

func (*Service) CanAccessOpenTaggedResource added in v1.16.0

func (s *Service) CanAccessOpenTaggedResource(ctx context.Context, user *entity.User, resourcePath string) bool

CanAccessOpenTaggedResource answers the tag question for a resource that is open to everyone until tagged — a provider instance, keyed by a tool_tags path like "/providers/claude/work". Untagged = any approved user; tagged = the user must carry one of the tags.

Unlike CanAccessTool it has NO admin bypass: the caller decides whether the admin role walks past tags (an admin_see_all_* knob), and a bypass hidden in here would make turning that knob off do nothing.

func (*Service) CanAccessSharedResource added in v0.33.0

func (s *Service) CanAccessSharedResource(ctx context.Context, user *entity.User, resourcePath string) bool

CanAccessSharedResource reports whether a non-owner may reach a resource that an admin shares purely by filter tag — a project or data table, keyed by a tool_tags path like "/projects/<id>" or "/data-tables/<slug>".

It differs from CanAccessTool on the untagged case, and that difference is the whole point. A tool with no filter tags is open to everyone ("untagged = public"); a project/data table with no filter tags is NOT — it stays private to its owner (+ admins), reachable by others ONLY through an explicit tag grant. Callers pass owner/admin access separately; this answers just the tag-share question, so an untagged resource returns false here instead of leaking to every authenticated user.

func (*Service) CanAccessTool

func (s *Service) CanAccessTool(ctx context.Context, user *entity.User, toolPath string, defaultVis entity.ToolVisibility) bool

func (*Service) FindUserIDByEmail added in v1.0.0

func (s *Service) FindUserIDByEmail(ctx context.Context, email string) (string, bool)

FindUserIDByEmail resolves an email to a wick user id. Used by chat channels to decide whose identity a channel-started session runs as.

func (*Service) FirstAdmin added in v0.6.4

func (s *Service) FirstAdmin(ctx context.Context) (*entity.User, error)

FirstAdmin returns the oldest admin user, or nil when no admin exists. Stdio MCP uses this to bind its synthetic context to a real admin so wick_enc_ tokens minted from MCP can be decrypted by that admin in the web UI (per-user keys are HKDF-salted with user.ID).

func (*Service) GetUserByEmail added in v1.2.9

func (s *Service) GetUserByEmail(ctx context.Context, email string) (*entity.User, error)

GetUserByEmail resolves an account by its email. The Source panel uses it to put a face on a commit: git records an author email, and when that email belongs to a wick account the panel can show that account's avatar instead of inventing one.

func (*Service) GetUserByID

func (s *Service) GetUserByID(ctx context.Context, id string) (*entity.User, error)

func (*Service) GetUserFilterTagIDs

func (s *Service) GetUserFilterTagIDs(ctx context.Context, userID string) []string

GetUserFilterTagIDs fetches the filter-type tag IDs for a user. Called at login time; the result is embedded in the encrypted session cookie so subsequent requests do not need an extra DB query for tag matching.

func (*Service) GetUsersByIDs added in v1.16.0

func (s *Service) GetUsersByIDs(ctx context.Context, ids []string) ([]*entity.User, error)

GetUsersByIDs resolves many accounts in a single query — for lists that put a name on each row, where one lookup per id would cost a DB round trip apiece.

func (*Service) ListApprovedAdmins added in v1.0.0

func (s *Service) ListApprovedAdmins(ctx context.Context) ([]*entity.User, error)

ListApprovedAdmins returns the admins who may be notified about account events. Both filters matter: unapproved accounts must not receive notices about a pending registration (they have not been vetted themselves), and non-admins cannot act on one.

IsOwner counts as admin, matching entity.User.IsAdmin.

func (*Service) LoginWithPassword

func (s *Service) LoginWithPassword(ctx context.Context, email, password string) (*entity.User, error)

func (*Service) RecordLogin added in v1.2.9

func (s *Service) RecordLogin(ctx context.Context, userID string)

RecordLogin notes that userID signed in, for the admin analytics. Never blocks, never fails the caller: a sign-in is the user's, the record is ours.

func (*Service) RegisterChannelUser added in v1.0.0

func (s *Service) RegisterChannelUser(ctx context.Context, email, name, source string) (string, error)

RegisterChannelUser creates an unapproved account for an identity that arrived over a chat channel, and returns its id.

The account cannot act until an admin approves it. A channel reports an email address; it does not prove the sender controls it, so approval is where that judgement is made. See repo.CreateChannelUser for why this never grants admin.

func (*Service) SetAutoDeleteEmptyTickets added in v0.40.0

func (s *Service) SetAutoDeleteEmptyTickets(ctx context.Context, userID, choice string) error

SetAutoDeleteEmptyTickets records the user's standing answer to "delete this ticket now that its last chat left?". Only the empty case: deleting a ticket that still holds chats always asks, because that one takes conversations with it.

func (*Service) SetConnectorHidden added in v1.16.0

func (s *Service) SetConnectorHidden(ctx context.Context, userID, connectorID string, hidden bool, exists func(id string) bool) ([]string, error)

SetConnectorHidden hides (hidden=true) or unhides one connector instance for this user only, and returns the hidden list as saved. Idempotent: hiding an already hidden id or unhiding an unknown one just returns the list. Unhide never checks the id, so a deleted instance can still be cleared.

exists, when non-nil, reports whether an instance still exists; ids it rejects are pruned when a hide would hit the cap, before ErrHiddenLimit is decided. It is called before the write transaction, never inside it, so it may query the database freely.

The write goes through repo.UpdateMetadata, so quick hide clicks or a second tab cannot drop each other's ids.

func (*Service) SetEmail added in v0.8.9

func (s *Service) SetEmail(ctx context.Context, userID, newEmail string) error

SetEmail updates the user's email address. Used by the first-login setup flow so admins can rename the seed account (admin@admin.com) to a real address. Returns ErrEmailTaken when the new email already belongs to a different user.

func (*Service) SetHomeView

func (s *Service) SetHomeView(ctx context.Context, userID, view string) error

SetHomeView updates the user's home-grid view preference.

func (*Service) SetPassword

func (s *Service) SetPassword(ctx context.Context, userID, currentPassword, newPassword string) error

func (*Service) SetPinnedAgentProject added in v0.14.21

func (s *Service) SetPinnedAgentProject(ctx context.Context, userID, projectID string) error

SetPinnedAgentProject sets (or clears, when projectID is empty) the user's pinned agents Project — their personal default. One per user.

func (*Service) SetPushPermission added in v0.15.0

func (s *Service) SetPushPermission(ctx context.Context, userID, permission string) error

func (*Service) SetRailLabels added in v1.16.0

func (s *Service) SetRailLabels(ctx context.Context, userID string, on bool) error

SetRailLabels saves whether the conversation rail prints tab names along the strip (true) or shows icons only (false). Both are stored explicitly, so the choice survives a later change of default. The layout is left alone.

func (*Service) SetRailPrefs added in v0.40.0

func (s *Service) SetRailPrefs(ctx context.Context, userID string, p entity.RailPrefs) error

SetRailPrefs saves the user's conversation-rail layout. Stored as given: both lists are tab ids, and the client owns which ids exist — a server that filtered them would drop a tab added by a newer client and silently undo the layout that client had just saved. Labels is kept as it was; the profile owns it (see SetRailLabels).

func (*Service) SetSidebarWidth added in v1.2.9

func (s *Service) SetSidebarWidth(ctx context.Context, userID, space string, width int) error

SetSidebarWidth saves how wide the user dragged the "team" or "agents" sidebar. width 0 resets it to the page default; others are clamped.

func (*Service) SetTheme

func (s *Service) SetTheme(ctx context.Context, userID, themeID string) error

SetTheme updates the user's UI theme preference. Empty id means "no preference" and the UI falls back to the device system setting.

func (*Service) SetTicketFilter added in v0.40.0

func (s *Service) SetTicketFilter(ctx context.Context, userID, projectID string, f entity.TicketFilter) error

SetTicketFilter saves the user's ticket-board filter for one project. A zero-value filter removes the entry so the metadata bag doesn't accumulate empty objects for every project ever visited.

func (*Service) SetUIScale added in v1.2.9

func (s *Service) SetUIScale(ctx context.Context, userID string, pct int) error

SetUIScale saves the user's interface size; an invalid value stores the default.

func (*Service) UpsertUser

func (s *Service) UpsertUser(ctx context.Context, email, name, avatar string) (*entity.User, error)

type ToolMeta

type ToolMeta struct {
	Path              string
	DefaultVisibility entity.ToolVisibility
}

ToolMeta is the minimal info RequireToolAccess needs about each tool. Declared here so the login package doesn't import ui (avoids a cycle).

Directories

Path Synopsis
templ: version: v0.3.1020
templ: version: v0.3.1020

Jump to

Keyboard shortcuts

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