favoritter/internal/middleware/context.go
Ole-Morten Duesund 1fc42bf1b2 feat: add packaging, deployment, error pages, and project docs
Phase 7 — Polish:
- Error page template with styled 404/403/500 pages
- Error rendering helper on Renderer

Phase 8 — Packaging & Deployment:
- Containerfile: multi-stage build, non-root user, health check,
  OCI labels with build date and git revision
- Makefile: build, test, cross-compile, deb, rpm, container,
  tarballs, checksums targets
- nfpm.yaml: .deb and .rpm package config
- systemd service: hardened with NoNewPrivileges, ProtectSystem,
  ProtectHome, PrivateTmp, RestrictSUIDSGID
- Default environment file with commented examples
- postinstall/preremove scripts (shellcheck validated)
- compose.yaml: example Podman/Docker Compose
- Caddyfile.example: subdomain, subpath, and remote proxy configs
- CHANGELOG.md for release notes
- CLAUDE.md with architecture, conventions, and quick reference

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 16:34:32 +02:00

62 lines
1.6 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package middleware
import (
"context"
"net/http"
"kode.naiv.no/olemd/favoritter/internal/model"
)
type contextKey string
const (
userKey contextKey = "user"
csrfTokenKey contextKey = "csrf_token"
realIPKey contextKey = "real_ip"
)
// UserFromContext returns the authenticated user from the request context, or nil.
func UserFromContext(ctx context.Context) *model.User {
u, _ := ctx.Value(userKey).(*model.User)
return u
}
// CSRFTokenFromContext returns the CSRF token from the request context.
func CSRFTokenFromContext(ctx context.Context) string {
s, _ := ctx.Value(csrfTokenKey).(string)
return s
}
// RealIPFromContext returns the real client IP from the request context.
func RealIPFromContext(ctx context.Context) string {
s, _ := ctx.Value(realIPKey).(string)
return s
}
// RequireLogin redirects to the login page if no user is authenticated.
func RequireLogin(basePath string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if UserFromContext(r.Context()) == nil {
http.Redirect(w, r, basePath+"/login", http.StatusSeeOther)
return
}
next.ServeHTTP(w, r)
})
}
}
// RequireAdmin returns 403 if the user is not an admin.
func RequireAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := UserFromContext(r.Context())
if user == nil || !user.IsAdmin() {
w.WriteHeader(http.StatusForbidden)
w.Write([]byte("Forbidden"))
return
}
next.ServeHTTP(w, r)
})
}