Phase 0 foundation for Docwell, an open-source knowledge base: - Database: PocketBase v0.40.6 with initial schema migrations; users is the built-in auth collection, plus a hook for token checks and env-driven app URL/SMTP settings - Server: Go API (health, version, auth endpoints forwarded to PocketBase, admin user list) with an embedded Vue admin panel - Web-App: Go static server and Vue/Tailwind app with Tiptap editor, sign-in, sign-up, password reset and email verification (EN/PL) - Desktop-App: Wails v3 host reusing the web app - Phone-App: Flutter app with sign-in - Shared packages (editor, ui, api-client), OpenAPI spec, Docker compose (separate services and all-in-one), GitHub Actions CI - Docs: feature inventory and architecture/build plan Licensed under AGPL-3.0-or-later. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
445 lines
13 KiB
Go
445 lines
13 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/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"`
|
|
IsAdmin bool `json:"isAdmin"`
|
|
Verified bool `json:"verified"`
|
|
Created string `json:"created"`
|
|
}
|
|
|
|
// userRecord is the PocketBase JSON shape of a "users" record.
|
|
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"`
|
|
IsAdmin bool `json:"is_admin"`
|
|
Verified bool `json:"verified"`
|
|
Created string `json:"created"`
|
|
}
|
|
|
|
func (r userRecord) user() User {
|
|
status := r.Status
|
|
if status == "" {
|
|
status = "active"
|
|
}
|
|
return User{
|
|
ID: r.ID, Email: r.Email, Name: r.Name, Avatar: r.Avatar, Locale: r.Locale, Theme: r.Theme,
|
|
Status: status, IsAdmin: r.IsAdmin, Verified: r.Verified, Created: r.Created,
|
|
}
|
|
}
|
|
|
|
// 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
|
|
}
|
|
|
|
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: res.Record.user()}, nil
|
|
}
|
|
|
|
// 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 admin.
|
|
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
|
|
|
|
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",
|
|
"is_admin": first,
|
|
"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: 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)
|
|
}
|
|
|
|
// ListUsersInput filters the admin user list.
|
|
type ListUsersInput struct {
|
|
Page int
|
|
PerPage int
|
|
Search string
|
|
}
|
|
|
|
type UserList struct {
|
|
Items []User `json:"items"`
|
|
Page int `json:"page"`
|
|
PerPage int `json:"perPage"`
|
|
TotalItems int `json:"totalItems"`
|
|
}
|
|
|
|
// ListUsers returns accounts for the admin panel.
|
|
func (s *Service) ListUsers(ctx context.Context, in ListUsersInput) (UserList, error) {
|
|
opts := pocketbase.ListOptions{Page: in.Page, PerPage: in.PerPage, Sort: "-created"}
|
|
if q := sanitizeFilterValue(in.Search); q != "" {
|
|
opts.Filter = fmt.Sprintf("email ~ '%s' || name ~ '%s'", q, q)
|
|
}
|
|
res, err := pocketbase.List[userRecord](ctx, s.pb, "users", opts)
|
|
if err != nil {
|
|
return UserList{}, err
|
|
}
|
|
out := UserList{Items: make([]User, 0, len(res.Items)), Page: res.Page, PerPage: res.PerPage, TotalItems: res.TotalItems}
|
|
for _, r := range res.Items {
|
|
out.Items = append(out.Items, r.user())
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// sanitizeFilterValue keeps search text from breaking out of a PocketBase
|
|
// filter string literal.
|
|
func sanitizeFilterValue(s string) string {
|
|
s = strings.TrimSpace(s)
|
|
return strings.Map(func(r rune) rune {
|
|
switch r {
|
|
case '\'', '"', '\\', '`':
|
|
return -1
|
|
}
|
|
return r
|
|
}, s)
|
|
}
|
|
|
|
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 ""
|
|
}
|