feat: auth middleware;

fix: backend healthcheck
This commit is contained in:
2025-06-19 14:08:51 +03:00
parent fed517f905
commit 4e3554346a
7 changed files with 118 additions and 23 deletions

View File

@@ -0,0 +1,56 @@
package middleware
import (
"easywish/config"
"errors"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
type Claims struct {
Username string `json:"username"`
jwt.RegisteredClaims
}
func JWTAuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
cfg := config.GetConfig()
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Authorization header required"})
return
}
tokenString := authHeader
token, err := jwt.ParseWithClaims(
tokenString,
&Claims{},
func(token *jwt.Token) (any, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(cfg.JwtSecret), nil
},
)
if err != nil {
if errors.Is(err, jwt.ErrTokenExpired) {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Token expired"})
} else {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
}
return
}
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
c.Set("userID", claims.Username)
c.Next()
} else {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid claims"})
}
}
}