refactor: replace can_upload boolean with role-based access control

Introduces a three-tier role hierarchy: reader < uploader < admin.

- internal/users/role.go: Role type, roleLevel map, AtLeast(min),
  ParseRole() — new roles added by inserting into roleLevel only
- internal/users/store.go: versioned migrations via _schema_version table;
  v2 migration adds 'role' column and migrates existing can_upload data;
  SetRole() replaces SetUpload(); Session carries Role instead of CanUpload
- internal/web/middleware.go: generic requireRole(minRole) middleware
  replaces the ad-hoc requireUpload
- internal/web/handlers.go: upload routes use requireRole(RoleUploader);
  listBooks derives canUpload from sess.Role.AtLeast(RoleUploader)
- cmd/admin/main.go: user add --role <reader|uploader|admin>,
  user set-role replaces user set-upload
- README, copilot-instructions updated

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
2026-08-11 19:43:39 +02:00
co-authored by Copilot
parent a66c370de4
commit 817763887a
7 changed files with 201 additions and 107 deletions
+21 -9
View File
@@ -22,10 +22,10 @@ go run ./cmd/server # run dev server on :8080
## Admin CLI ## Admin CLI
```bash ```bash
go run ./cmd/admin user add <name> [--upload] # Benutzer anlegen go run ./cmd/admin user add <name> [--role reader|uploader|admin] # Standard: reader
go run ./cmd/admin user list # alle Benutzer go run ./cmd/admin user list
go run ./cmd/admin user delete <name> # löschen go run ./cmd/admin user delete <name>
go run ./cmd/admin user set-upload <name> <true|false> go run ./cmd/admin user set-role <name> <reader|uploader|admin>
``` ```
## Architecture ## Architecture
@@ -33,11 +33,23 @@ go run ./cmd/admin user set-upload <name> <true|false>
- `cmd/server/main.go` — entrypoint; wires `library.Service`, `users.Store` and - `cmd/server/main.go` — entrypoint; wires `library.Service`, `users.Store` and
`web.Handler` together and starts the HTTP server. `web.Handler` together and starts the HTTP server.
- `internal/library` — core domain logic, no HTTP dependency (unchanged). - `internal/library` — core domain logic, no HTTP dependency (unchanged).
- `internal/users/store.go`SQLite-backed user store (`modernc.org/sqlite`, - `internal/users/role.go``Role` type (`reader`, `uploader`, `admin`),
pure Go driver). Tables: `users` (id, username, password_hash bcrypt, `roleLevel` map für Hierarchie, `AtLeast(min Role)`, `ParseRole(s)`.
can_upload), `sessions` (token, user_id FK, expires_at unix timestamp). Neue Rollen: in `roleLevel` eintragen und ggf. Routen anpassen — kein
Sessions TTL = 30 days. Key methods: `Authenticate`, `CreateSession`, Schema-Change nötig.
`LookupSession`, `DeleteSession`, `CreateUser`, `SetUpload`, `DeleteUser`, `ListUsers`. - `internal/users/store.go` — SQLite-backed user store. Migrations via
`_schema_version`-Tabelle (geordnete `migrations [][]string`); neue
Migrationen am Ende anhängen. `role TEXT` statt `can_upload INTEGER`.
- `internal/web/middleware.go``requireRole(minRole users.Role)` ist die
zentrale Middleware; `requireAuth` ist ein Spezialfall davon (implizit
`RoleReader`).
- Auth: `/login` und `/static/` sind die einzigen öffentlichen Routes.
Upload-Routes verwenden `requireRole(RoleUploader)`.
**Rollen-Hierarchie:**
```
reader (0) < uploader (1) < admin (2)
```
- `cmd/admin/main.go` — CLI binary for user management; reads `USERS_DB` env var. - `cmd/admin/main.go` — CLI binary for user management; reads `USERS_DB` env var.
- `internal/web/handlers.go` — HTTP handlers including `loginPage`, - `internal/web/handlers.go` — HTTP handlers including `loginPage`,
`loginSubmit`, `logout`, `uploadPage`, `uploadSubmit`. `loginSubmit`, `logout`, `uploadPage`, `uploadSubmit`.
+4 -2
View File
@@ -65,11 +65,13 @@ Alternativ können Benutzer mit Upload-Recht Bücher direkt im Browser hochladen
## Benutzerverwaltung (CLI) ## Benutzerverwaltung (CLI)
Rollen (aufsteigend): `reader``uploader``admin`
```bash ```bash
go run ./cmd/admin user add <name> [--role reader|uploader|admin]
go run ./cmd/admin user list go run ./cmd/admin user list
go run ./cmd/admin user add <name> [--upload]
go run ./cmd/admin user delete <name> go run ./cmd/admin user delete <name>
go run ./cmd/admin user set-upload <name> <true|false> go run ./cmd/admin user set-role <name> <reader|uploader|admin>
``` ```
## Konfiguration ## Konfiguration
+32 -25
View File
@@ -3,7 +3,6 @@ package main
import ( import (
"fmt" "fmt"
"os" "os"
"strconv"
"strings" "strings"
"syscall" "syscall"
@@ -40,10 +39,20 @@ func handleUser(store *users.Store, action string, args []string) {
switch action { switch action {
case "add": case "add":
if len(args) < 1 { if len(args) < 1 {
fatalf("usage: user add <username> [--upload]\n") fatalf("usage: user add <username> [--role reader|uploader|admin]\n")
} }
username := args[0] username := args[0]
canUpload := len(args) > 1 && args[1] == "--upload" role := users.RoleReader
if len(args) > 1 && args[1] == "--role" {
if len(args) < 3 {
fatalf("--role erwartet einen Wert: reader, uploader oder admin\n")
}
r, err := users.ParseRole(args[2])
if err != nil {
fatalf("%v\n", err)
}
role = r
}
password, err := readPassword(fmt.Sprintf("Passwort für '%s': ", username)) password, err := readPassword(fmt.Sprintf("Passwort für '%s': ", username))
if err != nil { if err != nil {
@@ -57,11 +66,11 @@ func handleUser(store *users.Store, action string, args []string) {
fatalf("Passwörter stimmen nicht überein.\n") fatalf("Passwörter stimmen nicht überein.\n")
} }
u, err := store.CreateUser(username, password, canUpload) u, err := store.CreateUser(username, password, role)
if err != nil { if err != nil {
fatalf("user anlegen: %v\n", err) fatalf("user anlegen: %v\n", err)
} }
fmt.Printf("✓ Benutzer '%s' angelegt (upload: %s)\n", u.Username, yesNo(u.CanUpload)) fmt.Printf("✓ Benutzer '%s' angelegt (rolle: %s)\n", u.Username, u.Role)
case "list": case "list":
list, err := store.ListUsers() list, err := store.ListUsers()
@@ -72,10 +81,10 @@ func handleUser(store *users.Store, action string, args []string) {
fmt.Println("Keine Benutzer vorhanden.") fmt.Println("Keine Benutzer vorhanden.")
return return
} }
fmt.Printf("%-20s %s\n", "BENUTZERNAME", "UPLOAD") fmt.Printf("%-20s %s\n", "BENUTZERNAME", "ROLLE")
fmt.Println(strings.Repeat("-", 32)) fmt.Println(strings.Repeat("-", 32))
for _, u := range list { for _, u := range list {
fmt.Printf("%-20s %s\n", u.Username, yesNo(u.CanUpload)) fmt.Printf("%-20s %s\n", u.Username, u.Role)
} }
case "delete": case "delete":
@@ -87,18 +96,18 @@ func handleUser(store *users.Store, action string, args []string) {
} }
fmt.Printf("✓ Benutzer '%s' gelöscht.\n", args[0]) fmt.Printf("✓ Benutzer '%s' gelöscht.\n", args[0])
case "set-upload": case "set-role":
if len(args) < 2 { if len(args) < 2 {
fatalf("usage: user set-upload <username> <true|false>\n") fatalf("usage: user set-role <username> <reader|uploader|admin>\n")
} }
val, err := strconv.ParseBool(args[1]) role, err := users.ParseRole(args[1])
if err != nil { if err != nil {
fatalf("ungültiger Wert '%s', erwartet true oder false\n", args[1]) fatalf("%v\n", err)
} }
if err := store.SetUpload(args[0], val); err != nil { if err := store.SetRole(args[0], role); err != nil {
fatalf("upload-recht setzen: %v\n", err) fatalf("rolle setzen: %v\n", err)
} }
fmt.Printf("✓ Upload-Recht für '%s' auf %s gesetzt.\n", args[0], yesNo(val)) fmt.Printf("✓ Rolle für '%s' auf '%s' gesetzt.\n", args[0], role)
default: default:
usage() usage()
@@ -116,13 +125,6 @@ func readPassword(prompt string) (string, error) {
return string(b), nil return string(b), nil
} }
func yesNo(b bool) string {
if b {
return "ja"
}
return "nein"
}
func getenv(key, fallback string) string { func getenv(key, fallback string) string {
if v := os.Getenv(key); v != "" { if v := os.Getenv(key); v != "" {
return v return v
@@ -138,11 +140,16 @@ func fatalf(format string, args ...any) {
func usage() { func usage() {
fmt.Fprintln(os.Stderr, `ebooks-admin Benutzerverwaltung fmt.Fprintln(os.Stderr, `ebooks-admin Benutzerverwaltung
Rollen (aufsteigend):
reader Lesen und Herunterladen
uploader Zusätzlich: Bücher hochladen
admin Alle Rechte
Befehle: Befehle:
user add <name> [--upload] Benutzer anlegen (optional: Upload-Recht) user add <name> [--role reader|uploader|admin] Benutzer anlegen (Standard: reader)
user list Alle Benutzer auflisten user list Alle Benutzer auflisten
user delete <name> Benutzer löschen user delete <name> Benutzer löschen
user set-upload <name> <true|false> Upload-Recht ändern user set-role <name> <reader|uploader|admin> Rolle ändern
Umgebungsvariablen: Umgebungsvariablen:
USERS_DB Pfad zur SQLite-Datenbank (Standard: users.db)`) USERS_DB Pfad zur SQLite-Datenbank (Standard: users.db)`)
+43
View File
@@ -0,0 +1,43 @@
package users
import "fmt"
// Role represents a user's access level. Roles are ordered hierarchically:
// RoleReader < RoleUploader < RoleAdmin.
// New roles can be inserted into roleLevel without changing existing code.
type Role string
const (
RoleReader Role = "reader"
RoleUploader Role = "uploader"
RoleAdmin Role = "admin"
)
// roleLevel defines the hierarchy. Higher = more permissions.
var roleLevel = map[Role]int{
RoleReader: 0,
RoleUploader: 1,
RoleAdmin: 2,
}
// AtLeast reports whether r has at least the same privilege level as min.
func (r Role) AtLeast(min Role) bool {
return roleLevel[r] >= roleLevel[min]
}
// IsValid reports whether r is a known role.
func (r Role) IsValid() bool {
_, ok := roleLevel[r]
return ok
}
func (r Role) String() string { return string(r) }
// ParseRole parses a role string. Returns an error for unknown values.
func ParseRole(s string) (Role, error) {
r := Role(s)
if !r.IsValid() {
return "", fmt.Errorf("unbekannte Rolle %q, gültig: reader, uploader, admin", s)
}
return r, nil
}
+90 -62
View File
@@ -6,26 +6,27 @@ import (
"encoding/hex" "encoding/hex"
"errors" "errors"
"fmt" "fmt"
"strings"
"time" "time"
_ "modernc.org/sqlite"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
_ "modernc.org/sqlite"
) )
var ErrNotFound = errors.New("user not found") var ErrNotFound = errors.New("user not found")
var ErrUserExists = errors.New("user already exists") var ErrUserExists = errors.New("user already exists")
type User struct { type User struct {
ID int64 ID int64
Username string Username string
CanUpload bool Role Role
} }
type Session struct { type Session struct {
Token string Token string
UserID int64 UserID int64
Username string Username string
CanUpload bool Role Role
ExpiresAt time.Time ExpiresAt time.Time
} }
@@ -49,32 +50,80 @@ func Open(path string) (*Store, error) {
func (s *Store) Close() error { return s.db.Close() } func (s *Store) Close() error { return s.db.Close() }
func (s *Store) migrate() error { // migrations is an ordered list of schema changes. Each entry is a slice of
_, err := s.db.Exec(` // SQL statements to execute in a transaction. Add new entries at the end only.
CREATE TABLE IF NOT EXISTS users ( var migrations = [][]string{
// v1: initial schema
{
`CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE, username TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL, password_hash TEXT NOT NULL,
can_upload INTEGER NOT NULL DEFAULT 0 can_upload INTEGER NOT NULL DEFAULT 0
); )`,
CREATE TABLE IF NOT EXISTS sessions ( `CREATE TABLE IF NOT EXISTS sessions (
token TEXT PRIMARY KEY, token TEXT PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
expires_at INTEGER NOT NULL expires_at INTEGER NOT NULL
); )`,
`) },
return err // v2: replace can_upload with role column; migrate existing data
{
`ALTER TABLE users ADD COLUMN role TEXT NOT NULL DEFAULT 'reader'`,
`UPDATE users SET role = CASE WHEN can_upload = 1 THEN 'uploader' ELSE 'reader' END`,
},
} }
// CreateUser adds a new user. Returns ErrUserExists if the username is taken. func (s *Store) migrate() error {
func (s *Store) CreateUser(username, password string, canUpload bool) (*User, error) { if _, err := s.db.Exec(
`CREATE TABLE IF NOT EXISTS _schema_version (version INTEGER NOT NULL)`,
); err != nil {
return err
}
var version int
if err := s.db.QueryRow(
`SELECT COALESCE(MAX(version), 0) FROM _schema_version`,
).Scan(&version); err != nil {
return err
}
for i, stmts := range migrations {
v := i + 1
if v <= version {
continue
}
tx, err := s.db.Begin()
if err != nil {
return err
}
for _, stmt := range stmts {
if _, err := tx.Exec(stmt); err != nil {
_ = tx.Rollback()
return fmt.Errorf("migration %d: %w", v, err)
}
}
if _, err := tx.Exec(`INSERT INTO _schema_version (version) VALUES (?)`, v); err != nil {
_ = tx.Rollback()
return err
}
if err := tx.Commit(); err != nil {
return err
}
}
return nil
}
// CreateUser adds a new user with the given role. Returns ErrUserExists if the
// username is already taken.
func (s *Store) CreateUser(username, password string, role Role) (*User, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil { if err != nil {
return nil, err return nil, err
} }
res, err := s.db.Exec( res, err := s.db.Exec(
`INSERT INTO users (username, password_hash, can_upload) VALUES (?, ?, ?)`, `INSERT INTO users (username, password_hash, role) VALUES (?, ?, ?)`,
username, string(hash), boolToInt(canUpload), username, string(hash), role,
) )
if err != nil { if err != nil {
if isUnique(err) { if isUnique(err) {
@@ -83,14 +132,14 @@ func (s *Store) CreateUser(username, password string, canUpload bool) (*User, er
return nil, err return nil, err
} }
id, _ := res.LastInsertId() id, _ := res.LastInsertId()
return &User{ID: id, Username: username, CanUpload: canUpload}, nil return &User{ID: id, Username: username, Role: role}, nil
} }
// SetUpload changes the upload permission of an existing user. // SetRole changes the role of an existing user.
func (s *Store) SetUpload(username string, canUpload bool) error { func (s *Store) SetRole(username string, role Role) error {
res, err := s.db.Exec( res, err := s.db.Exec(
`UPDATE users SET can_upload = ? WHERE username = ?`, `UPDATE users SET role = ? WHERE username = ?`,
boolToInt(canUpload), username, role, username,
) )
if err != nil { if err != nil {
return err return err
@@ -115,7 +164,7 @@ func (s *Store) DeleteUser(username string) error {
// ListUsers returns all users ordered by username. // ListUsers returns all users ordered by username.
func (s *Store) ListUsers() ([]User, error) { func (s *Store) ListUsers() ([]User, error) {
rows, err := s.db.Query(`SELECT id, username, can_upload FROM users ORDER BY username`) rows, err := s.db.Query(`SELECT id, username, role FROM users ORDER BY username`)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -124,25 +173,25 @@ func (s *Store) ListUsers() ([]User, error) {
var users []User var users []User
for rows.Next() { for rows.Next() {
var u User var u User
var up int var roleStr string
if err := rows.Scan(&u.ID, &u.Username, &up); err != nil { if err := rows.Scan(&u.ID, &u.Username, &roleStr); err != nil {
return nil, err return nil, err
} }
u.CanUpload = up != 0 u.Role = Role(roleStr)
users = append(users, u) users = append(users, u)
} }
return users, rows.Err() return users, rows.Err()
} }
// Authenticate verifies credentials and returns the matching user. // Authenticate verifies credentials and returns the matching user, or nil on
// wrong username/password.
func (s *Store) Authenticate(username, password string) (*User, error) { func (s *Store) Authenticate(username, password string) (*User, error) {
var u User var u User
var hash string var hash, roleStr string
var up int
err := s.db.QueryRow( err := s.db.QueryRow(
`SELECT id, username, password_hash, can_upload FROM users WHERE username = ?`, `SELECT id, username, password_hash, role FROM users WHERE username = ?`,
username, username,
).Scan(&u.ID, &u.Username, &hash, &up) ).Scan(&u.ID, &u.Username, &hash, &roleStr)
if errors.Is(err, sql.ErrNoRows) { if errors.Is(err, sql.ErrNoRows) {
return nil, nil return nil, nil
} }
@@ -152,7 +201,7 @@ func (s *Store) Authenticate(username, password string) (*User, error) {
if bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) != nil { if bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) != nil {
return nil, nil return nil, nil
} }
u.CanUpload = up != 0 u.Role = Role(roleStr)
return &u, nil return &u, nil
} }
@@ -163,32 +212,31 @@ func (s *Store) CreateSession(u *User) (*Session, error) {
return nil, err return nil, err
} }
exp := time.Now().Add(30 * 24 * time.Hour) exp := time.Now().Add(30 * 24 * time.Hour)
_, err = s.db.Exec( if _, err = s.db.Exec(
`INSERT INTO sessions (token, user_id, expires_at) VALUES (?, ?, ?)`, `INSERT INTO sessions (token, user_id, expires_at) VALUES (?, ?, ?)`,
token, u.ID, exp.Unix(), token, u.ID, exp.Unix(),
) ); err != nil {
if err != nil {
return nil, err return nil, err
} }
return &Session{ return &Session{
Token: token, Token: token,
UserID: u.ID, UserID: u.ID,
Username: u.Username, Username: u.Username,
CanUpload: u.CanUpload, Role: u.Role,
ExpiresAt: exp, ExpiresAt: exp,
}, nil }, nil
} }
// LookupSession returns the session if valid, nil if not found/expired. // LookupSession returns the session if valid, nil if not found or expired.
func (s *Store) LookupSession(token string) (*Session, error) { func (s *Store) LookupSession(token string) (*Session, error) {
var sess Session var sess Session
var up int var roleStr string
var expUnix int64 var expUnix int64
err := s.db.QueryRow(` err := s.db.QueryRow(`
SELECT s.token, s.user_id, u.username, u.can_upload, s.expires_at SELECT s.token, s.user_id, u.username, u.role, s.expires_at
FROM sessions s JOIN users u ON u.id = s.user_id FROM sessions s JOIN users u ON u.id = s.user_id
WHERE s.token = ? WHERE s.token = ?
`, token).Scan(&sess.Token, &sess.UserID, &sess.Username, &up, &expUnix) `, token).Scan(&sess.Token, &sess.UserID, &sess.Username, &roleStr, &expUnix)
if errors.Is(err, sql.ErrNoRows) { if errors.Is(err, sql.ErrNoRows) {
return nil, nil return nil, nil
} }
@@ -200,7 +248,7 @@ func (s *Store) LookupSession(token string) (*Session, error) {
_, _ = s.db.Exec(`DELETE FROM sessions WHERE token = ?`, token) _, _ = s.db.Exec(`DELETE FROM sessions WHERE token = ?`, token)
return nil, nil return nil, nil
} }
sess.CanUpload = up != 0 sess.Role = Role(roleStr)
return &sess, nil return &sess, nil
} }
@@ -218,26 +266,6 @@ func randomToken() (string, error) {
return hex.EncodeToString(b), nil return hex.EncodeToString(b), nil
} }
func boolToInt(b bool) int {
if b {
return 1
}
return 0
}
func isUnique(err error) bool { func isUnique(err error) bool {
return err != nil && (contains(err.Error(), "UNIQUE") || contains(err.Error(), "unique")) return err != nil && strings.Contains(strings.ToLower(err.Error()), "unique")
}
func contains(s, sub string) bool {
return len(s) >= len(sub) && (s == sub || len(s) > 0 && containsStr(s, sub))
}
func containsStr(s, sub string) bool {
for i := 0; i+len(sub) <= len(s); i++ {
if s[i:i+len(sub)] == sub {
return true
}
}
return false
} }
+5 -5
View File
@@ -34,15 +34,15 @@ func (h *Handler) RegisterRoutes(mux *http.ServeMux) {
mux.HandleFunc("POST /logout", h.logout) mux.HandleFunc("POST /logout", h.logout)
mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
// Authenticated // Authenticated (any role)
mux.HandleFunc("GET /", h.requireAuth(h.listBooks)) mux.HandleFunc("GET /", h.requireAuth(h.listBooks))
mux.HandleFunc("GET /book/{id}", h.requireAuth(h.bookDetails)) mux.HandleFunc("GET /book/{id}", h.requireAuth(h.bookDetails))
mux.HandleFunc("GET /download/{id}", h.requireAuth(h.downloadBook)) mux.HandleFunc("GET /download/{id}", h.requireAuth(h.downloadBook))
mux.HandleFunc("GET /cover/{id}", h.requireAuth(h.bookCover)) mux.HandleFunc("GET /cover/{id}", h.requireAuth(h.bookCover))
// Upload (authenticated + can_upload) // Uploader and above
mux.HandleFunc("GET /upload", h.requireUpload(h.uploadPage)) mux.HandleFunc("GET /upload", h.requireRole(users.RoleUploader, h.uploadPage))
mux.HandleFunc("POST /upload", h.requireUpload(h.uploadSubmit)) mux.HandleFunc("POST /upload", h.requireRole(users.RoleUploader, h.uploadSubmit))
} }
func (h *Handler) listBooks(w http.ResponseWriter, r *http.Request) { func (h *Handler) listBooks(w http.ResponseWriter, r *http.Request) {
@@ -52,7 +52,7 @@ func (h *Handler) listBooks(w http.ResponseWriter, r *http.Request) {
return return
} }
sess := sessionFrom(r) sess := sessionFrom(r)
canUpload := sess != nil && sess.CanUpload canUpload := sess != nil && sess.Role.AtLeast(users.RoleUploader)
render(w, r.Context(), views.IndexPage(books, canUpload)) render(w, r.Context(), views.IndexPage(books, canUpload))
} }
+6 -4
View File
@@ -17,7 +17,7 @@ func sessionFrom(r *http.Request) *users.Session {
return s return s
} }
// requireAuth is middleware that redirects unauthenticated requests to /login. // requireAuth redirects unauthenticated requests to /login.
func (h *Handler) requireAuth(next http.HandlerFunc) http.HandlerFunc { func (h *Handler) requireAuth(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
sess, err := h.sessionFromRequest(r) sess, err := h.sessionFromRequest(r)
@@ -30,11 +30,13 @@ func (h *Handler) requireAuth(next http.HandlerFunc) http.HandlerFunc {
} }
} }
// requireUpload is middleware that returns 403 if the user lacks upload permission. // requireRole returns middleware that allows access only to users whose role is
func (h *Handler) requireUpload(next http.HandlerFunc) http.HandlerFunc { // at least minRole. Unknown sessions are redirected to /login; insufficient
// role yields 403.
func (h *Handler) requireRole(minRole users.Role, next http.HandlerFunc) http.HandlerFunc {
return h.requireAuth(func(w http.ResponseWriter, r *http.Request) { return h.requireAuth(func(w http.ResponseWriter, r *http.Request) {
sess := sessionFrom(r) sess := sessionFrom(r)
if !sess.CanUpload { if !sess.Role.AtLeast(minRole) {
http.Error(w, "Keine Berechtigung", http.StatusForbidden) http.Error(w, "Keine Berechtigung", http.StatusForbidden)
return return
} }