Files
2026-05-14 02:27:26 +01:00

520 lines
13 KiB
Go

package main
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"golang.org/x/crypto/bcrypt"
)
type userStore struct {
path string
mu sync.RWMutex
users map[string]userRecord
}
type userRecord struct {
ID string `json:"id"`
Username string `json:"username"`
PasswordHash string `json:"password_hash"`
Role string `json:"role"`
PrinterGrants []printerGrant `json:"printer_grants,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
type publicUser struct {
ID string `json:"id"`
Username string `json:"username"`
Role string `json:"role"`
PrinterGrants []printerGrant `json:"printer_grants,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
type printerGrant struct {
PrinterID string `json:"printer_id"`
Access string `json:"access"`
}
type userFile struct {
Users []userRecord `json:"users"`
}
func newUserStore(path string, bootstrapUsername string, bootstrapPassword string) (*userStore, error) {
store := &userStore{
path: path,
users: make(map[string]userRecord),
}
if err := store.loadOrBootstrap(bootstrapUsername, bootstrapPassword); err != nil {
return nil, err
}
return store, nil
}
func (s *userStore) loadOrBootstrap(bootstrapUsername string, bootstrapPassword string) error {
s.mu.Lock()
defer s.mu.Unlock()
if err := s.loadLocked(); err != nil {
return err
}
if len(s.users) > 0 {
return nil
}
if bootstrapUsername == "" || bootstrapPassword == "" {
return errors.New("no users exist and bootstrap credentials are empty")
}
record, err := buildUserRecord(bootstrapUsername, bootstrapPassword, "admin", nil)
if err != nil {
return err
}
s.users[record.ID] = record
return s.saveLocked()
}
func (s *userStore) loadLocked() error {
if s.path == "" {
return errors.New("users file path is empty")
}
data, err := os.ReadFile(s.path)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
if len(strings.TrimSpace(string(data))) == 0 {
return nil
}
var file userFile
if err := json.Unmarshal(data, &file); err != nil {
return fmt.Errorf("failed to parse users file: %w", err)
}
s.users = make(map[string]userRecord, len(file.Users))
for _, record := range file.Users {
if record.ID == "" || record.Username == "" || record.PasswordHash == "" || record.Role == "" {
continue
}
record.PrinterGrants = normalizePrinterGrants(record.PrinterGrants)
s.users[record.ID] = record
}
return nil
}
func (s *userStore) saveLocked() error {
if err := os.MkdirAll(filepath.Dir(s.path), 0o755); err != nil {
return err
}
file := userFile{Users: make([]userRecord, 0, len(s.users))}
for _, record := range s.users {
file.Users = append(file.Users, record)
}
sort.Slice(file.Users, func(i, j int) bool {
if file.Users[i].Role != file.Users[j].Role {
return file.Users[i].Role > file.Users[j].Role
}
return strings.ToLower(file.Users[i].Username) < strings.ToLower(file.Users[j].Username)
})
encoded, err := json.MarshalIndent(file, "", " ")
if err != nil {
return err
}
encoded = append(encoded, '\n')
return os.WriteFile(s.path, encoded, 0o600)
}
func (s *userStore) authenticate(username string, password string) (publicUser, bool, error) {
s.mu.RLock()
defer s.mu.RUnlock()
username = strings.TrimSpace(username)
if username == "" || password == "" {
return publicUser{}, false, nil
}
for _, record := range s.users {
if record.Username != username {
continue
}
if err := bcrypt.CompareHashAndPassword([]byte(record.PasswordHash), []byte(password)); err != nil {
return publicUser{}, false, nil
}
return publicUser{
ID: record.ID,
Username: record.Username,
Role: record.Role,
PrinterGrants: append([]printerGrant(nil), record.PrinterGrants...),
CreatedAt: record.CreatedAt,
}, true, nil
}
return publicUser{}, false, nil
}
func (s *userStore) listPublic() []publicUser {
s.mu.RLock()
defer s.mu.RUnlock()
users := make([]publicUser, 0, len(s.users))
for _, record := range s.users {
users = append(users, publicUser{
ID: record.ID,
Username: record.Username,
Role: record.Role,
PrinterGrants: append([]printerGrant(nil), record.PrinterGrants...),
CreatedAt: record.CreatedAt,
})
}
sort.Slice(users, func(i, j int) bool {
if users[i].Role != users[j].Role {
return users[i].Role > users[j].Role
}
return strings.ToLower(users[i].Username) < strings.ToLower(users[j].Username)
})
return users
}
func (s *userStore) getByID(id string) (publicUser, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
record, ok := s.users[id]
if !ok {
return publicUser{}, false
}
return publicUser{
ID: record.ID,
Username: record.Username,
Role: record.Role,
PrinterGrants: append([]printerGrant(nil), record.PrinterGrants...),
CreatedAt: record.CreatedAt,
}, true
}
func (s *userStore) create(username string, password string, role string, grants []printerGrant) (publicUser, error) {
normalizedGrants, err := normalizePrinterGrantsStrict(grants)
if err != nil {
return publicUser{}, err
}
record, err := buildUserRecord(username, password, role, normalizedGrants)
if err != nil {
return publicUser{}, err
}
s.mu.Lock()
defer s.mu.Unlock()
for _, existing := range s.users {
if existing.Username == record.Username {
return publicUser{}, fmt.Errorf("username %q already exists", record.Username)
}
}
s.users[record.ID] = record
if err := s.saveLocked(); err != nil {
delete(s.users, record.ID)
return publicUser{}, err
}
return publicUser{
ID: record.ID,
Username: record.Username,
Role: record.Role,
PrinterGrants: append([]printerGrant(nil), record.PrinterGrants...),
CreatedAt: record.CreatedAt,
}, nil
}
func (s *userStore) update(id string, password string, role string, grants []printerGrant) (publicUser, error) {
s.mu.Lock()
defer s.mu.Unlock()
record, ok := s.users[id]
if !ok {
return publicUser{}, fmt.Errorf("user %q not found", id)
}
original := record
if password != "" {
hashed, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return publicUser{}, err
}
record.PasswordHash = string(hashed)
}
if role != "" {
role = normalizeRole(role)
if role == "" {
return publicUser{}, fmt.Errorf("invalid role %q", role)
}
if original.Role == "admin" && role != "admin" && s.adminCountLocked() <= 1 {
return publicUser{}, errors.New("cannot demote the last admin")
}
record.Role = role
}
if grants != nil {
normalizedGrants, err := normalizePrinterGrantsStrict(grants)
if err != nil {
return publicUser{}, err
}
record.PrinterGrants = normalizedGrants
}
s.users[id] = record
if err := s.saveLocked(); err != nil {
s.users[id] = original
return publicUser{}, err
}
return publicUser{
ID: record.ID,
Username: record.Username,
Role: record.Role,
PrinterGrants: append([]printerGrant(nil), record.PrinterGrants...),
CreatedAt: record.CreatedAt,
}, nil
}
func (s *userStore) changePassword(userID string, currentPassword string, newPassword string) error {
if len(newPassword) < 4 {
return errors.New("password must be at least 4 characters")
}
s.mu.Lock()
defer s.mu.Unlock()
record, ok := s.users[userID]
if !ok {
return fmt.Errorf("user %q not found", userID)
}
if err := bcrypt.CompareHashAndPassword([]byte(record.PasswordHash), []byte(currentPassword)); err != nil {
return errors.New("current password is incorrect")
}
hashed, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
if err != nil {
return err
}
original := record
record.PasswordHash = string(hashed)
s.users[userID] = record
if err := s.saveLocked(); err != nil {
s.users[userID] = original
return err
}
return nil
}
func (s *userStore) delete(id string, actorID string) error {
s.mu.Lock()
defer s.mu.Unlock()
record, ok := s.users[id]
if !ok {
return fmt.Errorf("user %q not found", id)
}
if id == actorID {
return errors.New("cannot delete the currently signed-in user")
}
if record.Role == "admin" && s.adminCountLocked() <= 1 {
return errors.New("cannot delete the last admin")
}
delete(s.users, id)
if err := s.saveLocked(); err != nil {
s.users[id] = record
return err
}
return nil
}
func (s *userStore) adminCountLocked() int {
count := 0
for _, record := range s.users {
if record.Role == "admin" {
count++
}
}
return count
}
func buildUserRecord(username string, password string, role string, grants []printerGrant) (userRecord, error) {
username = strings.TrimSpace(username)
if len(username) < 3 {
return userRecord{}, errors.New("username must be at least 3 characters")
}
if len(password) < 4 {
return userRecord{}, errors.New("password must be at least 4 characters")
}
role = normalizeRole(role)
if role == "" {
return userRecord{}, fmt.Errorf("invalid role %q", role)
}
hashed, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return userRecord{}, err
}
id, err := newID()
if err != nil {
return userRecord{}, err
}
return userRecord{
ID: id,
Username: username,
PasswordHash: string(hashed),
Role: role,
PrinterGrants: normalizePrinterGrants(grants),
CreatedAt: time.Now().UTC(),
}, nil
}
func normalizePrinterGrants(grants []printerGrant) []printerGrant {
if len(grants) == 0 {
return nil
}
seen := make(map[string]printerGrant)
for _, grant := range grants {
printerID := strings.TrimSpace(grant.PrinterID)
access := strings.ToLower(strings.TrimSpace(grant.Access))
if printerID == "" {
continue
}
switch access {
case "", "read", "viewer":
access = "read"
case "control", "operator", "write":
access = "control"
default:
continue
}
seen[printerID] = printerGrant{PrinterID: printerID, Access: access}
}
if len(seen) == 0 {
return nil
}
normalized := make([]printerGrant, 0, len(seen))
for _, grant := range seen {
normalized = append(normalized, grant)
}
sort.Slice(normalized, func(i, j int) bool {
return strings.ToLower(normalized[i].PrinterID) < strings.ToLower(normalized[j].PrinterID)
})
return normalized
}
func normalizePrinterGrantsStrict(grants []printerGrant) ([]printerGrant, error) {
if len(grants) == 0 {
return nil, nil
}
seen := make(map[string]printerGrant)
for _, grant := range grants {
printerID := strings.TrimSpace(grant.PrinterID)
access := strings.ToLower(strings.TrimSpace(grant.Access))
if printerID == "" {
return nil, errors.New("printer grant requires a printer id")
}
switch access {
case "read", "control":
default:
return nil, fmt.Errorf("invalid printer access %q for %s", grant.Access, printerID)
}
seen[printerID] = printerGrant{PrinterID: printerID, Access: access}
}
normalized := make([]printerGrant, 0, len(seen))
for _, grant := range seen {
normalized = append(normalized, grant)
}
sort.Slice(normalized, func(i, j int) bool {
return strings.ToLower(normalized[i].PrinterID) < strings.ToLower(normalized[j].PrinterID)
})
return normalized, nil
}
func normalizeRole(role string) string {
switch strings.ToLower(strings.TrimSpace(role)) {
case "", "user":
return "user"
case "admin":
return "admin"
default:
return ""
}
}
func (s *userStore) canAccessPrinter(userID string, printerID string, control bool) bool {
s.mu.RLock()
defer s.mu.RUnlock()
record, ok := s.users[userID]
if !ok {
return false
}
if record.Role == "admin" {
return true
}
required := "read"
if control {
required = "control"
}
for _, grant := range record.PrinterGrants {
if grant.PrinterID != printerID {
continue
}
if grant.Access == "control" {
return true
}
if grant.Access == required {
return true
}
}
return false
}
func (s *userStore) printerAccessLevel(userID string, printerID string) string {
s.mu.RLock()
defer s.mu.RUnlock()
record, ok := s.users[userID]
if !ok {
return "none"
}
if record.Role == "admin" {
return "admin"
}
level := "none"
for _, grant := range record.PrinterGrants {
if grant.PrinterID != printerID {
continue
}
switch grant.Access {
case "control":
return "control"
case "read":
level = "read"
}
}
return level
}
func (s *userStore) visiblePrinters(userID string, all []string) []string {
s.mu.RLock()
defer s.mu.RUnlock()
record, ok := s.users[userID]
if !ok {
return nil
}
if record.Role == "admin" {
return append([]string(nil), all...)
}
allowed := make([]string, 0, len(all))
for _, printerID := range all {
for _, grant := range record.PrinterGrants {
if grant.PrinterID == printerID {
allowed = append(allowed, printerID)
break
}
}
}
return allowed
}