Files
stpweb/backend/services/auth.go
T
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

175 lines
5.4 KiB
Go

package services
import (
"errors"
"net/http"
"time"
"adam-french.co.uk/backend/models"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"gorm.io/gorm"
)
// Auth mints and verifies HS256 JWTs. Revocation is by User.TokenVersion:
// every token carries it as "tv", and bumping it kills them all.
type Auth struct {
Config *AuthConfig
}
// Domain is the cookie domain; Endpoint is the backend's public base URL.
type AuthConfig struct {
Secret []byte
Domain string
AccessTokenLifetime time.Duration
RefreshTokenLifetime time.Duration
Endpoint string
}
type Tokens struct {
AccessToken string
RefreshToken string
}
// InitAuth panics on a short secret: HS256 accepts a zero-length key, which
// would make admin tokens forgeable.
func InitAuth(config *AuthConfig) *Auth {
if len(config.Secret) < 32 {
panic("auth secret must be set and at least 32 bytes (check BACKEND_SECRET)")
}
return &Auth{Config: config}
}
// GenerateJWT issues an access/refresh pair. Only the access token carries
// admin; refresh re-reads the row, so a revoked admin flag applies then.
func (auth *Auth) GenerateJWT(user *models.User) (*Tokens, error) {
accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": user.Username,
"id": user.ID,
"admin": user.Admin,
"tv": tokenVersionOf(user.TokenVersion),
"exp": time.Now().Add(auth.Config.AccessTokenLifetime).Unix(),
})
refreshToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"id": user.ID,
"tv": tokenVersionOf(user.TokenVersion),
"exp": time.Now().Add(auth.Config.RefreshTokenLifetime).Unix(),
})
accessTokenString, err := accessToken.SignedString(auth.Config.Secret)
if err != nil {
return nil, err
}
refreshTokenString, err := refreshToken.SignedString(auth.Config.Secret)
if err != nil {
return nil, err
}
return &Tokens{AccessToken: accessTokenString, RefreshToken: refreshTokenString}, nil
}
// The key is fixed; VerifyJWT pins the algorithm, which is what stops
// algorithm-confusion attacks.
func (auth *Auth) keyFunc(_ *jwt.Token) (any, error) {
return auth.Config.Secret, nil
}
// VerifyJWT returns the claims. Numbers decode as float64.
func (auth *Auth) VerifyJWT(tokenStr string) (*jwt.MapClaims, error) {
token, err := jwt.Parse(tokenStr, auth.keyFunc, jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}))
if err != nil {
return nil, err
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return nil, errors.New("Invalid token claims type")
}
return &claims, nil
}
// Distinct so REST and GraphQL can each map them to their own status codes.
var (
ErrInvalidToken = errors.New("invalid token")
ErrInvalidClaims = errors.New("invalid token claims")
ErrUserNotFound = errors.New("user not found")
ErrTokenRevoked = errors.New("token revoked")
)
// tokenVersionOf treats 0 (old rows, tokens without "tv") as 1, the column
// default, so introducing versioning logged nobody out.
func tokenVersionOf(v uint) uint {
if v == 0 {
return 1
}
return v
}
// AuthenticateToken turns a token into a user, checking signature, expiry,
// the user row and the token version. Errors are always the sentinels above.
func (auth *Auth) AuthenticateToken(db *gorm.DB, tokenStr string) (*models.User, error) {
user, _, err := auth.AuthenticateTokenWithClaims(db, tokenStr)
return user, err
}
// AuthenticateTokenWithClaims also returns the claims, for "admin". It costs
// one SELECT per request, which is the price of revocation.
func (auth *Auth) AuthenticateTokenWithClaims(db *gorm.DB, tokenStr string) (*models.User, *jwt.MapClaims, error) {
claims, err := auth.VerifyJWT(tokenStr)
if err != nil {
return nil, nil, ErrInvalidToken
}
userIDF, ok := (*claims)["id"].(float64)
if !ok {
return nil, nil, ErrInvalidClaims
}
// Soft-deleted users are excluded, so a deleted account fails here.
user := models.User{ID: uint(userIDF)}
if err := db.First(&user).Error; err != nil {
return nil, nil, ErrUserNotFound
}
claimedVersion, _ := (*claims)["tv"].(float64)
if tokenVersionOf(uint(claimedVersion)) != tokenVersionOf(user.TokenVersion) {
return nil, nil, ErrTokenRevoked
}
return &user, claims, nil
}
// BumpTokenVersion revokes all of userID's tokens. COALESCE treats a NULL
// version as 1.
func BumpTokenVersion(db *gorm.DB, userID uint) error {
return db.Model(&models.User{}).
Where("id = ?", userID).
UpdateColumn("token_version", gorm.Expr("COALESCE(token_version, 1) + 1")).
Error
}
const (
secure = true
httpOnly = true
)
// SetAuthCookies lives in services so REST and GraphQL share one copy.
// SameSite=Lax survives the redirect back from an OAuth provider.
func SetAuthCookies(gc *gin.Context, config *AuthConfig, tokens *Tokens) {
gc.SetSameSite(http.SameSiteLaxMode)
gc.SetCookie("access_token", tokens.AccessToken, int(config.AccessTokenLifetime.Seconds()), "/", config.Domain, secure, httpOnly)
gc.SetCookie("refresh_token", tokens.RefreshToken, int(config.RefreshTokenLifetime.Seconds()), "/", config.Domain, secure, httpOnly)
}
// ClearAuthCookies must match SetAuthCookies' attributes, or the browser
// keeps the originals.
func ClearAuthCookies(gc *gin.Context, config *AuthConfig) {
gc.SetSameSite(http.SameSiteLaxMode)
gc.SetCookie("access_token", "", -1, "/", config.Domain, secure, httpOnly)
gc.SetCookie("refresh_token", "", -1, "/", config.Domain, secure, httpOnly)
}