authMiddleware JWT authentication middleware
()
| 635 | |
| 636 | // authMiddleware JWT authentication middleware |
| 637 | func (s *Server) authMiddleware() gin.HandlerFunc { |
| 638 | return func(c *gin.Context) { |
| 639 | authHeader := c.GetHeader("Authorization") |
| 640 | if authHeader == "" { |
| 641 | c.JSON(http.StatusUnauthorized, gin.H{"error": "Missing Authorization header"}) |
| 642 | c.Abort() |
| 643 | return |
| 644 | } |
| 645 | |
| 646 | // Check Bearer token format |
| 647 | tokenParts := strings.Split(authHeader, " ") |
| 648 | if len(tokenParts) != 2 || tokenParts[0] != "Bearer" { |
| 649 | c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid Authorization format"}) |
| 650 | c.Abort() |
| 651 | return |
| 652 | } |
| 653 | |
| 654 | tokenString := tokenParts[1] |
| 655 | |
| 656 | // Blacklist check |
| 657 | if auth.IsTokenBlacklisted(tokenString) { |
| 658 | c.JSON(http.StatusUnauthorized, gin.H{"error": "Token expired, please login again"}) |
| 659 | c.Abort() |
| 660 | return |
| 661 | } |
| 662 | |
| 663 | // Validate JWT token |
| 664 | claims, err := auth.ValidateJWT(tokenString) |
| 665 | if err != nil { |
| 666 | logger.Errorf("[Auth] Invalid token: %v", err) |
| 667 | c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid or expired token"}) |
| 668 | c.Abort() |
| 669 | return |
| 670 | } |
| 671 | |
| 672 | // Store user information in context |
| 673 | c.Set("user_id", claims.UserID) |
| 674 | c.Set("email", claims.Email) |
| 675 | c.Next() |
| 676 | } |
| 677 | } |
| 678 | |
| 679 | // Start Start server |
| 680 | func (s *Server) Start() error { |
no test coverage detected