package middleware import ( "fmt" "github.com/gin-gonic/gin" "github.com/golang-jwt/jwt/v5" "net/http" "os" "time" "udemy_httpserver/models" ) func RequireAuth(c *gin.Context) { // Get JWT from cookie tokenString := c.GetHeader("Authorization") if tokenString == "" { c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"}) c.Abort() return } tokenString = tokenString[7:] // Remove "Bearer " from the token // Decode/validate it token, _ := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { // Don't forget to validate the alg is what you expect: if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) } // hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key") return []byte(os.Getenv("JWT_SECRET")), nil }) if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { // Check the expiry date if float64(time.Now().Unix()) > claims["exp"].(float64) { c.AbortWithStatus(http.StatusUnauthorized) } // Validate that the user exists in the database user, err := models.FindOneByID(int(claims["sub"].(float64))) if err != nil || user == nil { c.AbortWithStatus(http.StatusUnauthorized) } c.Set("user", user) c.Next() } else { c.AbortWithStatus(http.StatusUnauthorized) } }