Files
GoMembership/internal/middlewares/auth_test.go
2024-09-05 16:39:06 +02:00

114 lines
2.8 KiB
Go

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 int64
}{
{
name: "Valid Token",
setupAuth: func(r *http.Request) {
token, _ := GenerateToken(123)
r.AddCookie(&http.Cookie{Name: "jwt", Value: token})
},
expectedStatus: http.StatusOK,
expectedUserID: 123,
},
{
name: "Missing Auth Header",
setupAuth: func(r *http.Request) {},
expectedStatus: http.StatusUnauthorized,
expectedUserID: 0,
},
{
name: "Invalid Token Format",
setupAuth: func(r *http.Request) {
r.Header.Set("Authorization", "InvalidFormat")
},
expectedStatus: http.StatusUnauthorized,
expectedUserID: 0,
},
{
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.AddCookie(&http.Cookie{Name: "jwt", Value: tokenString})
},
expectedStatus: http.StatusUnauthorized,
expectedUserID: 0,
},
{
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.AddCookie(&http.Cookie{Name: "jwt", Value: tokenString})
},
expectedStatus: http.StatusUnauthorized,
expectedUserID: 0,
},
}
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": 0})
}
})
req, _ := http.NewRequest(http.MethodGet, "/test", nil)
tt.setupAuth(req)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Equal(t, tt.expectedStatus, w.Code)
if tt.expectedStatus == http.StatusOK {
var response map[string]int64
err := json.Unmarshal(w.Body.Bytes(), &response)
assert.NoError(t, err)
assert.Equal(t, tt.expectedUserID, response["user_id"])
// Check if a new cookie was set
cookies := w.Result().Cookies()
assert.GreaterOrEqual(t, len(cookies), 1)
assert.Equal(t, "jwt", cookies[0].Name)
assert.NotEmpty(t, cookies[0].Value)
} else {
assert.Equal(t, 0, len(w.Result().Cookies()))
}
})
}
}