feat: add authentication and book upload
- Session-based login (username/password, 30-day cookie) - SQLite user store with bcrypt password hashing (modernc.org/sqlite) - Per-user upload permission (can_upload flag) - Admin CLI (cmd/admin) for user management: user add/list/delete/set-upload - Upload handler for EPUB/PDF with path-traversal protection - All routes protected by requireAuth middleware; /upload additionally requires requireUpload - Login/logout UI, upload form, logout button in header - New env var: USERS_DB (default: users.db, gitignored) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,243 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
var ErrNotFound = errors.New("user not found")
|
||||
var ErrUserExists = errors.New("user already exists")
|
||||
|
||||
type User struct {
|
||||
ID int64
|
||||
Username string
|
||||
CanUpload bool
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
Token string
|
||||
UserID int64
|
||||
Username string
|
||||
CanUpload bool
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func Open(path string) (*Store, error) {
|
||||
db, err := sql.Open("sqlite", path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db.SetMaxOpenConns(1) // SQLite doesn't support concurrent writers
|
||||
s := &Store{db: db}
|
||||
if err := s.migrate(); err != nil {
|
||||
db.Close()
|
||||
return nil, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *Store) Close() error { return s.db.Close() }
|
||||
|
||||
func (s *Store) migrate() error {
|
||||
_, err := s.db.Exec(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
can_upload INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token TEXT PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
expires_at INTEGER NOT NULL
|
||||
);
|
||||
`)
|
||||
return err
|
||||
}
|
||||
|
||||
// CreateUser adds a new user. Returns ErrUserExists if the username is taken.
|
||||
func (s *Store) CreateUser(username, password string, canUpload bool) (*User, error) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res, err := s.db.Exec(
|
||||
`INSERT INTO users (username, password_hash, can_upload) VALUES (?, ?, ?)`,
|
||||
username, string(hash), boolToInt(canUpload),
|
||||
)
|
||||
if err != nil {
|
||||
if isUnique(err) {
|
||||
return nil, ErrUserExists
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
id, _ := res.LastInsertId()
|
||||
return &User{ID: id, Username: username, CanUpload: canUpload}, nil
|
||||
}
|
||||
|
||||
// SetUpload changes the upload permission of an existing user.
|
||||
func (s *Store) SetUpload(username string, canUpload bool) error {
|
||||
res, err := s.db.Exec(
|
||||
`UPDATE users SET can_upload = ? WHERE username = ?`,
|
||||
boolToInt(canUpload), username,
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteUser removes a user by username.
|
||||
func (s *Store) DeleteUser(username string) error {
|
||||
res, err := s.db.Exec(`DELETE FROM users WHERE username = ?`, username)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListUsers returns all users ordered by username.
|
||||
func (s *Store) ListUsers() ([]User, error) {
|
||||
rows, err := s.db.Query(`SELECT id, username, can_upload FROM users ORDER BY username`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var users []User
|
||||
for rows.Next() {
|
||||
var u User
|
||||
var up int
|
||||
if err := rows.Scan(&u.ID, &u.Username, &up); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
u.CanUpload = up != 0
|
||||
users = append(users, u)
|
||||
}
|
||||
return users, rows.Err()
|
||||
}
|
||||
|
||||
// Authenticate verifies credentials and returns the matching user.
|
||||
func (s *Store) Authenticate(username, password string) (*User, error) {
|
||||
var u User
|
||||
var hash string
|
||||
var up int
|
||||
err := s.db.QueryRow(
|
||||
`SELECT id, username, password_hash, can_upload FROM users WHERE username = ?`,
|
||||
username,
|
||||
).Scan(&u.ID, &u.Username, &hash, &up)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) != nil {
|
||||
return nil, nil
|
||||
}
|
||||
u.CanUpload = up != 0
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
// CreateSession issues a new session token for a user (TTL: 30 days).
|
||||
func (s *Store) CreateSession(u *User) (*Session, error) {
|
||||
token, err := randomToken()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
exp := time.Now().Add(30 * 24 * time.Hour)
|
||||
_, err = s.db.Exec(
|
||||
`INSERT INTO sessions (token, user_id, expires_at) VALUES (?, ?, ?)`,
|
||||
token, u.ID, exp.Unix(),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Session{
|
||||
Token: token,
|
||||
UserID: u.ID,
|
||||
Username: u.Username,
|
||||
CanUpload: u.CanUpload,
|
||||
ExpiresAt: exp,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// LookupSession returns the session if valid, nil if not found/expired.
|
||||
func (s *Store) LookupSession(token string) (*Session, error) {
|
||||
var sess Session
|
||||
var up int
|
||||
var expUnix int64
|
||||
err := s.db.QueryRow(`
|
||||
SELECT s.token, s.user_id, u.username, u.can_upload, s.expires_at
|
||||
FROM sessions s JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token = ?
|
||||
`, token).Scan(&sess.Token, &sess.UserID, &sess.Username, &up, &expUnix)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sess.ExpiresAt = time.Unix(expUnix, 0)
|
||||
if time.Now().After(sess.ExpiresAt) {
|
||||
_, _ = s.db.Exec(`DELETE FROM sessions WHERE token = ?`, token)
|
||||
return nil, nil
|
||||
}
|
||||
sess.CanUpload = up != 0
|
||||
return &sess, nil
|
||||
}
|
||||
|
||||
// DeleteSession invalidates a session token (logout).
|
||||
func (s *Store) DeleteSession(token string) error {
|
||||
_, err := s.db.Exec(`DELETE FROM sessions WHERE token = ?`, token)
|
||||
return err
|
||||
}
|
||||
|
||||
func randomToken() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", fmt.Errorf("random token: %w", err)
|
||||
}
|
||||
return hex.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
func boolToInt(b bool) int {
|
||||
if b {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func isUnique(err error) bool {
|
||||
return err != nil && (contains(err.Error(), "UNIQUE") || contains(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
|
||||
}
|
||||
+137
-8
@@ -3,29 +3,46 @@ package web
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/a-h/templ"
|
||||
"github.com/arnef/ebooks/internal/library"
|
||||
"github.com/arnef/ebooks/internal/users"
|
||||
"github.com/arnef/ebooks/views"
|
||||
)
|
||||
|
||||
const maxUploadBytes = 512 << 20 // 512 MiB
|
||||
|
||||
type Handler struct {
|
||||
lib *library.Service
|
||||
lib *library.Service
|
||||
store *users.Store
|
||||
}
|
||||
|
||||
func NewHandler(lib *library.Service) *Handler {
|
||||
return &Handler{lib: lib}
|
||||
func NewHandler(lib *library.Service, store *users.Store) *Handler {
|
||||
return &Handler{lib: lib, store: store}
|
||||
}
|
||||
|
||||
func (h *Handler) RegisterRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /", h.listBooks)
|
||||
mux.HandleFunc("GET /book/{id}", h.bookDetails)
|
||||
mux.HandleFunc("GET /download/{id}", h.downloadBook)
|
||||
mux.HandleFunc("GET /cover/{id}", h.bookCover)
|
||||
// Public
|
||||
mux.HandleFunc("GET /login", h.loginPage)
|
||||
mux.HandleFunc("POST /login", h.loginSubmit)
|
||||
mux.HandleFunc("POST /logout", h.logout)
|
||||
mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
|
||||
|
||||
// Authenticated
|
||||
mux.HandleFunc("GET /", h.requireAuth(h.listBooks))
|
||||
mux.HandleFunc("GET /book/{id}", h.requireAuth(h.bookDetails))
|
||||
mux.HandleFunc("GET /download/{id}", h.requireAuth(h.downloadBook))
|
||||
mux.HandleFunc("GET /cover/{id}", h.requireAuth(h.bookCover))
|
||||
|
||||
// Upload (authenticated + can_upload)
|
||||
mux.HandleFunc("GET /upload", h.requireUpload(h.uploadPage))
|
||||
mux.HandleFunc("POST /upload", h.requireUpload(h.uploadSubmit))
|
||||
}
|
||||
|
||||
func (h *Handler) listBooks(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -34,7 +51,9 @@ func (h *Handler) listBooks(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "failed to load books", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
render(w, r.Context(), views.IndexPage(books))
|
||||
sess := sessionFrom(r)
|
||||
canUpload := sess != nil && sess.CanUpload
|
||||
render(w, r.Context(), views.IndexPage(books, canUpload))
|
||||
}
|
||||
|
||||
func (h *Handler) bookDetails(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -116,3 +135,113 @@ func render(w http.ResponseWriter, ctx context.Context, c templ.Component) {
|
||||
http.Error(w, "render failed", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Auth handlers ---
|
||||
|
||||
func (h *Handler) loginPage(w http.ResponseWriter, r *http.Request) {
|
||||
render(w, r.Context(), views.LoginPage(""))
|
||||
}
|
||||
|
||||
func (h *Handler) loginSubmit(w http.ResponseWriter, r *http.Request) {
|
||||
username := r.FormValue("username")
|
||||
password := r.FormValue("password")
|
||||
|
||||
user, err := h.store.Authenticate(username, password)
|
||||
if err != nil {
|
||||
http.Error(w, "interner Fehler", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if user == nil {
|
||||
render(w, r.Context(), views.LoginPage("Benutzername oder Passwort falsch."))
|
||||
return
|
||||
}
|
||||
|
||||
sess, err := h.store.CreateSession(user)
|
||||
if err != nil {
|
||||
http.Error(w, "Session konnte nicht erstellt werden", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "session",
|
||||
Value: sess.Token,
|
||||
Path: "/",
|
||||
Expires: sess.ExpiresAt,
|
||||
HttpOnly: true,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
})
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func (h *Handler) logout(w http.ResponseWriter, r *http.Request) {
|
||||
cookie, err := r.Cookie("session")
|
||||
if err == nil {
|
||||
_ = h.store.DeleteSession(cookie.Value)
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: "session",
|
||||
Value: "",
|
||||
Path: "/",
|
||||
MaxAge: -1,
|
||||
HttpOnly: true,
|
||||
})
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
// --- Upload handlers ---
|
||||
|
||||
func (h *Handler) uploadPage(w http.ResponseWriter, r *http.Request) {
|
||||
render(w, r.Context(), views.UploadPage(""))
|
||||
}
|
||||
|
||||
func (h *Handler) uploadSubmit(w http.ResponseWriter, r *http.Request) {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxUploadBytes)
|
||||
if err := r.ParseMultipartForm(32 << 20); err != nil {
|
||||
render(w, r.Context(), views.UploadPage("Datei zu groß oder ungültige Anfrage."))
|
||||
return
|
||||
}
|
||||
|
||||
file, header, err := r.FormFile("book")
|
||||
if err != nil {
|
||||
render(w, r.Context(), views.UploadPage("Keine Datei ausgewählt."))
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
ext := strings.ToLower(filepath.Ext(header.Filename))
|
||||
if ext != ".epub" && ext != ".pdf" {
|
||||
render(w, r.Context(), views.UploadPage("Nur EPUB- und PDF-Dateien erlaubt."))
|
||||
return
|
||||
}
|
||||
|
||||
// Sanitize filename: keep only base name, no path components.
|
||||
safeFilename := filepath.Base(header.Filename)
|
||||
destPath := filepath.Join(h.lib.BooksDir(), safeFilename)
|
||||
|
||||
// Check it still resolves inside BooksDir.
|
||||
cleanBase := filepath.Clean(h.lib.BooksDir())
|
||||
cleanDest := filepath.Clean(destPath)
|
||||
if !strings.HasPrefix(cleanDest, cleanBase+string(filepath.Separator)) {
|
||||
render(w, r.Context(), views.UploadPage("Ungültiger Dateiname."))
|
||||
return
|
||||
}
|
||||
|
||||
out, err := os.OpenFile(destPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
|
||||
if err != nil {
|
||||
if os.IsExist(err) {
|
||||
render(w, r.Context(), views.UploadPage(fmt.Sprintf("Datei '%s' existiert bereits.", safeFilename)))
|
||||
return
|
||||
}
|
||||
http.Error(w, "Datei konnte nicht gespeichert werden", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
if _, err := io.Copy(out, file); err != nil {
|
||||
_ = os.Remove(destPath)
|
||||
http.Error(w, "Upload fehlgeschlagen", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/arnef/ebooks/internal/users"
|
||||
)
|
||||
|
||||
type contextKey int
|
||||
|
||||
const sessionKey contextKey = iota
|
||||
|
||||
// sessionFrom retrieves the session stored in request context.
|
||||
func sessionFrom(r *http.Request) *users.Session {
|
||||
s, _ := r.Context().Value(sessionKey).(*users.Session)
|
||||
return s
|
||||
}
|
||||
|
||||
// requireAuth is middleware that redirects unauthenticated requests to /login.
|
||||
func (h *Handler) requireAuth(next http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
sess, err := h.sessionFromRequest(r)
|
||||
if err != nil || sess == nil {
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), sessionKey, sess)
|
||||
next(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
// requireUpload is middleware that returns 403 if the user lacks upload permission.
|
||||
func (h *Handler) requireUpload(next http.HandlerFunc) http.HandlerFunc {
|
||||
return h.requireAuth(func(w http.ResponseWriter, r *http.Request) {
|
||||
sess := sessionFrom(r)
|
||||
if !sess.CanUpload {
|
||||
http.Error(w, "Keine Berechtigung", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) sessionFromRequest(r *http.Request) (*users.Session, error) {
|
||||
cookie, err := r.Cookie("session")
|
||||
if err != nil {
|
||||
return nil, nil
|
||||
}
|
||||
return h.store.LookupSession(cookie.Value)
|
||||
}
|
||||
Reference in New Issue
Block a user