Files
mygo/internal/middleware/auth.go
T
ld be4fcad605 Refactor handlers to use MustGetUserID
- Fix: replace repeated authorization checks in handlers with the new
  MustGetUserID helper, which panics if the user ID is missing. This
  simplifies handler code by eliminating redundant error handling.
- Tests: update auth tests to verify the panic behavior in unprotected
  routes.
2026-06-24 14:43:38 +08:00

71 lines
1.8 KiB
Go

package middleware
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/dhao2001/mygo/internal/api"
"github.com/dhao2001/mygo/internal/auth"
)
const userIDKey = "user_id"
// AuthRequired returns a Gin middleware that validates JWT access tokens.
// On success, it injects the user ID into the context via c.Get("user_id").
func AuthRequired(jwtSecret []byte) gin.HandlerFunc {
return func(c *gin.Context) {
header := c.GetHeader("Authorization")
if header == "" {
api.Error(c, http.StatusUnauthorized, "missing authorization header")
c.Abort()
return
}
parts := strings.SplitN(header, " ", 2)
if len(parts) != 2 || !strings.EqualFold(parts[0], "bearer") {
api.Error(c, http.StatusUnauthorized, "invalid authorization header format")
c.Abort()
return
}
claims, err := auth.ParseToken(parts[1], jwtSecret)
if err != nil {
api.Error(c, http.StatusUnauthorized, "invalid or expired token")
c.Abort()
return
}
if claims.Type != auth.TokenAccess {
api.Error(c, http.StatusUnauthorized, "invalid token type")
c.Abort()
return
}
c.Set(userIDKey, claims.UserID)
c.Next()
}
}
// GetUserID extracts the user ID injected by AuthRequired.
// Returns an empty string if the key is not present (e.g., optional auth contexts).
func GetUserID(c *gin.Context) string {
v, _ := c.Get(userIDKey)
if v == nil {
return ""
}
return v.(string)
}
// MustGetUserID extracts the user ID injected by AuthRequired.
// It panics if the key is missing — this indicates a programming error
// (a handler registered without the AuthRequired middleware).
func MustGetUserID(c *gin.Context) string {
userID := GetUserID(c)
if userID == "" {
panic("user_id not found in context — is AuthRequired middleware applied?")
}
return userID
}