feat: Update JWT token generation to set cookie and modify authentication middleware to use cookie
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user