package middlewares import ( "encoding/json" "net/http" "net/http/httptest" "testing" "time" "github.com/gin-gonic/gin" "github.com/golang-jwt/jwt/v5" "github.com/stretchr/testify/assert" ) func TestAuthMiddleware(t *testing.T) { gin.SetMode(gin.TestMode) tests := []struct { name string setupAuth func(r *http.Request) expectedStatus int expectedUserID string }{ { name: "Valid Token", setupAuth: func(r *http.Request) { token, _ := GenerateToken("user123") r.Header.Set("Authorization", "Bearer "+token) }, expectedStatus: http.StatusOK, expectedUserID: "user123", }, { name: "Missing Auth Header", setupAuth: func(r *http.Request) {}, expectedStatus: http.StatusUnauthorized, expectedUserID: "", }, { name: "Invalid Token Format", setupAuth: func(r *http.Request) { r.Header.Set("Authorization", "InvalidFormat") }, expectedStatus: http.StatusUnauthorized, expectedUserID: "", }, { name: "Expired Token", setupAuth: func(r *http.Request) { token := jwt.NewWithClaims(jwtSigningMethod, jwt.MapClaims{ "user_id": "user123", "exp": time.Now().Add(-time.Hour).Unix(), // Expired 1 hour ago }) tokenString, _ := token.SignedString(jwtKey) r.Header.Set("Authorization", "Bearer "+tokenString) }, expectedStatus: http.StatusUnauthorized, expectedUserID: "", }, { name: "Invalid Signature", setupAuth: func(r *http.Request) { token := jwt.NewWithClaims(jwtSigningMethod, jwt.MapClaims{ "user_id": "user123", "exp": time.Now().Add(time.Hour).Unix(), }) tokenString, _ := token.SignedString([]byte("wrong_secret")) r.Header.Set("Authorization", "Bearer "+tokenString) }, expectedStatus: http.StatusUnauthorized, expectedUserID: "", }, { name: "Missing Auth Header", setupAuth: func(r *http.Request) {}, expectedStatus: http.StatusUnauthorized, expectedUserID: "", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Setup r := gin.New() r.Use(AuthMiddleware()) r.GET("/test", func(c *gin.Context) { userID, exists := c.Get("user_id") if exists { c.JSON(http.StatusOK, gin.H{"user_id": userID}) } else { c.JSON(http.StatusUnauthorized, gin.H{"user_id": ""}) } }) req, _ := http.NewRequest(http.MethodGet, "/test", nil) tt.setupAuth(req) w := httptest.NewRecorder() r.ServeHTTP(w, req) assert.Equal(t, tt.expectedStatus, w.Code) var response map[string]string err := json.Unmarshal(w.Body.Bytes(), &response) assert.NoError(t, err) assert.Equal(t, tt.expectedUserID, response["user_id"]) }) } }