Files
CatsOfMastodonGo/internal/auth/jwt.go
Mohammad Mahdi f136ae58b3 Refactor: Implement uber-go/fx dependency injection
- Replace global variable pattern with proper dependency injection
- Add uber-go/fx for automatic dependency resolution
- Refactor all services and handlers to use constructor injection
- Eliminate fragile initialization order dependencies
- Improve testability and modularity
- Add structured logging with zap

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
2025-09-16 11:41:01 +03:30

64 lines
1.5 KiB
Go

package auth
import (
"CatsOfMastodonBotGo/internal/config"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
type JwtTokenGenerator struct {
cfg *config.Config
}
func NewJwtTokenGenerator(cfg *config.Config) *JwtTokenGenerator {
return &JwtTokenGenerator{cfg: cfg}
}
func (j *JwtTokenGenerator) GenerateToken(claims map[string]interface{}) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"exp": time.Now().AddDate(0, 0, 1).Unix(),
"iat": time.Now().Unix(),
"iss": j.cfg.JwtIssuer,
"aud": j.cfg.JwtAudience,
})
for k, v := range claims {
token.Claims.(jwt.MapClaims)[k] = v
}
return token.SignedString([]byte(j.cfg.JwtSecret))
}
// Gin middleware
func (j *JwtTokenGenerator) GinMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.AbortWithStatusJSON(401, gin.H{"error": "Unauthorized"})
return
}
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
t, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, jwt.ErrSignatureInvalid
}
return []byte(j.cfg.JwtSecret), nil
})
if err != nil {
c.AbortWithStatusJSON(401, gin.H{"error": "Unauthorized"})
return
}
claims, ok := t.Claims.(jwt.MapClaims)
if !ok || claims["role"] != "admin" {
c.AbortWithStatusJSON(401, gin.H{"error": "Unauthorized"})
return
}
c.Next()
}
}