107 lines
2.9 KiB
Go
107 lines
2.9 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
"net/http"
|
|
|
|
"git.arnef.de/arnef/nidus/internal/config"
|
|
"git.arnef.de/arnef/nidus/internal/db"
|
|
)
|
|
|
|
type contextKey string
|
|
|
|
const userContextKey contextKey = "authenticated_user"
|
|
|
|
// Middleware wraps an http.Handler with HTTP Basic Auth enforcement.
|
|
type Middleware struct {
|
|
cfg *config.Config
|
|
dbase *db.DB
|
|
logger *slog.Logger
|
|
}
|
|
|
|
func NewMiddleware(cfg *config.Config, dbase *db.DB, logger *slog.Logger) *Middleware {
|
|
return &Middleware{cfg: cfg, dbase: dbase, logger: logger}
|
|
}
|
|
|
|
// Wrap returns an http.Handler that requires valid Basic Auth credentials
|
|
// before delegating to next.
|
|
func (m *Middleware) Wrap(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
username, password, ok := r.BasicAuth()
|
|
if !ok {
|
|
m.challenge(w)
|
|
return
|
|
}
|
|
|
|
user, err := m.authenticate(username, password)
|
|
if err != nil {
|
|
m.logger.Warn("authentication failed",
|
|
"username", username,
|
|
"remote_addr", r.RemoteAddr,
|
|
"error", err)
|
|
m.challenge(w)
|
|
return
|
|
}
|
|
|
|
m.logger.Debug("authenticated request",
|
|
"username", username,
|
|
"method", r.Method,
|
|
"path", r.URL.Path)
|
|
|
|
ctx := context.WithValue(r.Context(), userContextKey, &Principal{
|
|
Username: username,
|
|
DisplayName: user.DisplayName,
|
|
Email: user.Email,
|
|
})
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
|
|
// challenge sends a 401 response requesting Basic Auth.
|
|
func (m *Middleware) challenge(w http.ResponseWriter) {
|
|
w.Header().Set("WWW-Authenticate", `Basic realm="`+m.cfg.Auth.Realm+`"`)
|
|
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
_, _ = w.Write([]byte("Unauthorized"))
|
|
}
|
|
|
|
// authenticate validates username/password against the database.
|
|
func (m *Middleware) authenticate(username, password string) (*db.User, error) {
|
|
user, err := m.dbase.GetUser(username)
|
|
if err != nil {
|
|
return nil, errUnauthorized
|
|
}
|
|
if !m.dbase.VerifyPassword(username, password) {
|
|
return nil, errUnauthorized
|
|
}
|
|
return user, nil
|
|
}
|
|
|
|
// Principal holds the authenticated user's identity.
|
|
type Principal struct {
|
|
Username string
|
|
DisplayName string
|
|
Email string
|
|
}
|
|
|
|
// FromContext extracts the Principal from a request context.
|
|
// Returns nil if the request was not authenticated.
|
|
func FromContext(ctx context.Context) *Principal {
|
|
p, _ := ctx.Value(userContextKey).(*Principal)
|
|
return p
|
|
}
|
|
|
|
// NewContext returns a copy of ctx carrying p, retrievable via FromContext.
|
|
// This is primarily useful for tests of downstream packages that need an
|
|
// authenticated context without going through the Basic Auth handshake.
|
|
func NewContext(ctx context.Context, p *Principal) context.Context {
|
|
return context.WithValue(ctx, userContextKey, p)
|
|
}
|
|
|
|
var errUnauthorized = &authError{msg: "invalid credentials"}
|
|
|
|
type authError struct{ msg string }
|
|
|
|
func (e *authError) Error() string { return e.msg }
|