remove preact and create setup wizard
This commit is contained in:
@@ -100,6 +100,93 @@ func (r *Repository) CountAdmins(ctx context.Context) (int, error) {
|
||||
return count, nil
|
||||
}
|
||||
|
||||
func (r *Repository) GetInstanceSettings(ctx context.Context) (InstanceSettings, error) {
|
||||
var setupCompleted string
|
||||
var signupsEnabled int
|
||||
if err := r.db.QueryRowContext(ctx, `
|
||||
SELECT COALESCE(setup_completed_at, ''), signups_enabled
|
||||
FROM instance_settings
|
||||
WHERE id = 1
|
||||
`).Scan(&setupCompleted, &signupsEnabled); err != nil {
|
||||
return InstanceSettings{}, fmt.Errorf("get instance settings: %w", err)
|
||||
}
|
||||
return InstanceSettings{
|
||||
SetupComplete: setupCompleted != "",
|
||||
SignupsEnabled: signupsEnabled == 1,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *Repository) CompleteInitialSetup(ctx context.Context, user User, signupsEnabled bool) (User, error) {
|
||||
now := time.Now().UTC()
|
||||
if user.ID == "" {
|
||||
user.ID = "user:" + user.Email
|
||||
}
|
||||
if user.DisplayName == "" {
|
||||
user.DisplayName = user.Email
|
||||
}
|
||||
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return User{}, fmt.Errorf("begin initial setup: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
var setupCompleted string
|
||||
if err := tx.QueryRowContext(ctx, `
|
||||
SELECT COALESCE(setup_completed_at, '')
|
||||
FROM instance_settings
|
||||
WHERE id = 1
|
||||
`).Scan(&setupCompleted); err != nil {
|
||||
return User{}, fmt.Errorf("get initial setup state: %w", err)
|
||||
}
|
||||
if setupCompleted != "" {
|
||||
return User{}, fmt.Errorf("initial setup has already been completed")
|
||||
}
|
||||
|
||||
var userCount int
|
||||
if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM users`).Scan(&userCount); err != nil {
|
||||
return User{}, fmt.Errorf("count users during initial setup: %w", err)
|
||||
}
|
||||
if userCount != 0 {
|
||||
return User{}, fmt.Errorf("initial setup requires an empty user database")
|
||||
}
|
||||
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO users (id, email, display_name, password_hash, role, created_at, last_seen_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
`, user.ID, user.Email, user.DisplayName, nullString(user.PasswordHash), string(RoleAdmin), now.Format(time.RFC3339), now.Format(time.RFC3339)); err != nil {
|
||||
return User{}, fmt.Errorf("create initial admin: %w", err)
|
||||
}
|
||||
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
UPDATE instance_settings
|
||||
SET setup_completed_at = ?, signups_enabled = ?, updated_at = ?
|
||||
WHERE id = 1 AND setup_completed_at IS NULL
|
||||
`, now.Format(time.RFC3339), boolInt(signupsEnabled), now.Format(time.RFC3339)); err != nil {
|
||||
return User{}, fmt.Errorf("complete initial setup: %w", err)
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
return User{}, fmt.Errorf("commit initial setup: %w", err)
|
||||
}
|
||||
return r.GetUserByEmail(ctx, user.Email)
|
||||
}
|
||||
|
||||
func (r *Repository) UpdateSignupsEnabled(ctx context.Context, enabled bool) error {
|
||||
result, err := r.db.ExecContext(ctx, `
|
||||
UPDATE instance_settings
|
||||
SET signups_enabled = ?, updated_at = ?
|
||||
WHERE id = 1 AND setup_completed_at IS NOT NULL
|
||||
`, boolInt(enabled), time.Now().UTC().Format(time.RFC3339))
|
||||
if err != nil {
|
||||
return fmt.Errorf("update signup setting: %w", err)
|
||||
}
|
||||
if rows, _ := result.RowsAffected(); rows == 0 {
|
||||
return fmt.Errorf("initial setup is required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) ListUsers(ctx context.Context) ([]User, error) {
|
||||
rows, err := r.db.QueryContext(ctx, `
|
||||
SELECT id, email, COALESCE(display_name, ''), COALESCE(password_hash, ''), COALESCE(role, 'viewer'), created_at, COALESCE(last_seen_at, '')
|
||||
@@ -522,6 +609,13 @@ func nullString(value string) any {
|
||||
return value
|
||||
}
|
||||
|
||||
func boolInt(value bool) int {
|
||||
if value {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func timePtrString(value *time.Time) any {
|
||||
if value == nil {
|
||||
return nil
|
||||
|
||||
@@ -55,7 +55,34 @@ func NewService(repo *Repository, publicOrigin string) (*Service, error) {
|
||||
return &Service{repo: repo, webauthn: web, publicOrigin: publicOrigin}, nil
|
||||
}
|
||||
|
||||
func (s *Service) GetInstanceSettings(ctx context.Context) (InstanceSettings, error) {
|
||||
return s.repo.GetInstanceSettings(ctx)
|
||||
}
|
||||
|
||||
func (s *Service) CompleteInitialSetup(ctx context.Context, email, displayName, password string, signupsEnabled bool) (User, error) {
|
||||
email = normalizeEmail(email)
|
||||
if email == "" {
|
||||
return User{}, fmt.Errorf("email is required")
|
||||
}
|
||||
if len(password) < 12 {
|
||||
return User{}, fmt.Errorf("password must be at least 12 characters")
|
||||
}
|
||||
passwordHash, err := hashPassword(password)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
return s.repo.CompleteInitialSetup(ctx, User{
|
||||
Email: email,
|
||||
DisplayName: strings.TrimSpace(displayName),
|
||||
PasswordHash: passwordHash,
|
||||
Role: RoleAdmin,
|
||||
}, signupsEnabled)
|
||||
}
|
||||
|
||||
func (s *Service) RegisterPasswordUser(ctx context.Context, email, displayName, password, role string) (User, error) {
|
||||
if err := s.requirePublicSignups(ctx); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
email = normalizeEmail(email)
|
||||
if email == "" {
|
||||
return User{}, fmt.Errorf("email is required")
|
||||
@@ -72,21 +99,11 @@ func (s *Service) RegisterPasswordUser(ctx context.Context, email, displayName,
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
userCount, err := s.repo.CountUsers(ctx)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
normalizedRole := RoleViewer
|
||||
if userCount == 0 {
|
||||
normalizedRole = RoleAdmin
|
||||
} else if strings.EqualFold(role, string(RoleViewer)) {
|
||||
normalizedRole = RoleViewer
|
||||
}
|
||||
return s.repo.UpsertUser(ctx, User{
|
||||
Email: email,
|
||||
DisplayName: strings.TrimSpace(displayName),
|
||||
PasswordHash: passwordHash,
|
||||
Role: normalizedRole,
|
||||
Role: RoleViewer,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -113,23 +130,18 @@ func (s *Service) LoginPassword(ctx context.Context, email, password, ip, userAg
|
||||
}
|
||||
|
||||
func (s *Service) BeginPasskeyRegistration(ctx context.Context, email, displayName, role string) (any, string, error) {
|
||||
if err := s.requirePublicSignups(ctx); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
user, err := s.repo.GetUserByEmail(ctx, normalizeEmail(email))
|
||||
if err != nil {
|
||||
if !isNoRows(err) {
|
||||
return nil, "", err
|
||||
}
|
||||
userCount, err := s.repo.CountUsers(ctx)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
normalizedRole := RoleViewer
|
||||
if userCount == 0 {
|
||||
normalizedRole = RoleAdmin
|
||||
}
|
||||
user, err = s.repo.UpsertUser(ctx, User{
|
||||
Email: normalizeEmail(email),
|
||||
DisplayName: strings.TrimSpace(displayName),
|
||||
Role: normalizedRole,
|
||||
Role: RoleViewer,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
@@ -278,6 +290,43 @@ func (s *Service) ListUsers(ctx context.Context) ([]User, error) {
|
||||
return s.repo.ListUsers(ctx)
|
||||
}
|
||||
|
||||
func (s *Service) UpdateSignupsEnabled(ctx context.Context, actor Principal, enabled bool) (InstanceSettings, error) {
|
||||
if !Allows(actor, ScopeAdmin) {
|
||||
return InstanceSettings{}, fmt.Errorf("admin role required")
|
||||
}
|
||||
if err := s.repo.UpdateSignupsEnabled(ctx, enabled); err != nil {
|
||||
return InstanceSettings{}, err
|
||||
}
|
||||
return s.repo.GetInstanceSettings(ctx)
|
||||
}
|
||||
|
||||
func (s *Service) EnsureDevUser(ctx context.Context) (User, error) {
|
||||
const email = "dev@localhost"
|
||||
settings, err := s.repo.GetInstanceSettings(ctx)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
if !settings.SetupComplete {
|
||||
return s.CompleteInitialSetup(ctx, email, "Development Admin", "development-only-password", true)
|
||||
}
|
||||
user, err := s.repo.GetUserByEmail(ctx, email)
|
||||
if err == nil {
|
||||
return user, nil
|
||||
}
|
||||
if !isNoRows(err) {
|
||||
return User{}, err
|
||||
}
|
||||
return s.repo.UpsertUser(ctx, User{Email: email, DisplayName: "Development Admin", Role: RoleAdmin})
|
||||
}
|
||||
|
||||
func (s *Service) PrincipalForUser(ctx context.Context, userID string) (Principal, error) {
|
||||
user, err := s.repo.GetUserByID(ctx, userID)
|
||||
if err != nil {
|
||||
return Principal{}, err
|
||||
}
|
||||
return principalFromUser(user, "dev", "", "", nil, time.Time{}), nil
|
||||
}
|
||||
|
||||
func (s *Service) UpdateUserRole(ctx context.Context, actor Principal, userID, role string) (User, error) {
|
||||
if !Allows(actor, ScopeAdmin) {
|
||||
return User{}, fmt.Errorf("admin role required")
|
||||
@@ -453,6 +502,20 @@ func (s *Service) createSession(ctx context.Context, user User, ip, userAgent st
|
||||
return principalFromUser(user, "session", session.ID, "", nil, session.ExpiresAt), token, nil
|
||||
}
|
||||
|
||||
func (s *Service) requirePublicSignups(ctx context.Context) error {
|
||||
settings, err := s.repo.GetInstanceSettings(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !settings.SetupComplete {
|
||||
return fmt.Errorf("initial setup is required")
|
||||
}
|
||||
if !settings.SignupsEnabled {
|
||||
return fmt.Errorf("signups are disabled")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func principalFromUser(user User, method, sessionID, apiKeyID string, scopes []Scope, expiresAt time.Time) Principal {
|
||||
return Principal{
|
||||
UserID: user.ID,
|
||||
|
||||
@@ -28,13 +28,23 @@ func setupAuthTestService(t *testing.T) *Service {
|
||||
return service
|
||||
}
|
||||
|
||||
func setupInitialAdmin(t *testing.T, service *Service, signupsEnabled bool) User {
|
||||
t.Helper()
|
||||
|
||||
user, err := service.CompleteInitialSetup(context.Background(), "admin@example.com", "Admin", "correct horse battery staple", signupsEnabled)
|
||||
if err != nil {
|
||||
t.Fatalf("CompleteInitialSetup() error = %v", err)
|
||||
}
|
||||
return user
|
||||
}
|
||||
|
||||
func TestPasswordLoginCreatesValidSession(t *testing.T) {
|
||||
service := setupAuthTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
user, err := service.RegisterPasswordUser(ctx, "Dev@Example.com", "Dev User", "correct horse battery staple", "editor")
|
||||
user, err := service.CompleteInitialSetup(ctx, "Dev@Example.com", "Dev User", "correct horse battery staple", true)
|
||||
if err != nil {
|
||||
t.Fatalf("RegisterPasswordUser() error = %v", err)
|
||||
t.Fatalf("CompleteInitialSetup() error = %v", err)
|
||||
}
|
||||
if user.Email != "dev@example.com" {
|
||||
t.Fatalf("email = %q, want normalized", user.Email)
|
||||
@@ -48,7 +58,7 @@ func TestPasswordLoginCreatesValidSession(t *testing.T) {
|
||||
t.Fatal("expected session token")
|
||||
}
|
||||
if principal.Role != RoleAdmin {
|
||||
t.Fatalf("role = %s, want first registered user to bootstrap as admin", principal.Role)
|
||||
t.Fatalf("role = %s, want initial setup user to be admin", principal.Role)
|
||||
}
|
||||
|
||||
validated, err := service.ValidateSessionToken(ctx, token)
|
||||
@@ -64,10 +74,7 @@ func TestAPIKeyUsesShownOnceBearerToken(t *testing.T) {
|
||||
service := setupAuthTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
user, err := service.RegisterPasswordUser(ctx, "admin@example.com", "Admin", "correct horse battery staple", "admin")
|
||||
if err != nil {
|
||||
t.Fatalf("RegisterPasswordUser() error = %v", err)
|
||||
}
|
||||
user := setupInitialAdmin(t, service, true)
|
||||
expires := time.Now().UTC().Add(time.Hour)
|
||||
created, err := service.CreateAPIKey(ctx, user.ID, "CLI", []Scope{ScopeDocsRead, ScopeSyncWrite}, &expires)
|
||||
if err != nil {
|
||||
@@ -99,10 +106,7 @@ func TestDeviceFlowMintsAPIKeyAfterApproval(t *testing.T) {
|
||||
service := setupAuthTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
user, err := service.RegisterPasswordUser(ctx, "admin@example.com", "Admin", "correct horse battery staple", "admin")
|
||||
if err != nil {
|
||||
t.Fatalf("RegisterPasswordUser() error = %v", err)
|
||||
}
|
||||
user := setupInitialAdmin(t, service, true)
|
||||
start, err := service.StartDeviceFlow(ctx, "Laptop", []Scope{ScopeSyncRead})
|
||||
if err != nil {
|
||||
t.Fatalf("StartDeviceFlow() error = %v", err)
|
||||
@@ -132,10 +136,7 @@ func TestPasswordChangeInvalidatesOldPassword(t *testing.T) {
|
||||
service := setupAuthTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
user, err := service.RegisterPasswordUser(ctx, "admin@example.com", "Admin", "correct horse battery staple", "admin")
|
||||
if err != nil {
|
||||
t.Fatalf("RegisterPasswordUser() error = %v", err)
|
||||
}
|
||||
user := setupInitialAdmin(t, service, true)
|
||||
principal := principalFromUser(user, "session", "sess:test", "", nil, time.Now().Add(time.Hour))
|
||||
if err := service.ChangePassword(ctx, principal, "correct horse battery staple", "new correct horse battery staple"); err != nil {
|
||||
t.Fatalf("ChangePassword() error = %v", err)
|
||||
@@ -152,10 +153,7 @@ func TestCannotDemoteOrDeleteLastAdmin(t *testing.T) {
|
||||
service := setupAuthTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
user, err := service.RegisterPasswordUser(ctx, "admin@example.com", "Admin", "correct horse battery staple", "admin")
|
||||
if err != nil {
|
||||
t.Fatalf("RegisterPasswordUser() error = %v", err)
|
||||
}
|
||||
user := setupInitialAdmin(t, service, true)
|
||||
principal := principalFromUser(user, "session", "sess:test", "", nil, time.Now().Add(time.Hour))
|
||||
if _, err := service.UpdateUserRole(ctx, principal, user.ID, string(RoleEditor)); err == nil {
|
||||
t.Fatal("expected demoting last admin to fail")
|
||||
@@ -169,6 +167,7 @@ func TestPublicRegistrationCannotAttachCredentialsToExistingUser(t *testing.T) {
|
||||
service := setupAuthTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
setupInitialAdmin(t, service, true)
|
||||
if _, err := service.RegisterPasswordUser(ctx, "dev@example.com", "Dev", "correct horse battery staple", "admin"); err != nil {
|
||||
t.Fatalf("RegisterPasswordUser() error = %v", err)
|
||||
}
|
||||
@@ -179,3 +178,32 @@ func TestPublicRegistrationCannotAttachCredentialsToExistingUser(t *testing.T) {
|
||||
t.Fatal("expected public passkey registration for existing account to fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitialSetupCanDisablePublicRegistration(t *testing.T) {
|
||||
service := setupAuthTestService(t)
|
||||
ctx := context.Background()
|
||||
admin := setupInitialAdmin(t, service, false)
|
||||
|
||||
if admin.Role != RoleAdmin {
|
||||
t.Fatalf("initial role = %s, want admin", admin.Role)
|
||||
}
|
||||
if _, err := service.RegisterPasswordUser(ctx, "viewer@example.com", "Viewer", "correct horse battery staple", "viewer"); err == nil || err.Error() != "signups are disabled" {
|
||||
t.Fatalf("RegisterPasswordUser() error = %v, want signups are disabled", err)
|
||||
}
|
||||
|
||||
principal := principalFromUser(admin, "session", "sess:test", "", nil, time.Now().Add(time.Hour))
|
||||
settings, err := service.UpdateSignupsEnabled(ctx, principal, true)
|
||||
if err != nil {
|
||||
t.Fatalf("UpdateSignupsEnabled() error = %v", err)
|
||||
}
|
||||
if !settings.SignupsEnabled {
|
||||
t.Fatal("expected signups to be enabled")
|
||||
}
|
||||
viewer, err := service.RegisterPasswordUser(ctx, "viewer@example.com", "Viewer", "correct horse battery staple", "admin")
|
||||
if err != nil {
|
||||
t.Fatalf("RegisterPasswordUser() after enabling signups error = %v", err)
|
||||
}
|
||||
if viewer.Role != RoleViewer {
|
||||
t.Fatalf("public signup role = %s, want viewer", viewer.Role)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,6 +92,11 @@ type CreatedAPIKey struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
type InstanceSettings struct {
|
||||
SetupComplete bool `json:"setupComplete"`
|
||||
SignupsEnabled bool `json:"signupsEnabled"`
|
||||
}
|
||||
|
||||
type DeviceCode struct {
|
||||
ID string
|
||||
UserID string
|
||||
|
||||
@@ -12,10 +12,10 @@ type Config struct {
|
||||
Server ServerConfig `json:"server"`
|
||||
Database DatabaseConfig `json:"database"`
|
||||
Content ContentConfig `json:"content"`
|
||||
Web WebConfig `json:"web"`
|
||||
Auth AuthConfig `json:"auth"`
|
||||
Email EmailConfig `json:"email"`
|
||||
LogLevel string `json:"logLevel"`
|
||||
DevMode bool `json:"devMode"`
|
||||
}
|
||||
|
||||
type ServerConfig struct {
|
||||
@@ -33,11 +33,6 @@ type ContentConfig struct {
|
||||
StoreDir string `json:"storeDir"`
|
||||
}
|
||||
|
||||
type WebConfig struct {
|
||||
DistDir string `json:"distDir"`
|
||||
DevViteURL string `json:"devViteUrl"`
|
||||
}
|
||||
|
||||
type AuthConfig struct {
|
||||
PublicOrigin string `json:"publicOrigin"`
|
||||
}
|
||||
@@ -60,10 +55,6 @@ func Default() Config {
|
||||
SourceDir: filepath.Join("..", "..", "content"),
|
||||
StoreDir: filepath.Join("..", "..", "data", "files"),
|
||||
},
|
||||
Web: WebConfig{
|
||||
DistDir: filepath.Join("..", "web", "dist"),
|
||||
DevViteURL: os.Getenv("CAIRNQUIRE_DEV_VITE_URL"),
|
||||
},
|
||||
Auth: AuthConfig{
|
||||
PublicOrigin: "http://localhost:8080",
|
||||
},
|
||||
@@ -91,8 +82,6 @@ func Load() (Config, error) {
|
||||
overrideString(&cfg.Database.AuthToken, "CAIRNQUIRE_DATABASE_AUTH_TOKEN")
|
||||
overrideString(&cfg.Content.SourceDir, "CAIRNQUIRE_CONTENT_SOURCE_DIR")
|
||||
overrideString(&cfg.Content.StoreDir, "CAIRNQUIRE_CONTENT_STORE_DIR")
|
||||
overrideString(&cfg.Web.DistDir, "CAIRNQUIRE_WEB_DIST_DIR")
|
||||
overrideString(&cfg.Web.DevViteURL, "CAIRNQUIRE_DEV_VITE_URL")
|
||||
overrideString(&cfg.Auth.PublicOrigin, "CAIRNQUIRE_PUBLIC_ORIGIN")
|
||||
overrideString(&cfg.Email.SMTPHost, "CAIRNQUIRE_EMAIL_SMTP_HOST")
|
||||
if port := os.Getenv("CAIRNQUIRE_EMAIL_SMTP_PORT"); port != "" {
|
||||
@@ -102,6 +91,13 @@ func Load() (Config, error) {
|
||||
}
|
||||
overrideString(&cfg.Email.From, "CAIRNQUIRE_EMAIL_FROM")
|
||||
overrideString(&cfg.LogLevel, "CAIRNQUIRE_LOG_LEVEL")
|
||||
if devMode := os.Getenv("CAIRNQUIRE_DEV_MODE"); devMode != "" {
|
||||
parsed, err := strconv.ParseBool(devMode)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("parse CAIRNQUIRE_DEV_MODE: %w", err)
|
||||
}
|
||||
cfg.DevMode = parsed
|
||||
}
|
||||
|
||||
if cfg.Server.Addr == "" {
|
||||
return Config{}, fmt.Errorf("server.addr must not be empty")
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
DROP TABLE IF EXISTS instance_settings;
|
||||
@@ -0,0 +1,13 @@
|
||||
CREATE TABLE IF NOT EXISTS instance_settings (
|
||||
id INTEGER PRIMARY KEY CHECK(id = 1),
|
||||
setup_completed_at TEXT,
|
||||
signups_enabled INTEGER NOT NULL DEFAULT 0 CHECK(signups_enabled IN (0, 1)),
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
INSERT OR IGNORE INTO instance_settings (id, setup_completed_at, signups_enabled, updated_at)
|
||||
SELECT
|
||||
1,
|
||||
CASE WHEN EXISTS(SELECT 1 FROM users) THEN datetime('now') ELSE NULL END,
|
||||
CASE WHEN EXISTS(SELECT 1 FROM users) THEN 1 ELSE 0 END,
|
||||
datetime('now');
|
||||
@@ -271,6 +271,33 @@ func (r *Repository) GetAttachment(ctx context.Context, hash string) (*Attachmen
|
||||
return &record, nil
|
||||
}
|
||||
|
||||
func (r *Repository) ListAttachments(ctx context.Context) ([]AttachmentRecord, error) {
|
||||
rows, err := r.db.QueryContext(ctx, `
|
||||
SELECT hash, original_name, content_type, size_bytes, created_at
|
||||
FROM attachments
|
||||
ORDER BY created_at DESC
|
||||
`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list attachments: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var attachments []AttachmentRecord
|
||||
for rows.Next() {
|
||||
var record AttachmentRecord
|
||||
var created string
|
||||
if err := rows.Scan(&record.Hash, &record.OriginalName, &record.ContentType, &record.SizeBytes, &created); err != nil {
|
||||
return nil, fmt.Errorf("scan attachment: %w", err)
|
||||
}
|
||||
record.CreatedAt, err = time.Parse(time.RFC3339, created)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse attachment created_at: %w", err)
|
||||
}
|
||||
attachments = append(attachments, record)
|
||||
}
|
||||
return attachments, rows.Err()
|
||||
}
|
||||
|
||||
type SearchResult struct {
|
||||
Path string `json:"path"`
|
||||
Title string `json:"title"`
|
||||
|
||||
@@ -15,6 +15,10 @@ type adminUserInput struct {
|
||||
Role string `json:"role"`
|
||||
}
|
||||
|
||||
type adminSettingsInput struct {
|
||||
SignupsEnabled bool `json:"signupsEnabled"`
|
||||
}
|
||||
|
||||
func (s *Server) handleAdminLogin(w http.ResponseWriter, r *http.Request) {
|
||||
var input adminUserInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
|
||||
@@ -95,7 +99,6 @@ func (s *Server) handleAdminWorkspace(w http.ResponseWriter, r *http.Request) {
|
||||
"databasePath": s.config.Database.Path,
|
||||
"documentCount": len(documents),
|
||||
"userCount": len(users),
|
||||
"webDistDir": s.config.Web.DistDir,
|
||||
},
|
||||
"documents": documents,
|
||||
})
|
||||
@@ -113,6 +116,30 @@ func (s *Server) handleAdminWorkspaceSync(w http.ResponseWriter, r *http.Request
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleAdminSettings(w http.ResponseWriter, r *http.Request) {
|
||||
settings, err := s.auth.GetInstanceSettings(r.Context())
|
||||
if err != nil {
|
||||
writeJSONWithStatus(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"settings": settings})
|
||||
}
|
||||
|
||||
func (s *Server) handleAdminSettingsUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
principal, _ := requirePrincipal(r)
|
||||
var input adminSettingsInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
|
||||
writeJSONWithStatus(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
|
||||
return
|
||||
}
|
||||
settings, err := s.auth.UpdateSignupsEnabled(r.Context(), principal, input.SignupsEnabled)
|
||||
if err != nil {
|
||||
writeJSONWithStatus(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"settings": settings})
|
||||
}
|
||||
|
||||
func (s *Server) normalizeAdminUserInput(input adminUserInput) (docs.UserRecord, bool) {
|
||||
email := strings.TrimSpace(strings.ToLower(input.Email))
|
||||
if email == "" {
|
||||
|
||||
@@ -32,6 +32,10 @@ type apiTestServer struct {
|
||||
}
|
||||
|
||||
func newAPITestServer(t *testing.T) *apiTestServer {
|
||||
return newAPITestServerWithSetup(t, true)
|
||||
}
|
||||
|
||||
func newAPITestServerWithSetup(t *testing.T, setupComplete bool) *apiTestServer {
|
||||
t.Helper()
|
||||
|
||||
ctx := context.Background()
|
||||
@@ -69,9 +73,12 @@ func newAPITestServer(t *testing.T) *apiTestServer {
|
||||
if err != nil {
|
||||
t.Fatalf("create auth service: %v", err)
|
||||
}
|
||||
user, err := authService.RegisterPasswordUser(ctx, "editor@example.com", "Editor", "very secure password", string(auth.RoleEditor))
|
||||
if err != nil {
|
||||
t.Fatalf("create test user: %v", err)
|
||||
var user auth.User
|
||||
if setupComplete {
|
||||
user, err = authService.CompleteInitialSetup(ctx, "editor@example.com", "Editor", "very secure password", false)
|
||||
if err != nil {
|
||||
t.Fatalf("create test user: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
syncRepo := sync.NewRepository(db.SQL())
|
||||
@@ -81,7 +88,6 @@ func newAPITestServer(t *testing.T) *apiTestServer {
|
||||
SourceDir: sourceDir,
|
||||
StoreDir: storeDir,
|
||||
},
|
||||
Web: config.WebConfig{DistDir: filepath.Join(root, "web-dist")},
|
||||
Auth: config.AuthConfig{PublicOrigin: "http://localhost:8080"},
|
||||
},
|
||||
Logger: logger,
|
||||
@@ -106,6 +112,54 @@ func newAPITestServer(t *testing.T) *apiTestServer {
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitialSetupWizardCreatesAdminAndPersistsSignupPolicy(t *testing.T) {
|
||||
server := newAPITestServerWithSetup(t, false)
|
||||
|
||||
index := httptest.NewRecorder()
|
||||
server.handler.ServeHTTP(index, httptest.NewRequest(http.MethodGet, "/", nil))
|
||||
if index.Code != http.StatusSeeOther || index.Header().Get("Location") != "/setup" {
|
||||
t.Fatalf("initial index response = %d %q, want redirect to /setup", index.Code, index.Header().Get("Location"))
|
||||
}
|
||||
|
||||
setupPage := httptest.NewRecorder()
|
||||
server.handler.ServeHTTP(setupPage, httptest.NewRequest(http.MethodGet, "/setup", nil))
|
||||
if setupPage.Code != http.StatusOK || !bytes.Contains(setupPage.Body.Bytes(), []byte("Initial setup")) {
|
||||
t.Fatalf("setup page response = %d %q", setupPage.Code, setupPage.Body.String())
|
||||
}
|
||||
|
||||
setup := httptest.NewRecorder()
|
||||
server.handler.ServeHTTP(setup, jsonRequest(http.MethodPost, "/api/setup", map[string]any{
|
||||
"email": "owner@example.com",
|
||||
"displayName": "Owner",
|
||||
"password": "correct horse battery staple",
|
||||
"signupsEnabled": false,
|
||||
}))
|
||||
if setup.Code != http.StatusCreated {
|
||||
t.Fatalf("setup status = %d, want %d; body=%s", setup.Code, http.StatusCreated, setup.Body.String())
|
||||
}
|
||||
if len(setup.Result().Cookies()) == 0 {
|
||||
t.Fatal("expected setup to create a browser session")
|
||||
}
|
||||
|
||||
settings, err := server.auth.GetInstanceSettings(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("GetInstanceSettings() error = %v", err)
|
||||
}
|
||||
if !settings.SetupComplete || settings.SignupsEnabled {
|
||||
t.Fatalf("settings = %#v, want setup complete with signups disabled", settings)
|
||||
}
|
||||
|
||||
register := httptest.NewRecorder()
|
||||
server.handler.ServeHTTP(register, jsonRequest(http.MethodPost, "/api/auth/register/password", map[string]any{
|
||||
"email": "viewer@example.com",
|
||||
"displayName": "Viewer",
|
||||
"password": "correct horse battery staple",
|
||||
}))
|
||||
if register.Code != http.StatusBadRequest || !bytes.Contains(register.Body.Bytes(), []byte("signups are disabled")) {
|
||||
t.Fatalf("register response = %d %q, want disabled signup error", register.Code, register.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func (s *apiTestServer) token(t *testing.T, scopes ...auth.Scope) string {
|
||||
t.Helper()
|
||||
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
package httpserver
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (s *Server) appFileServer() http.Handler {
|
||||
if s.config.Web.DevViteURL != "" {
|
||||
viteURL, err := url.Parse(s.config.Web.DevViteURL)
|
||||
if err == nil {
|
||||
proxy := httputil.NewSingleHostReverseProxy(viteURL)
|
||||
originalDirector := proxy.Director
|
||||
proxy.Director = func(req *http.Request) {
|
||||
originalDirector(req)
|
||||
req.Host = viteURL.Host
|
||||
// Add back the /app/ prefix that was stripped by http.StripPrefix
|
||||
req.URL.Path = "/app" + req.URL.Path
|
||||
}
|
||||
return proxy
|
||||
}
|
||||
}
|
||||
|
||||
files := http.FileServer(http.Dir(s.config.Web.DistDir))
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
cleanPath := filepath.Clean(strings.TrimPrefix(r.URL.Path, "/"))
|
||||
if cleanPath == "." {
|
||||
cleanPath = "index.html"
|
||||
}
|
||||
|
||||
target := filepath.Join(s.config.Web.DistDir, cleanPath)
|
||||
if info, err := os.Stat(target); err == nil && !info.IsDir() {
|
||||
files.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
http.ServeFile(w, r, filepath.Join(s.config.Web.DistDir, "index.html"))
|
||||
})
|
||||
}
|
||||
@@ -24,6 +24,13 @@ type passwordLoginRequest struct {
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type initialSetupRequest struct {
|
||||
Email string `json:"email"`
|
||||
DisplayName string `json:"displayName"`
|
||||
Password string `json:"password"`
|
||||
SignupsEnabled bool `json:"signupsEnabled"`
|
||||
}
|
||||
|
||||
type passkeyBeginRequest struct {
|
||||
Email string `json:"email"`
|
||||
DisplayName string `json:"displayName"`
|
||||
@@ -67,17 +74,61 @@ func (s *Server) handleLoginPage(w http.ResponseWriter, r *http.Request) {
|
||||
if !strings.HasPrefix(nextPath, "/") || strings.HasPrefix(nextPath, "//") {
|
||||
nextPath = "/account"
|
||||
}
|
||||
settings, err := s.auth.GetInstanceSettings(r.Context())
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "load registration settings")
|
||||
return
|
||||
}
|
||||
s.renderTemplate(w, http.StatusOK, "login.gohtml", layoutData{
|
||||
Title: "Sign in",
|
||||
WebEnabled: s.webEnabled,
|
||||
BodyClass: "page-auth",
|
||||
BodyTemplate: "login_content",
|
||||
Data: struct {
|
||||
Next string
|
||||
}{Next: nextPath},
|
||||
Next string
|
||||
SignupsEnabled bool
|
||||
}{Next: nextPath, SignupsEnabled: settings.SignupsEnabled},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleSetupPage(w http.ResponseWriter, r *http.Request) {
|
||||
settings, err := s.auth.GetInstanceSettings(r.Context())
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, "load initial setup state")
|
||||
return
|
||||
}
|
||||
if settings.SetupComplete {
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
s.renderTemplate(w, http.StatusOK, "setup.gohtml", layoutData{
|
||||
Title: "Initial setup",
|
||||
BodyClass: "page-auth",
|
||||
BodyTemplate: "setup_content",
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleSetup(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.allowAuthAttempt(w, r) {
|
||||
return
|
||||
}
|
||||
var req initialSetupRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeJSONWithStatus(w, http.StatusBadRequest, map[string]string{"error": "invalid json"})
|
||||
return
|
||||
}
|
||||
if _, err := s.auth.CompleteInitialSetup(r.Context(), req.Email, req.DisplayName, req.Password, req.SignupsEnabled); err != nil {
|
||||
writeJSONWithStatus(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
principal, token, err := s.auth.LoginPassword(r.Context(), req.Email, req.Password, requestIP(r), r.UserAgent())
|
||||
if err != nil {
|
||||
writeJSONWithStatus(w, http.StatusInternalServerError, map[string]string{"error": "initial admin created; sign in to continue"})
|
||||
return
|
||||
}
|
||||
setSessionCookie(w, r, token, principal.ExpiresAt)
|
||||
writeJSONWithStatus(w, http.StatusCreated, map[string]any{"principal": principal})
|
||||
}
|
||||
|
||||
func (s *Server) handleAccountPage(w http.ResponseWriter, r *http.Request) {
|
||||
principal, ok := requirePrincipal(r)
|
||||
if !ok {
|
||||
@@ -86,7 +137,6 @@ func (s *Server) handleAccountPage(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
s.renderTemplate(w, http.StatusOK, "account.gohtml", layoutData{
|
||||
Title: "Account",
|
||||
WebEnabled: s.webEnabled,
|
||||
BodyClass: "page-account",
|
||||
BodyTemplate: "account_content",
|
||||
Data: principal,
|
||||
@@ -377,7 +427,6 @@ func (s *Server) handleDeviceVerifyPage(w http.ResponseWriter, r *http.Request)
|
||||
userCode := strings.TrimSpace(r.URL.Query().Get("user_code"))
|
||||
s.renderTemplate(w, http.StatusOK, "device_verify.gohtml", layoutData{
|
||||
Title: "Approve device",
|
||||
WebEnabled: s.webEnabled,
|
||||
BodyClass: "page-auth",
|
||||
BodyTemplate: "device_verify_content",
|
||||
Data: struct {
|
||||
|
||||
@@ -23,7 +23,6 @@ import (
|
||||
|
||||
type layoutData struct {
|
||||
Title string
|
||||
WebEnabled bool
|
||||
BodyClass string
|
||||
BodyTemplate string
|
||||
Data any
|
||||
@@ -98,7 +97,6 @@ func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
|
||||
activeFolder := strings.Trim(r.URL.Query().Get("folder"), "/")
|
||||
s.renderTemplate(w, http.StatusOK, "index.gohtml", layoutData{
|
||||
Title: "Cairnquire",
|
||||
WebEnabled: s.webEnabled,
|
||||
BodyClass: "page-index",
|
||||
BodyTemplate: "index_content",
|
||||
Data: indexData{
|
||||
@@ -118,7 +116,6 @@ func (s *Server) handleSearchPage(w http.ResponseWriter, r *http.Request, query
|
||||
|
||||
s.renderTemplate(w, http.StatusOK, "search.gohtml", layoutData{
|
||||
Title: "Search: " + query,
|
||||
WebEnabled: s.webEnabled,
|
||||
BodyClass: "page-search",
|
||||
BodyTemplate: "search_content",
|
||||
Data: struct {
|
||||
@@ -225,7 +222,6 @@ func (s *Server) renderDocumentEditor(w http.ResponseWriter, r *http.Request, pa
|
||||
|
||||
s.renderTemplate(w, http.StatusOK, "document_edit.gohtml", layoutData{
|
||||
Title: "Edit: " + page.Title,
|
||||
WebEnabled: s.webEnabled,
|
||||
BodyClass: "page-document-edit",
|
||||
BodyTemplate: "document_edit_content",
|
||||
Data: documentEditData{
|
||||
@@ -259,7 +255,6 @@ func (s *Server) renderDocumentPage(w http.ResponseWriter, r *http.Request, page
|
||||
|
||||
s.renderTemplate(w, http.StatusOK, "document.gohtml", layoutData{
|
||||
Title: page.Title,
|
||||
WebEnabled: s.webEnabled,
|
||||
BodyClass: "page-document",
|
||||
BodyTemplate: "document_content",
|
||||
Data: documentData{
|
||||
@@ -403,6 +398,15 @@ func (s *Server) handleAttachment(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write(content)
|
||||
}
|
||||
|
||||
func (s *Server) handleAttachmentsList(w http.ResponseWriter, r *http.Request) {
|
||||
attachments, err := s.repository.ListAttachments(r.Context())
|
||||
if err != nil {
|
||||
writeJSONWithStatus(w, http.StatusInternalServerError, map[string]string{"error": "list attachments"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"attachments": attachments})
|
||||
}
|
||||
|
||||
func (s *Server) renderTemplate(w http.ResponseWriter, status int, name string, data layoutData) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
@@ -414,7 +418,6 @@ func (s *Server) renderTemplate(w http.ResponseWriter, status int, name string,
|
||||
func (s *Server) renderError(w http.ResponseWriter, r *http.Request, status int, message string) {
|
||||
s.renderTemplate(w, status, "error.gohtml", layoutData{
|
||||
Title: http.StatusText(status),
|
||||
WebEnabled: s.webEnabled,
|
||||
BodyClass: "page-error",
|
||||
BodyTemplate: "error_content",
|
||||
Data: errorData{
|
||||
|
||||
@@ -76,6 +76,33 @@ func (s *Server) authMiddleware(next http.Handler) http.Handler {
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) setupMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
settings, err := s.auth.GetInstanceSettings(r.Context())
|
||||
if err != nil {
|
||||
writeJSONWithStatus(w, http.StatusInternalServerError, map[string]string{"error": "lookup initial setup state"})
|
||||
return
|
||||
}
|
||||
if settings.SetupComplete || isSetupAllowedPath(r.URL.Path) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
if r.Method == http.MethodGet && !strings.HasPrefix(r.URL.Path, "/api/") {
|
||||
http.Redirect(w, r, "/setup", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
writeJSONWithStatus(w, http.StatusServiceUnavailable, map[string]string{"error": "initial setup is required"})
|
||||
})
|
||||
}
|
||||
|
||||
func isSetupAllowedPath(path string) bool {
|
||||
return path == "/setup" ||
|
||||
path == "/api/setup" ||
|
||||
path == "/health" ||
|
||||
path == "/sw.js" ||
|
||||
strings.HasPrefix(path, "/static/")
|
||||
}
|
||||
|
||||
func (s *Server) authenticateRequest(r *http.Request) (auth.Principal, bool) {
|
||||
if header := r.Header.Get("Authorization"); strings.HasPrefix(header, "Bearer ") {
|
||||
principal, err := s.auth.ValidateBearerToken(r.Context(), strings.TrimSpace(strings.TrimPrefix(header, "Bearer ")))
|
||||
@@ -87,7 +114,11 @@ func (s *Server) authenticateRequest(r *http.Request) (auth.Principal, bool) {
|
||||
}
|
||||
cookie, err := r.Cookie(auth.SessionCookieName)
|
||||
if err != nil || cookie.Value == "" {
|
||||
return auth.Principal{}, false
|
||||
if s.devUserID == "" {
|
||||
return auth.Principal{}, false
|
||||
}
|
||||
principal, err := s.auth.PrincipalForUser(r.Context(), s.devUserID)
|
||||
return principal, err == nil
|
||||
}
|
||||
principal, err := s.auth.ValidateSessionToken(r.Context(), cookie.Value)
|
||||
if err != nil {
|
||||
@@ -120,6 +151,8 @@ func requiredScopeForPath(r *http.Request) (auth.Scope, bool) {
|
||||
return auth.ScopeDocsWrite, true
|
||||
case strings.HasPrefix(path, "/api/uploads"):
|
||||
return auth.ScopeDocsWrite, true
|
||||
case path == "/api/attachments":
|
||||
return auth.ScopeDocsRead, true
|
||||
case strings.HasPrefix(path, "/api/sync/"):
|
||||
if method == http.MethodPost {
|
||||
return auth.ScopeSyncWrite, true
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
package httpserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -50,7 +51,7 @@ type Server struct {
|
||||
collaboration *collaboration.Service
|
||||
authLimiter *rateLimiter
|
||||
templates *template.Template
|
||||
webEnabled bool
|
||||
devUserID string
|
||||
}
|
||||
|
||||
func New(deps Dependencies) (http.Handler, error) {
|
||||
@@ -81,8 +82,13 @@ func New(deps Dependencies) (http.Handler, error) {
|
||||
templates: templates,
|
||||
}
|
||||
|
||||
if _, err := os.Stat(deps.Config.Web.DistDir); err == nil {
|
||||
server.webEnabled = true
|
||||
if deps.Config.DevMode {
|
||||
devUser, err := deps.Auth.EnsureDevUser(context.Background())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("ensure dev user: %w", err)
|
||||
}
|
||||
server.devUserID = devUser.ID
|
||||
deps.Logger.Info("dev mode enabled", "dev_user_id", devUser.ID)
|
||||
}
|
||||
|
||||
router := chi.NewRouter()
|
||||
@@ -92,9 +98,11 @@ func New(deps Dependencies) (http.Handler, error) {
|
||||
router.Use(server.timeoutExceptWebSocket(30 * time.Second))
|
||||
router.Use(server.requestLogger)
|
||||
router.Use(server.securityHeaders)
|
||||
router.Use(server.setupMiddleware)
|
||||
router.Use(server.authMiddleware)
|
||||
|
||||
router.Get("/", server.handleIndex)
|
||||
router.Get("/setup", server.handleSetupPage)
|
||||
router.Get("/login", server.handleLoginPage)
|
||||
router.Get("/account", server.handleAccountPage)
|
||||
router.Get("/device/verify", server.handleDeviceVerifyPage)
|
||||
@@ -102,6 +110,7 @@ func New(deps Dependencies) (http.Handler, error) {
|
||||
router.Get("/sw.js", server.handleServiceWorker)
|
||||
router.Get("/ws", server.handleWebSocket)
|
||||
router.Get("/api/auth/me", server.handleAuthMe)
|
||||
router.Post("/api/setup", server.handleSetup)
|
||||
router.Post("/api/auth/register/password", server.handlePasswordRegister)
|
||||
router.Post("/api/auth/login/password", server.handlePasswordLogin)
|
||||
router.Post("/api/auth/logout", server.handleLogout)
|
||||
@@ -123,6 +132,8 @@ func New(deps Dependencies) (http.Handler, error) {
|
||||
router.Post("/api/admin/users", server.handleAdminCreateUser)
|
||||
router.Patch("/api/admin/users/{id}/role", server.handleAdminUpdateUserRole)
|
||||
router.Get("/api/admin/auth-users", server.handleAdminAuthUsers)
|
||||
router.Get("/api/admin/settings", server.handleAdminSettings)
|
||||
router.Patch("/api/admin/settings", server.handleAdminSettingsUpdate)
|
||||
router.Get("/api/admin/workspace", server.handleAdminWorkspace)
|
||||
router.Post("/api/admin/workspace/sync", server.handleAdminWorkspaceSync)
|
||||
router.Get("/docs", server.handleDocsIndex)
|
||||
@@ -131,6 +142,7 @@ func New(deps Dependencies) (http.Handler, error) {
|
||||
router.Post("/api/documents/*", server.handleDocumentSave)
|
||||
router.Get("/api/search", server.handleSearch)
|
||||
router.Post("/api/uploads", server.handleUpload)
|
||||
router.Get("/api/attachments", server.handleAttachmentsList)
|
||||
router.Get("/attachments/{hash}", server.handleAttachment)
|
||||
|
||||
// Collaboration endpoints
|
||||
@@ -155,18 +167,9 @@ func New(deps Dependencies) (http.Handler, error) {
|
||||
|
||||
router.Handle("/static/*", http.StripPrefix("/static/", http.FileServer(mustSub("static"))))
|
||||
|
||||
if server.webEnabled {
|
||||
router.Get("/app", server.handleAppRedirect)
|
||||
router.Handle("/app/*", http.StripPrefix("/app/", server.appFileServer()))
|
||||
}
|
||||
|
||||
return router, nil
|
||||
}
|
||||
|
||||
func (s *Server) handleAppRedirect(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "/app/", http.StatusMovedPermanently)
|
||||
}
|
||||
|
||||
func mustSub(path string) http.FileSystem {
|
||||
sub, err := fsSub(path)
|
||||
if err != nil {
|
||||
|
||||
@@ -78,6 +78,22 @@
|
||||
|
||||
const formJSON = (form) => Object.fromEntries(new FormData(form).entries());
|
||||
|
||||
document.querySelector("[data-initial-setup]")?.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget;
|
||||
try {
|
||||
await postJSON("/api/setup", {
|
||||
email: form.elements.email.value,
|
||||
displayName: form.elements.displayName.value,
|
||||
password: form.elements.password.value,
|
||||
signupsEnabled: form.elements.signupsEnabled.checked,
|
||||
});
|
||||
window.location.href = "/account";
|
||||
} catch (error) {
|
||||
setStatus("[data-setup-status]", error.message, true);
|
||||
}
|
||||
});
|
||||
|
||||
const base64URLToBuffer = (value) => {
|
||||
const padded = value.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(value.length / 4) * 4, "=");
|
||||
const binary = atob(padded);
|
||||
@@ -350,6 +366,29 @@
|
||||
);
|
||||
};
|
||||
|
||||
const loadAdminSettings = async () => {
|
||||
const section = document.querySelector("[data-admin-settings-section]");
|
||||
const form = document.querySelector("[data-admin-settings]");
|
||||
if (!section || !form) return;
|
||||
const me = await fetch("/api/auth/me", { credentials: "same-origin" }).then((response) => response.json()).catch(() => null);
|
||||
if (me?.principal?.role !== "admin") return;
|
||||
section.hidden = false;
|
||||
const data = await fetch("/api/admin/settings", { credentials: "same-origin" }).then((response) => response.json());
|
||||
form.elements.signupsEnabled.checked = Boolean(data.settings?.signupsEnabled);
|
||||
};
|
||||
|
||||
document.querySelector("[data-admin-settings]")?.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
try {
|
||||
const form = event.currentTarget;
|
||||
await postJSON("/api/admin/settings", { signupsEnabled: form.elements.signupsEnabled.checked }, { method: "PATCH" });
|
||||
setStatus("[data-admin-settings-status]", "Registration setting saved.");
|
||||
} catch (error) {
|
||||
setStatus("[data-admin-settings-status]", error.message, true);
|
||||
}
|
||||
});
|
||||
|
||||
loadTokens().catch(() => {});
|
||||
loadAdminUsers().catch(() => {});
|
||||
loadAdminSettings().catch(() => {});
|
||||
})();
|
||||
|
||||
@@ -240,6 +240,16 @@ code {
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.auth-form .auth-choice {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.55rem;
|
||||
}
|
||||
|
||||
.auth-choice input {
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.auth-form input,
|
||||
.auth-form select,
|
||||
.user-row select {
|
||||
@@ -1817,4 +1827,3 @@ code {
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -56,6 +56,18 @@
|
||||
<p class="form-status" data-admin-users-status></p>
|
||||
</section>
|
||||
|
||||
<section class="account-section" data-admin-settings-section hidden>
|
||||
<h2>Registration</h2>
|
||||
<form class="auth-form" data-admin-settings>
|
||||
<label class="auth-choice">
|
||||
<input type="checkbox" name="signupsEnabled" />
|
||||
Allow visitors to create accounts
|
||||
</label>
|
||||
<button type="submit">Save registration setting</button>
|
||||
<p class="form-status" data-admin-settings-status></p>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="account-section account-section--danger">
|
||||
<h2>Delete Account</h2>
|
||||
<form class="auth-form" data-account-delete>
|
||||
|
||||
@@ -50,6 +50,8 @@
|
||||
{{ template "search_content" .Data }}
|
||||
{{ else if eq .BodyTemplate "login_content" }}
|
||||
{{ template "login_content" .Data }}
|
||||
{{ else if eq .BodyTemplate "setup_content" }}
|
||||
{{ template "setup_content" .Data }}
|
||||
{{ else if eq .BodyTemplate "account_content" }}
|
||||
{{ template "account_content" .Data }}
|
||||
{{ else if eq .BodyTemplate "device_verify_content" }}
|
||||
|
||||
@@ -43,12 +43,12 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="auth-register-cta">
|
||||
{{ if .SignupsEnabled }}<div class="auth-register-cta">
|
||||
<button type="button" class="btn-cta" data-register-toggle>Create an Account</button>
|
||||
</div>
|
||||
</div>{{ end }}
|
||||
</div>
|
||||
|
||||
<div class="auth-register-panel" data-register-panel hidden>
|
||||
{{ if .SignupsEnabled }}<div class="auth-register-panel" data-register-panel hidden>
|
||||
<div class="auth-tabs">
|
||||
<div class="auth-tab-list" role="tablist">
|
||||
<button type="button" class="auth-tab is-active" role="tab" aria-selected="true" data-tab="passkey-register">Passkey</button>
|
||||
@@ -93,7 +93,7 @@
|
||||
<div class="auth-register-cancel">
|
||||
<button type="button" class="btn-secondary" data-register-cancel>Cancel — Back to Log In</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>{{ end }}
|
||||
</div>
|
||||
</section>
|
||||
{{ end }}
|
||||
|
||||
34
apps/server/internal/httpserver/templates/setup.gohtml
Normal file
34
apps/server/internal/httpserver/templates/setup.gohtml
Normal file
@@ -0,0 +1,34 @@
|
||||
{{ define "setup.gohtml" }}{{ template "base" . }}{{ end }}
|
||||
|
||||
{{ define "setup_content" }}
|
||||
<section class="auth-shell">
|
||||
<div class="auth-panel">
|
||||
<div class="auth-panel__header">
|
||||
<p class="eyebrow">Cairnquire</p>
|
||||
<h1>Initial setup</h1>
|
||||
<p class="auth-note">Create the first administrator account and choose whether visitors can register their own accounts.</p>
|
||||
</div>
|
||||
|
||||
<form class="auth-form" data-initial-setup>
|
||||
<label>
|
||||
Admin email
|
||||
<input type="email" name="email" autocomplete="email" required />
|
||||
</label>
|
||||
<label>
|
||||
Display name
|
||||
<input type="text" name="displayName" autocomplete="name" />
|
||||
</label>
|
||||
<label>
|
||||
Password
|
||||
<input type="password" name="password" autocomplete="new-password" minlength="12" required />
|
||||
</label>
|
||||
<label class="auth-choice">
|
||||
<input type="checkbox" name="signupsEnabled" />
|
||||
Allow visitors to create accounts
|
||||
</label>
|
||||
<button type="submit" class="btn-primary">Finish setup</button>
|
||||
<p class="form-status" data-setup-status></p>
|
||||
</form>
|
||||
</div>
|
||||
</section>
|
||||
{{ end }}
|
||||
Reference in New Issue
Block a user