feat: Update JWT token generation to set cookie and modify authentication middleware to use cookie

This commit is contained in:
2025-03-11 17:14:55 +00:00
parent 728258caa7
commit 165432208c
3 changed files with 11 additions and 18 deletions
+8 -15
View File
@@ -2,7 +2,6 @@ package middleware
import (
"errors"
"strings"
"time"
"github.com/gin-gonic/gin"
@@ -31,23 +30,14 @@ type Claims struct {
// AuthMiddleware checks if the user is authenticated
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// Get the Authorization header
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
utils.UnauthorizedResponse(c, "Authorization header is required")
// Get the token from cookie
tokenString, err := c.Cookie("jwt")
if err != nil {
utils.UnauthorizedResponse(c, "Authentication cookie is required")
c.Abort()
return
}
// Check if the header has the Bearer prefix
parts := strings.Split(authHeader, " ")
if len(parts) != 2 || parts[0] != "Bearer" {
utils.UnauthorizedResponse(c, "Invalid authorization format, expected 'Bearer TOKEN'")
c.Abort()
return
}
tokenString := parts[1]
claims, err := validateToken(tokenString)
if err != nil {
utils.UnauthorizedResponse(c, "Invalid or expired token")
@@ -102,7 +92,7 @@ func RoleMiddleware(roles ...string) gin.HandlerFunc {
}
// GenerateToken creates a new JWT token for a user
func GenerateToken(user *models.User) (string, error) {
func GenerateToken(user *models.User, c *gin.Context) (string, error) {
// Create the claims
claims := Claims{
UserID: user.ID.String(),
@@ -125,6 +115,9 @@ func GenerateToken(user *models.User) (string, error) {
return "", err
}
// Set the cookie
c.SetCookie("jwt", tokenString, int(tokenDuration.Seconds()), "/", "", true, true)
return tokenString, nil
}