Files
Docwell/Server/internal/auth/auth.go
T
tajniak81andClaude Opus 5.5 03f3434c10 Add organizations with cascading user rights
Same model as DriverVault, with organizations above workspaces:

- users get a role (user, admin, superadmin) and at most one
  organization; existing instance admins become superadmins
- rights cascade: superadmins own everything, org admins own their
  organization's workspaces, others get their workspace role
  (owner > admin > member > guest) while they stay in the org
- nobody grants a role above their own, acts on someone ranked above
  them, or changes their own role; rules live in internal/access as
  pure, tested functions
- self-service organizations: an org-less user creates one and becomes
  its admin; the last admin can delete it and is demoted
- endpoints for users, orgs, workspaces and members; token cache is
  dropped when a user's rights change
- admin panel: Users and Organizations pages scoped to the caller
- web app: organization page, workspace list, workspace settings with
  member management (EN/PL)
- fix: organization name missing after login/refresh, and stale tokens
  redirecting public pages to sign-in

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 22:53:11 +01:00

459 lines
14 KiB
Go

// Package auth implements Docwell sign-in on top of PocketBase's "users" auth
// collection. PocketBase stores the credentials and issues the tokens;
// docwell-server forwards the calls and adds Docwell rules (signup policy,
// disabled accounts, instance admins).
package auth
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"net/http"
"strings"
"sync"
"time"
"docwell/server/internal/access"
"docwell/server/internal/store/pocketbase"
)
const usersPath = "/api/collections/users"
var (
ErrInvalidCredentials = errors.New("invalid credentials")
ErrUnauthorized = errors.New("unauthorized")
ErrForbidden = errors.New("forbidden")
ErrAccountDisabled = errors.New("account disabled")
ErrSignupDisabled = errors.New("signup disabled")
ErrDomainNotAllowed = errors.New("email domain not allowed")
ErrInvalidToken = errors.New("invalid or expired token")
)
// MFARequiredError means the first factor passed; the client must finish
// with a second method (e.g. OTP) and send MFAID along.
type MFARequiredError struct{ MFAID string }
func (e *MFARequiredError) Error() string { return "mfa required" }
// ValidationError lists invalid input fields with a message per field.
type ValidationError struct{ Fields map[string]string }
func (e *ValidationError) Error() string { return fmt.Sprintf("validation failed: %v", e.Fields) }
// User is the public view of a Docwell account.
type User struct {
ID string `json:"id"`
Email string `json:"email"`
Name string `json:"name"`
Avatar string `json:"avatar"`
Locale string `json:"locale"`
Theme string `json:"theme"`
Status string `json:"status"`
Verified bool `json:"verified"`
Created string `json:"created"`
// Role is the instance role: user, admin (of their organization) or superadmin.
Role string `json:"role"`
// Organization is the id of the user's organization ("" = none).
Organization string `json:"organization"`
OrganizationName string `json:"organizationName"`
}
// Caller returns the identity the access rules decide for.
func (u User) Caller() access.Caller {
return access.Caller{ID: u.ID, Role: u.Role, OrgID: u.Organization}
}
// UserRecord is the PocketBase JSON shape of a "users" record (with the
// organization optionally expanded).
type UserRecord struct {
ID string `json:"id"`
Email string `json:"email"`
Name string `json:"name"`
Avatar string `json:"avatar"`
Locale string `json:"locale"`
Theme string `json:"theme"`
Status string `json:"status"`
Verified bool `json:"verified"`
Created string `json:"created"`
Role string `json:"role"`
Organization string `json:"organization"`
Expand struct {
Organization *struct {
Name string `json:"name"`
} `json:"organization"`
} `json:"expand"`
}
// User converts the record to the public view, filling defaults.
func (r UserRecord) User() User {
status := r.Status
if status == "" {
status = "active"
}
role, ok := access.NormalizeRole(r.Role)
if !ok {
role = access.RoleUser
}
u := User{
ID: r.ID, Email: r.Email, Name: r.Name, Avatar: r.Avatar, Locale: r.Locale, Theme: r.Theme,
Status: status, Verified: r.Verified, Created: r.Created, Role: role, Organization: r.Organization,
}
if r.Expand.Organization != nil {
u.OrganizationName = r.Expand.Organization.Name
}
return u
}
// Session is a signed-in user and their PocketBase auth token.
type Session struct {
Token string `json:"token"`
User User `json:"user"`
}
type authResponse struct {
Token string `json:"token"`
Record UserRecord `json:"record"`
}
// Methods lists the sign-in methods enabled in PocketBase.
type Methods struct {
Password bool `json:"password"`
OTP bool `json:"otp"`
MFA bool `json:"mfa"`
OAuth2 []string `json:"oauth2"`
Signup bool `json:"signup"`
}
type Options struct {
// SignupEnabled allows self-service signup. The first account can always
// sign up and becomes the instance admin.
SignupEnabled bool
// SignupDomains, if not empty, limits signup to these email domains.
SignupDomains []string
// CacheTTL is how long a verified token is trusted without asking
// PocketBase again.
CacheTTL time.Duration
}
type Service struct {
pb *pocketbase.Client
opts Options
now func() time.Time
mu sync.Mutex
cache map[[32]byte]cachedUser
}
type cachedUser struct {
user User
expires time.Time
}
// Forget drops cached token checks for a user, so a role change, move or
// deletion takes effect on their next request instead of after CacheTTL.
func (s *Service) Forget(userID string) {
s.mu.Lock()
defer s.mu.Unlock()
for k, c := range s.cache {
if c.user.ID == userID {
delete(s.cache, k)
}
}
}
func NewService(pb *pocketbase.Client, opts Options) *Service {
if opts.CacheTTL == 0 {
opts.CacheTTL = 30 * time.Second
}
return &Service{pb: pb, opts: opts, now: time.Now, cache: map[[32]byte]cachedUser{}}
}
// Login signs in with email and password. mfaID is set when finishing an
// MFA flow started by another method.
func (s *Service) Login(ctx context.Context, email, password, mfaID string) (Session, error) {
body := map[string]string{"identity": strings.TrimSpace(email), "password": password}
if mfaID != "" {
body["mfaId"] = mfaID
}
return s.authenticate(ctx, "/auth-with-password", body)
}
// RequestOTP emails a one-time code and returns the id to log in with.
func (s *Service) RequestOTP(ctx context.Context, email string) (string, error) {
var res struct {
OTPID string `json:"otpId"`
}
err := s.pb.DoAs(ctx, http.MethodPost, usersPath+"/request-otp", "", map[string]string{"email": strings.TrimSpace(email)}, &res)
return res.OTPID, mapError(err)
}
// LoginWithOTP signs in with a code sent by RequestOTP.
func (s *Service) LoginWithOTP(ctx context.Context, otpID, code, mfaID string) (Session, error) {
body := map[string]string{"otpId": otpID, "password": code}
if mfaID != "" {
body["mfaId"] = mfaID
}
return s.authenticate(ctx, "/auth-with-otp", body)
}
func (s *Service) authenticate(ctx context.Context, action string, body any) (Session, error) {
var res authResponse
err := s.pb.DoAs(ctx, http.MethodPost, usersPath+action, "", body, &res)
if err != nil {
var pbErr *pocketbase.Error
if errors.As(err, &pbErr) {
if pbErr.MFAID != "" {
return Session{}, &MFARequiredError{MFAID: pbErr.MFAID}
}
// PocketBase answers 400 "Failed to authenticate." for bad credentials.
if pbErr.Status == http.StatusBadRequest && len(pbErr.Data) == 0 {
return Session{}, ErrInvalidCredentials
}
// 403 means the credentials were right but the collection authRule
// (status != 'disabled') rejected the account.
if pbErr.Status == http.StatusForbidden {
return Session{}, ErrAccountDisabled
}
}
return Session{}, mapError(err)
}
return Session{Token: res.Token, User: s.withOrganization(ctx, res.Token, res.Record.User())}, nil
}
// withOrganization fills in the organization name. PocketBase applies the
// user's own access rules when expanding auth responses, and users cannot read
// the organizations collection, so the name comes from the token-check hook
// instead (which also warms the Verify cache).
func (s *Service) withOrganization(ctx context.Context, token string, u User) User {
if u.Organization == "" || u.OrganizationName != "" {
return u
}
if full, err := s.Verify(ctx, token); err == nil {
return full
}
return u
}
// SignupInput is a new account request.
type SignupInput struct {
Email string `json:"email"`
Password string `json:"password"`
Name string `json:"name"`
}
// Signup creates an account and signs it in. The first account on the
// instance becomes the superadmin.
func (s *Service) Signup(ctx context.Context, in SignupInput) (Session, error) {
in.Email = strings.TrimSpace(in.Email)
in.Name = strings.TrimSpace(in.Name)
fields := map[string]string{}
if in.Name == "" {
fields["name"] = "Name is required."
}
if len(in.Password) < 8 {
fields["password"] = "Password must be at least 8 characters."
}
if len(fields) > 0 {
return Session{}, &ValidationError{Fields: fields}
}
existing, err := pocketbase.List[UserRecord](ctx, s.pb, "users", pocketbase.ListOptions{PerPage: 1})
if err != nil {
return Session{}, err
}
first := existing.TotalItems == 0
// The first account runs the instance; everyone after starts as a plain
// user without an organization (they can create one or be invited).
role := access.RoleUser
if first {
role = access.RoleSuperadmin
}
if !first {
if !s.opts.SignupEnabled {
return Session{}, ErrSignupDisabled
}
if !s.domainAllowed(in.Email) {
return Session{}, ErrDomainNotAllowed
}
}
_, err = pocketbase.Create[UserRecord](ctx, s.pb, "users", map[string]any{
"email": in.Email,
"password": in.Password,
"passwordConfirm": in.Password,
"name": in.Name,
"status": "active",
"role": role,
"emailVisibility": false,
})
if err != nil {
return Session{}, mapError(err)
}
// Best effort: without SMTP configured PocketBase cannot send it.
_ = s.RequestVerification(ctx, in.Email)
return s.Login(ctx, in.Email, in.Password, "")
}
func (s *Service) domainAllowed(email string) bool {
if len(s.opts.SignupDomains) == 0 {
return true
}
at := strings.LastIndexByte(email, '@')
if at < 0 {
return false
}
domain := strings.ToLower(email[at+1:])
for _, d := range s.opts.SignupDomains {
if strings.EqualFold(d, domain) {
return true
}
}
return false
}
// Refresh exchanges a valid token for a new one.
func (s *Service) Refresh(ctx context.Context, token string) (Session, error) {
var res authResponse
if err := s.pb.DoAs(ctx, http.MethodPost, usersPath+"/auth-refresh", token, nil, &res); err != nil {
return Session{}, tokenError(err)
}
u := res.Record.User()
if u.Status == "disabled" {
return Session{}, ErrAccountDisabled
}
return Session{Token: res.Token, User: s.withOrganization(ctx, res.Token, u)}, nil
}
// Verify returns the user that owns token. Results are cached for CacheTTL.
func (s *Service) Verify(ctx context.Context, token string) (User, error) {
if token == "" {
return User{}, ErrUnauthorized
}
key := sha256.Sum256([]byte(token))
now := s.now()
s.mu.Lock()
if c, ok := s.cache[key]; ok && now.Before(c.expires) {
s.mu.Unlock()
return c.user, nil
}
s.mu.Unlock()
var rec UserRecord
if err := s.pb.DoAs(ctx, http.MethodGet, "/api/docwell/auth/verify", token, nil, &rec); err != nil {
return User{}, tokenError(err)
}
u := rec.User()
if u.Status == "disabled" {
return User{}, ErrAccountDisabled
}
s.mu.Lock()
if len(s.cache) > 10000 {
for k, c := range s.cache {
if now.After(c.expires) {
delete(s.cache, k)
}
}
}
s.cache[key] = cachedUser{user: u, expires: now.Add(s.opts.CacheTTL)}
s.mu.Unlock()
return u, nil
}
// Methods reports which sign-in methods are enabled.
func (s *Service) Methods(ctx context.Context) (Methods, error) {
var res struct {
Password struct{ Enabled bool } `json:"password"`
OTP struct{ Enabled bool } `json:"otp"`
MFA struct{ Enabled bool } `json:"mfa"`
OAuth2 struct {
Enabled bool
Providers []struct {
Name string `json:"name"`
} `json:"providers"`
} `json:"oauth2"`
}
if err := s.pb.DoAs(ctx, http.MethodGet, usersPath+"/auth-methods", "", nil, &res); err != nil {
return Methods{}, mapError(err)
}
m := Methods{Password: res.Password.Enabled, OTP: res.OTP.Enabled, MFA: res.MFA.Enabled, OAuth2: []string{}, Signup: s.opts.SignupEnabled}
if res.OAuth2.Enabled {
for _, p := range res.OAuth2.Providers {
m.OAuth2 = append(m.OAuth2, p.Name)
}
}
return m, nil
}
// RequestPasswordReset emails a reset link. It succeeds for unknown emails too.
func (s *Service) RequestPasswordReset(ctx context.Context, email string) error {
return mapError(s.pb.DoAs(ctx, http.MethodPost, usersPath+"/request-password-reset", "", map[string]string{"email": strings.TrimSpace(email)}, nil))
}
// ConfirmPasswordReset sets a new password using the emailed token.
func (s *Service) ConfirmPasswordReset(ctx context.Context, token, password string) error {
err := s.pb.DoAs(ctx, http.MethodPost, usersPath+"/confirm-password-reset", "",
map[string]string{"token": token, "password": password, "passwordConfirm": password}, nil)
return confirmError(err)
}
// RequestVerification emails an email-verification link.
func (s *Service) RequestVerification(ctx context.Context, email string) error {
return mapError(s.pb.DoAs(ctx, http.MethodPost, usersPath+"/request-verification", "", map[string]string{"email": strings.TrimSpace(email)}, nil))
}
// ConfirmVerification marks the email as verified using the emailed token.
func (s *Service) ConfirmVerification(ctx context.Context, token string) error {
err := s.pb.DoAs(ctx, http.MethodPost, usersPath+"/confirm-verification", "", map[string]string{"token": token}, nil)
return confirmError(err)
}
func tokenError(err error) error {
var pbErr *pocketbase.Error
if errors.As(err, &pbErr) && (pbErr.Status == http.StatusUnauthorized || pbErr.Status == http.StatusForbidden || pbErr.Status == http.StatusNotFound) {
return ErrUnauthorized
}
return err
}
func confirmError(err error) error {
var pbErr *pocketbase.Error
if errors.As(err, &pbErr) && pbErr.Status == http.StatusBadRequest {
if _, ok := pbErr.Data["token"]; ok {
return ErrInvalidToken
}
}
return mapError(err)
}
// mapError turns PocketBase validation errors into ValidationError.
func mapError(err error) error {
var pbErr *pocketbase.Error
if errors.As(err, &pbErr) && pbErr.Status == http.StatusBadRequest && len(pbErr.Data) > 0 {
fields := make(map[string]string, len(pbErr.Data))
for k, v := range pbErr.Data {
if k == "passwordConfirm" {
continue
}
fields[k] = v.Message
}
return &ValidationError{Fields: fields}
}
return err
}
// BearerToken extracts the token from an "Authorization: Bearer ..." header.
func BearerToken(r *http.Request) string {
h := r.Header.Get("Authorization")
if t, ok := strings.CutPrefix(h, "Bearer "); ok {
return strings.TrimSpace(t)
}
return ""
}