Skip to content

Commit 00af184

Browse files
Audit logout events
1 parent 45e9ace commit 00af184

2 files changed

Lines changed: 11 additions & 1 deletion

File tree

‎cmd/stackhost/main.go‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,13 @@ func (a *app) createSession(w http.ResponseWriter, r *http.Request, id int64) {
241241
func (a *app) logout(w http.ResponseWriter, r *http.Request) {
242242
if c, err := r.Cookie("stackhost_session"); err == nil {
243243
hash := sha256.Sum256([]byte(c.Value))
244-
a.db.Exec("UPDATE sessions SET revoked_at=? WHERE token_hash=?", time.Now().UTC().Format(time.RFC3339), hex.EncodeToString(hash[:]))
244+
tokenHash := hex.EncodeToString(hash[:])
245+
var userID int64
246+
_ = a.db.QueryRow("SELECT user_id FROM sessions WHERE token_hash=?", tokenHash).Scan(&userID)
247+
a.db.Exec("UPDATE sessions SET revoked_at=? WHERE token_hash=?", time.Now().UTC().Format(time.RFC3339), tokenHash)
248+
if userID > 0 {
249+
a.audit(userID, "logout", "user", userID)
250+
}
245251
}
246252
http.SetCookie(w, &http.Cookie{Name: "stackhost_session", Value: "", Path: "/", MaxAge: -1, HttpOnly: true})
247253
json.NewEncoder(w).Encode(map[string]bool{"ok": true})

‎cmd/stackhost/main_test.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,10 @@ func TestLoginInvalidAndLogout(t *testing.T) {
8787
if logout.Code != http.StatusOK {
8888
t.Fatalf("logout status = %d", logout.Code)
8989
}
90+
var logoutEvents int
91+
if err := a.db.QueryRow("SELECT count(*) FROM audit_logs WHERE action='logout'").Scan(&logoutEvents); err != nil || logoutEvents != 1 {
92+
t.Fatalf("logout audit count = %d, err=%v", logoutEvents, err)
93+
}
9094
me := httptest.NewRecorder()
9195
meReq := httptest.NewRequest(http.MethodGet, "/api/v1/me", nil)
9296
meReq.AddCookie(cookie)

0 commit comments

Comments
 (0)