refactor(api): enforce protocol-neutral service boundaries

- refactor: move HTTP status and DTO concerns out of model and service
  layers into API and handler code.
- feat: add admin service boundary and route auth through services
  instead of direct repository access.
- test: add architecture and error tests covering package boundaries,
  redaction, and service behavior.
- docs: record the protocol-neutral boundary decision and update
  architecture and roadmap notes.
This commit is contained in:
2026-07-05 23:30:17 +08:00
parent 28e17a5b08
commit 63ede5c237
34 changed files with 1028 additions and 438 deletions
+42 -30
View File
@@ -1,21 +1,28 @@
package middleware
import (
"context"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/dhao2001/mygo/internal/api"
"github.com/dhao2001/mygo/internal/auth"
"github.com/dhao2001/mygo/internal/repository"
"github.com/dhao2001/mygo/internal/service"
)
const userIDKey = "user_id"
const (
userIDKey = "user_id"
principalKey = "principal"
)
type accessAuthenticator interface {
AuthenticateAccessToken(ctx context.Context, token string) (*service.Principal, error)
}
// 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 {
// On success, it injects the principal and user ID into the context.
func AuthRequired(authenticator accessAuthenticator) gin.HandlerFunc {
return func(c *gin.Context) {
header := c.GetHeader("Authorization")
if header == "" {
@@ -31,20 +38,15 @@ func AuthRequired(jwtSecret []byte) gin.HandlerFunc {
return
}
claims, err := auth.ParseToken(parts[1], jwtSecret)
principal, err := authenticator.AuthenticateAccessToken(c.Request.Context(), parts[1])
if err != nil {
api.Error(c, http.StatusUnauthorized, "invalid or expired token")
api.RespondError(c, err)
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.Set(principalKey, *principal)
c.Set(userIDKey, principal.UserID)
c.Next()
}
}
@@ -65,32 +67,42 @@ func GetUserID(c *gin.Context) string {
func MustGetUserID(c *gin.Context) string {
userID := GetUserID(c)
if userID == "" {
panic("user_id not found in context is AuthRequired middleware applied?")
panic("user_id not found in context - is AuthRequired middleware applied?")
}
return userID
}
// AdminRequired returns a Gin middleware that gates access to admin-only
// endpoints. It must be applied AFTER AuthRequired. It fetches the user from
// the repository, and returns 403 if the user is not an admin. Soft-deleted
// users are not found by FindByID and will receive a 401 response.
func AdminRequired(userRepo repository.UserRepository) gin.HandlerFunc {
// GetPrincipal extracts the authenticated principal injected by AuthRequired.
func GetPrincipal(c *gin.Context) (service.Principal, bool) {
v, ok := c.Get(principalKey)
if !ok || v == nil {
return service.Principal{}, false
}
principal, ok := v.(service.Principal)
return principal, ok
}
// MustGetPrincipal extracts the authenticated principal injected by AuthRequired.
func MustGetPrincipal(c *gin.Context) service.Principal {
principal, ok := GetPrincipal(c)
if !ok {
panic("principal not found in context - is AuthRequired middleware applied?")
}
return principal
}
// AdminRequired returns a Gin middleware that gates access to admin-only endpoints.
// It must be applied after AuthRequired.
func AdminRequired() gin.HandlerFunc {
return func(c *gin.Context) {
userID := GetUserID(c)
if userID == "" {
principal, ok := GetPrincipal(c)
if !ok {
api.Error(c, http.StatusUnauthorized, "missing user context")
c.Abort()
return
}
user, err := userRepo.FindByID(c.Request.Context(), userID)
if err != nil {
api.Error(c, http.StatusUnauthorized, "user not found")
c.Abort()
return
}
if !user.IsAdmin {
if !principal.IsAdmin {
api.Error(c, http.StatusForbidden, "admin access required")
c.Abort()
return