chg: auth handling to jwt cookies

This commit is contained in:
$(pass /github/name)
2024-09-05 16:39:06 +02:00
parent 4e5e0963c7
commit 8113b02356
2 changed files with 75 additions and 45 deletions

View File

@@ -24,11 +24,11 @@ func TestAuthMiddleware(t *testing.T) {
{
name: "Valid Token",
setupAuth: func(r *http.Request) {
token, _ := GenerateToken("user123")
r.Header.Set("Authorization", "Bearer "+token)
token, _ := GenerateToken(123)
r.AddCookie(&http.Cookie{Name: "jwt", Value: token})
},
expectedStatus: http.StatusOK,
expectedUserID: 12,
expectedUserID: 123,
},
{
name: "Missing Auth Header",
@@ -52,7 +52,7 @@ func TestAuthMiddleware(t *testing.T) {
"exp": time.Now().Add(-time.Hour).Unix(), // Expired 1 hour ago
})
tokenString, _ := token.SignedString(jwtKey)
r.Header.Set("Authorization", "Bearer "+tokenString)
r.AddCookie(&http.Cookie{Name: "jwt", Value: tokenString})
},
expectedStatus: http.StatusUnauthorized,
expectedUserID: 0,
@@ -65,17 +65,11 @@ func TestAuthMiddleware(t *testing.T) {
"exp": time.Now().Add(time.Hour).Unix(),
})
tokenString, _ := token.SignedString([]byte("wrong_secret"))
r.Header.Set("Authorization", "Bearer "+tokenString)
r.AddCookie(&http.Cookie{Name: "jwt", Value: tokenString})
},
expectedStatus: http.StatusUnauthorized,
expectedUserID: 0,
},
{
name: "Missing Auth Header",
setupAuth: func(r *http.Request) {},
expectedStatus: http.StatusUnauthorized,
expectedUserID: 0,
},
}
for _, tt := range tests {
@@ -100,11 +94,20 @@ func TestAuthMiddleware(t *testing.T) {
assert.Equal(t, tt.expectedStatus, w.Code)
var response map[string]string
err := json.Unmarshal(w.Body.Bytes(), &response)
assert.NoError(t, err)
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"])
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()))
}
})
}
}