Spaces:
Sleeping
Sleeping
| package middleware | |
| import ( | |
| "net/http" | |
| "strings" | |
| "time" | |
| "github.com/gin-gonic/gin" | |
| "github.com/golang-jwt/jwt/v5" | |
| ) | |
| func IssueToken(secret string, ttl time.Duration) (string, error) { | |
| now := time.Now() | |
| claims := jwt.RegisteredClaims{ | |
| Subject: "admin", | |
| IssuedAt: jwt.NewNumericDate(now), | |
| ExpiresAt: jwt.NewNumericDate(now.Add(ttl)), | |
| } | |
| token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) | |
| return token.SignedString([]byte(secret)) | |
| } | |
| func AuthRequired(secret string) gin.HandlerFunc { | |
| return func(ctx *gin.Context) { | |
| header := ctx.GetHeader("Authorization") | |
| if !strings.HasPrefix(header, "Bearer ") { | |
| ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing bearer token"}) | |
| return | |
| } | |
| raw := strings.TrimPrefix(header, "Bearer ") | |
| _, err := jwt.Parse(raw, func(token *jwt.Token) (interface{}, error) { | |
| return []byte(secret), nil | |
| }, jwt.WithValidMethods([]string{"HS256"})) | |
| if err != nil { | |
| ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"}) | |
| return | |
| } | |
| ctx.Next() | |
| } | |
| } | |