From 0fa9037164d7d418e087dace9d9471248ad67aac Mon Sep 17 00:00:00 2001 From: Lucas Schumacher Date: Thu, 22 Aug 2024 21:02:09 -0400 Subject: [PATCH] Add sign out button --- controllers/users.go | 20 ++++++++++++++++++++ main.go | 1 + models/sessions.go | 9 +++++++++ templates/tailwind.gohtml | 4 ++++ 4 files changed, 34 insertions(+) diff --git a/controllers/users.go b/controllers/users.go index 8b6ef03..605ec17 100644 --- a/controllers/users.go +++ b/controllers/users.go @@ -92,6 +92,26 @@ func (u Users) PostSignin(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "User authenticated: %+v", user) } +func (u Users) GetSignout(w http.ResponseWriter, r *http.Request) { + sessionCookie, err := r.Cookie("session") + if err != nil { + http.Redirect(w, r, "/signin", http.StatusFound) + return + } + err = u.SessionService.Delete(sessionCookie.Value) + if err != nil { + fmt.Println(err) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + c := http.Cookie{ + Name: "session", + MaxAge: -1, + } + http.SetCookie(w, &c) + http.Redirect(w, r, "/signin", http.StatusFound) +} + func (u Users) CurrentUser(w http.ResponseWriter, r *http.Request) { seshCookie, err := r.Cookie("session") if err != nil { diff --git a/main.go b/main.go index 3d0df4b..5b43a2a 100644 --- a/main.go +++ b/main.go @@ -60,6 +60,7 @@ func main() { r.Post("/signup", usersCtrlr.PostSignup) r.Get("/signin", usersCtrlr.GetSignin) r.Post("/signin", usersCtrlr.PostSignin) + r.Post("/signout", usersCtrlr.GetSignout) r.Get("/user", usersCtrlr.CurrentUser) diff --git a/models/sessions.go b/models/sessions.go index 604e1b7..607762b 100644 --- a/models/sessions.go +++ b/models/sessions.go @@ -85,6 +85,15 @@ func (ss *SessionService) Create(userID int) (*Session, error) { return &session, nil } +func (ss *SessionService) Delete(token string) error { + tokenHash := hash(token) + _, err := ss.DB.Exec(`DELETE FROM sessions WHERE token_hash = $1;`, tokenHash) + if err != nil { + return fmt.Errorf("delete: %w", err) + } + return nil +} + func (ss *SessionService) User(token string) (*User, error) { token_hash := hash(token) var user User diff --git a/templates/tailwind.gohtml b/templates/tailwind.gohtml index c1a0394..12aa03d 100644 --- a/templates/tailwind.gohtml +++ b/templates/tailwind.gohtml @@ -16,6 +16,10 @@ FAQ
+
+ {{csrfField}} + +
Sign in Sign up