fix(auth): #130 delete inactive sessions on login
All checks were successful
Build Docker Image / Explore-Gitea-Actions (push) Successful in 45s
Build and Push Docker Image / Explore-Gitea-Actions (push) Successful in 51s

This commit was merged in pull request #134.
This commit is contained in:
Tim
2024-09-03 22:49:45 +02:00
parent 38aa94c121
commit 914fbcf5a8

View File

@@ -154,7 +154,6 @@ func HandleSignInComp(db *sql.DB) http.HandlerFunc {
if result {
w.Header().Add("HX-Redirect", "/")
w.WriteHeader(http.StatusOK)
} else {
auth.Error("Invalid email or password").Render(r.Context(), w)
}
@@ -183,7 +182,7 @@ func HandleSignOutComp(db *sql.DB) http.HandlerFunc {
}
http.SetCookie(w, &c)
auth.UserComp("").Render(r.Context(), w)
w.Header().Add("HX-Redirect", "/")
}
}
@@ -197,9 +196,15 @@ func tryCreateSessionAndSetCookie(r *http.Request, w http.ResponseWriter, db *sq
}
session_id := base64.StdEncoding.EncodeToString(session_id_bytes)
// Delete old inactive sessions
_, err = db.Exec("DELETE FROM session WHERE created_at < datetime('now','-8 hours') AND user_uuid = ?", user_uuid)
if err != nil {
slog.Error("Could not delete old sessions: " + err.Error())
}
_, err = db.Exec("INSERT INTO session (session_id, user_uuid, created_at) VALUES (?, ?, datetime())", session_id, user_uuid)
if err != nil {
slog.Error("Could not insert session: %v", err)
slog.Error("Could not insert session: " + err.Error())
auth.Error("Internal Server Error").Render(r.Context(), w)
return false
}
@@ -242,7 +247,7 @@ func verifySessionAndReturnUser(db *sql.DB, r *http.Request) *User {
INNER JOIN user u ON s.user_uuid = u.user_uuid
WHERE session_id = ?`, sessionId).Scan(&user.id, &user.email, &createdAt)
if err != nil {
slog.Error("Could not verify session: " + err.Error())
slog.Warn("Could not verify session: " + err.Error())
return nil
}