feat(api): POST /api/auth/logout
Deletes the session row keyed by the cookie/bearer token and clears the cookie on the client. Best-effort DB delete — logout still succeeds for the client if the row's already gone. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -157,3 +157,51 @@ func TestHandleLogin_MalformedBodyReturns400(t *testing.T) {
|
||||
t.Errorf("status = %d, want 400", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func userCtxKeyForTest() any { return auth.UserCtxKeyForTest() }
|
||||
|
||||
func TestHandleLogout_DeletesSessionAndClearsCookie(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
user := seedUser(t, pool, "alice", "hunter2", false)
|
||||
|
||||
// Manually create a session to log out of.
|
||||
token, err := auth.MintSessionToken()
|
||||
if err != nil {
|
||||
t.Fatalf("mint: %v", err)
|
||||
}
|
||||
if _, err := dbq.New(pool).InsertSession(context.Background(), dbq.InsertSessionParams{
|
||||
UserID: user.ID,
|
||||
TokenHash: auth.HashSessionToken(token),
|
||||
}); err != nil {
|
||||
t.Fatalf("insert: %v", err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/auth/logout", nil)
|
||||
req.AddCookie(&http.Cookie{Name: auth.SessionCookieName, Value: token})
|
||||
// handleLogout runs behind RequireUser in real routing; simulate that by
|
||||
// putting the user into context here.
|
||||
req = req.WithContext(context.WithValue(req.Context(), userCtxKeyForTest(), user))
|
||||
w := httptest.NewRecorder()
|
||||
h.handleLogout(w, req)
|
||||
|
||||
if w.Code != http.StatusNoContent {
|
||||
t.Errorf("status = %d, want 204", w.Code)
|
||||
}
|
||||
|
||||
// Cookie should be cleared.
|
||||
var cleared bool
|
||||
for _, c := range w.Result().Cookies() {
|
||||
if c.Name == auth.SessionCookieName && c.MaxAge < 0 {
|
||||
cleared = true
|
||||
}
|
||||
}
|
||||
if !cleared {
|
||||
t.Error("session cookie not cleared")
|
||||
}
|
||||
|
||||
// Session row should be gone.
|
||||
_, err = dbq.New(pool).GetSessionByTokenHash(context.Background(), auth.HashSessionToken(token))
|
||||
if err == nil {
|
||||
t.Error("session row still present after logout")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user