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"})
}
}
}

View File

@@ -2,6 +2,7 @@ package routes
import (
"easywish/internal/controllers"
"easywish/internal/middleware"
"github.com/gin-gonic/gin"
)
@@ -24,18 +25,27 @@ func SetupRoutes(r *gin.Engine) *gin.Engine {
authGroup.POST("/passwordResetComplete", controllers.PasswordResetComplete)
}
accountGroup := apiGroup.Group("/account")
{
accountGroup.PUT("/changePassword", controllers.ChangePassword)
}
profileGroup := apiGroup.Group("/profile")
{
profileGroup.GET("/:username", controllers.GetProfile)
profileGroup.GET("/me", controllers.GetOwnProfile)
profileGroup.GET("/privacy", controllers.GetPrivacySettings)
profileGroup.PATCH("/privacy", controllers.UpdatePrivacySettings)
}
protected := apiGroup.Group("")
protected.Use(middleware.JWTAuthMiddleware())
{
accountGroup := protected.Group("/account")
{
accountGroup.PUT("/changePassword", controllers.ChangePassword)
}
profileGroup := protected.Group("/profile")
{
profileGroup.GET("/me", controllers.GetOwnProfile)
profileGroup.GET("/privacy", controllers.GetPrivacySettings)
profileGroup.PATCH("/privacy", controllers.UpdatePrivacySettings)
}
}
}
return r

View File

@@ -0,0 +1,26 @@
package utils
import (
"easywish/config"
"time"
"github.com/golang-jwt/jwt/v5"
)
func GenerateTokens(username string) (accessToken, refreshToken string, err error) {
cfg := config.GetConfig()
accessClaims := jwt.MapClaims{
"username": username,
"exp": time.Now().Add(time.Minute * time.Duration(cfg.JwtExpAccess)).Unix(),
}
accessToken, err = jwt.NewWithClaims(jwt.SigningMethodHS256, accessClaims).SignedString([]byte(cfg.JwtSecret))
refreshClaims := jwt.MapClaims{
"username": username,
"exp": time.Now().Add(time.Hour * time.Duration(cfg.JwtExpRefresh)).Unix(),
}
refreshToken, err = jwt.NewWithClaims(jwt.SigningMethodHS256, refreshClaims).SignedString([]byte(cfg.JwtSecret))
return
}