Add sign out button

This commit is contained in:
Lucas Schumacher 2024-08-22 21:02:09 -04:00
parent dfde1b8381
commit 0fa9037164
4 changed files with 34 additions and 0 deletions

View File

@ -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 {

View File

@ -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)

View File

@ -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

View File

@ -16,6 +16,10 @@
<a class="text-base font-semibold hover:text-blue-100 pr-8" href="/faq">FAQ</a>
</div>
<div class="space-x-4">
<form action="/signout" method="post" class="inline pr-4">
{{csrfField}}
<button type="submit">Sign out</button>
</form>
<a href="/signin">Sign in</a>
<a href="/signup" clss="px-4 py-2 bg-blue-700 hover:bg-blue-600 rounded">Sign up</a>
</div>