81 lines
2.0 KiB
Go
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
|
|
}
|