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:
2026-08-11 19:11:40 +02:00
co-authored by Copilot
parent a8b31dae8a
commit a66c370de4
13 changed files with 1115 additions and 111 deletions
+137 -8
View File
@@ -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)
}
+51
View File
@@ -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)
}