Files
stpweb/backend/handlers/handle_auth.go
adamfandClaude Opus 5.5 4530cb8dc4
Test and deploy / test (push) Successful in 28s
Test and deploy / deploy (push) Successful in 31s
Trim comments to the non-obvious why
Drop narration, history and restated-code comments across the repo,
keep short ones for security boundaries, upstream quirks and ordering
constraints, and record the convention in CLAUDE.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 20:49:03 +00:00

282 lines
8.2 KiB
Go

package handlers
import (
"errors"
"log"
"net/http"
"adam-french.co.uk/backend/models"
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
)
// REST auth endpoints and middleware. GraphQL's login/logout/refresh live in
// graph/auth.resolvers.go; both mint cookies through services.Auth.
type UserCredentials struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
// AuthMiddleware requires a valid, unrevoked access token. It does not fall
// back to the refresh token: the client refreshes and retries on 401.
func (store *Store) AuthMiddleware(ctx *gin.Context) {
access_token, err := ctx.Cookie("access_token")
if err != nil {
ctx.AbortWithStatusJSON(401, gin.H{"error": "unauthorized"})
return
}
_, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, access_token)
if err != nil {
ctx.AbortWithStatusJSON(401, gin.H{"error": "unauthorized"})
return
}
// Gin context key; graph/context.go uses its own, separate mechanism.
ctx.Set("userClaims", claims)
ctx.Next()
}
// AdminMiddleware must follow AuthMiddleware. Admin comes from the token, so
// a revoked flag applies once the access token expires.
func (store *Store) AdminMiddleware(ctx *gin.Context) {
claims, exists := ctx.Get("userClaims")
if !exists {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
mapClaims, ok := claims.(*jwt.MapClaims)
if !ok {
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid claims"})
return
}
// Tokens minted before the admin claim have none: not an admin.
admin, ok := (*mapClaims)["admin"].(bool)
if !ok || !admin {
ctx.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "admin access required"})
return
}
ctx.Next()
}
// ValidateAdmin answers 200/403/401 with no body, for the SPA, Caddy's admin
// gate and the jobs container. It falls back to the refresh token and may
// mint new cookies, so a returning admin needn't log in again.
func (store *Store) ValidateAdmin(ctx *gin.Context) {
store.validateSession(ctx, func(user *models.User, claims *jwt.MapClaims) bool {
// The refresh path has no admin claim, so it reads the row.
if claims == nil {
return user.Admin
}
admin, ok := (*claims)["admin"].(bool)
return ok && admin
})
}
// ValidatePermission backs Caddy's permission gate, like ValidateAdmin but
// reading the user row. An unknown key is 404, so a typo in a Caddy route
// fails visibly rather than looking like a missing grant.
func (store *Store) ValidatePermission(ctx *gin.Context) {
key := ctx.Param("permission")
if !services.ValidPermission(key) {
ctx.Status(http.StatusNotFound)
return
}
store.validateSession(ctx, func(user *models.User, _ *jwt.MapClaims) bool {
return services.HasPermission(user, key)
})
}
// validateSession identifies the caller by access token, else refresh token
// (allow then gets nil claims), and answers 200/403/401. On 200 the username
// goes in X-Auth-User for Caddy to pass upstream.
func (store *Store) validateSession(ctx *gin.Context, allow func(*models.User, *jwt.MapClaims) bool) {
accessToken, err := ctx.Cookie("access_token")
if err == nil {
user, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, accessToken)
if err == nil {
if !allow(user, claims) {
ctx.Status(http.StatusForbidden)
return
}
ctx.Header("X-Auth-User", user.Username)
ctx.Status(http.StatusOK)
return
}
}
if !store.tryRefreshAndValidate(ctx, allow) {
ctx.Status(http.StatusUnauthorized)
}
}
// tryRefreshAndValidate returns whether it wrote the response (200 or 403),
// not whether access is allowed. On false the caller sends 401.
func (store *Store) tryRefreshAndValidate(ctx *gin.Context, allow func(*models.User, *jwt.MapClaims) bool) bool {
refreshToken, err := ctx.Cookie("refresh_token")
if err != nil {
return false
}
user, err := store.Auth.AuthenticateToken(store.DB, refreshToken)
if err != nil {
return false
}
if !allow(user, nil) {
ctx.Status(http.StatusForbidden)
return true
}
tokens, err := store.Auth.GenerateJWT(user)
if err != nil {
return false
}
store.setAuthCookies(ctx, tokens)
ctx.Header("X-Auth-User", user.Username)
ctx.Status(http.StatusOK)
return true
}
func (store *Store) setAuthCookies(ctx *gin.Context, tokens *services.Tokens) {
services.SetAuthCookies(ctx, store.Auth.Config, tokens)
}
// CheckToken returns the current user. A valid token for a deleted user gets
// 404 and cleared cookies.
func (store *Store) CheckToken(ctx *gin.Context) {
access_token, err := ctx.Cookie("access_token")
if err != nil {
ctx.JSON(401, gin.H{"error": "unauthorized"})
return
}
user, err := store.Auth.AuthenticateToken(store.DB, access_token)
if err != nil {
if errors.Is(err, services.ErrUserNotFound) {
log.Println(err)
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
store.removeCookies(ctx)
return
}
ctx.JSON(401, gin.H{"error": "unauthorized"})
return
}
ctx.JSON(http.StatusOK, user)
}
// RefreshToken exchanges the refresh token for a new pair. It is not rotated,
// but logout and password changes revoke it via the token version.
func (store *Store) RefreshToken(ctx *gin.Context) {
refreshToken, err := ctx.Cookie("refresh_token")
if err != nil {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
user, err := store.Auth.AuthenticateToken(store.DB, refreshToken)
if err != nil {
switch {
case errors.Is(err, services.ErrInvalidClaims):
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "invalid token claims"})
case errors.Is(err, services.ErrUserNotFound):
log.Println(err)
ctx.JSON(http.StatusNotFound, gin.H{"error": "not found"})
store.removeCookies(ctx)
default:
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
}
return
}
tokens, err := store.Auth.GenerateJWT(user)
if err != nil {
log.Println(err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
}
store.setAuthCookies(ctx, tokens)
ctx.JSON(http.StatusAccepted, user)
}
func (store *Store) Login(ctx *gin.Context) {
// On top of Caddy's limit. ClientIP is trustworthy because main.go pins
// the trusted proxy range.
if !store.LoginLimiter.Allow(ctx.ClientIP()) {
ctx.JSON(http.StatusTooManyRequests, gin.H{"error": "too many login attempts, please try again later"})
return
}
var input UserCredentials
if err := ctx.ShouldBindBodyWithJSON(&input); err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
return
}
// Same message for unknown user and wrong password.
user := models.User{}
if err := store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
return
}
if err := bcrypt.CompareHashAndPassword(user.Password, []byte(input.Password)); err != nil {
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
return
}
tokens, err := store.Auth.GenerateJWT(&user)
if err != nil {
log.Println(err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
return
}
store.setAuthCookies(ctx, tokens)
ctx.JSON(http.StatusAccepted, user)
}
// Logout clears the cookies and bumps the token version, revoking every copy
// of the tokens. Always 200.
func (store *Store) Logout(ctx *gin.Context) {
store.revokeCallerTokens(ctx)
store.removeCookies(ctx)
ctx.Status(http.StatusOK)
}
// revokeCallerTokens verifies the token before bumping, or a forged cookie
// could revoke any user's sessions.
func (store *Store) revokeCallerTokens(ctx *gin.Context) {
for _, name := range []string{"access_token", "refresh_token"} {
token, err := ctx.Cookie(name)
if err != nil {
continue
}
user, err := store.Auth.AuthenticateToken(store.DB, token)
if err != nil {
continue
}
if err := services.BumpTokenVersion(store.DB, user.ID); err != nil {
log.Printf("logout: failed to revoke tokens for user %d: %v", user.ID, err)
}
return
}
}
func (store *Store) removeCookies(ctx *gin.Context) {
services.ClearAuthCookies(ctx, store.Auth.Config)
}