Files
shared/backend/auth/reset.go
T
Gabriel20xx da97fd4fb1
Lint / Lint (Node/Svelte) (push) Successful in 24s
Lint / Lint (Go) (push) Successful in 28s
Lint / Lint (Python) (push) Failing after 14s
Tests / Test (Node/Svelte) (push) Successful in 18s
Tests / Test (Go) (push) Successful in 25s
Tests / Test (Python) (push) Successful in 12s
feat(auth): implement TOTP setup and management
- Added TOTP support for two-factor authentication in the auth module.
- Introduced new types and interfaces for TOTP setup and token actions in the web UI.
- Created backend logic for generating and verifying TOTP secrets and tokens.
- Implemented user management features including role assignments and user CRUD operations.
- Enhanced UI components for managing users and TOTP settings.
- Added styles for optional labels and authentication reset links.
- Implemented reset code generation and validation for admin accounts.
2026-08-05 14:57:01 +02:00

81 lines
2.0 KiB
Go

package auth
import (
"crypto/rand"
"crypto/subtle"
"encoding/hex"
"fmt"
"strings"
"sync"
"time"
)
// ResetCodeTTL is the amount of time a printed admin reset code remains valid.
const ResetCodeTTL = 5 * time.Minute
// ResetManager creates and validates the short-lived, one-time code used by
// the public "reset admin account" flow. Account deletion remains owned by
// each application because its account table and session policy may differ.
type ResetManager struct {
mu sync.Mutex
code string
expiresAt time.Time
}
// NewResetManager creates an independent reset-code manager for one server.
func NewResetManager() *ResetManager {
return &ResetManager{}
}
// Request creates a reset code and prints it to the server console. A new
// request invalidates any code previously issued by this manager.
func (m *ResetManager) Request() (string, error) {
if m == nil {
return "", fmt.Errorf("auth reset manager is nil")
}
raw := make([]byte, 4)
if _, err := rand.Read(raw); err != nil {
return "", fmt.Errorf("generate auth reset code: %w", err)
}
code := strings.ToUpper(hex.EncodeToString(raw))
m.mu.Lock()
m.code = code
m.expiresAt = time.Now().Add(ResetCodeTTL)
m.mu.Unlock()
fmt.Printf("\n%s\nADMIN RESET CODE: %s\nExpires in 5 minutes. Enter it on the login page.\n%s\n\n", strings.Repeat("=", 50), code, strings.Repeat("=", 50))
return code, nil
}
// Confirm validates a code and consumes it on success. Invalid codes do not
// consume the pending code, while expired codes are cleared immediately.
func (m *ResetManager) Confirm(candidate string) bool {
if m == nil {
return false
}
m.mu.Lock()
defer m.mu.Unlock()
if m.code == "" {
return false
}
if time.Now().After(m.expiresAt) {
m.code = ""
m.expiresAt = time.Time{}
return false
}
want := []byte(m.code)
got := []byte(strings.ToUpper(strings.TrimSpace(candidate)))
if len(want) != len(got) || subtle.ConstantTimeCompare(want, got) != 1 {
return false
}
m.code = ""
m.expiresAt = time.Time{}
return true
}