From 858f72093f81c774a70f01fae5b60925206bd2cb Mon Sep 17 00:00:00 2001 From: Simon Ser Date: Mon, 19 Feb 2024 01:25:13 +0100 Subject: [PATCH] Add logout route --- main.go | 1 + middleware.go | 16 ++++++++++------ template/index.html | 5 +++-- user.go | 5 +++++ diff --git a/main.go b/main.go index 063c66500e938e47213622f7462593a85a994b3a..317bfdd68d1f44f9b0dc67df19f32a82d5b8d6ca 100644 --- a/main.go +++ b/main.go @@ -36,6 +36,7 @@ mux.Handle("/static/*", http.FileServer(http.FS(staticFS))) mux.Get("/", index) mux.Post("/client/new", createClient) mux.HandleFunc("/login", login) + mux.Post("/logout", logout) mux.HandleFunc("/user/new", updateUser) mux.HandleFunc("/user/{id}", updateUser) mux.HandleFunc("/authorize", authorize) diff --git a/middleware.go b/middleware.go index 18c7b4701787fca59a111b04ac6ee8cea6f163fc..909b5293f02b070318aef33b2cbb5e2924d2cd15 100644 --- a/middleware.go +++ b/middleware.go @@ -50,6 +50,15 @@ // TODO: Secure }) } +func unsetLoginTokenCookie(w http.ResponseWriter) { + http.SetCookie(w, &http.Cookie{ + Name: "sinwon-token", + HttpOnly: true, + SameSite: http.SameSiteStrictMode, + MaxAge: -1, + }) +} + func loginTokenMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { cookie, _ := req.Cookie("sinwon-token") @@ -63,12 +72,7 @@ db := dbFromContext(ctx) tokenID, tokenSecret, _ := UnmarshalSecret[*AccessToken](cookie.Value) token, err := db.FetchAccessToken(ctx, tokenID) if err == errNoDBRows || (err == nil && !token.VerifySecret(tokenSecret)) { - http.SetCookie(w, &http.Cookie{ - Name: "sinwon-token", - HttpOnly: true, - SameSite: http.SameSiteStrictMode, - MaxAge: -1, - }) + unsetLoginTokenCookie(w) next.ServeHTTP(w, req) return } else if err != nil { diff --git a/template/index.html b/template/index.html index 764be26d0efd6979d632c552d50f83308545df2d..3f643efde220126418718c02005b34727c2118d1 100644 --- a/template/index.html +++ b/template/index.html @@ -4,10 +4,11 @@

sinwon

-
+ - + +
{{ with .Clients }} diff --git a/user.go b/user.go index 1071fcfad3459a1cabe61095e087d9300f360abf..a0b3dd05253ba208c19f2c686c5981a30992f945 100644 --- a/user.go +++ b/user.go @@ -104,6 +104,11 @@ setLoginTokenCookie(w, &token, secret) http.Redirect(w, req, redirectURI.String(), http.StatusFound) } +func logout(w http.ResponseWriter, req *http.Request) { + unsetLoginTokenCookie(w) + http.Redirect(w, req, "/login", http.StatusFound) +} + func updateUser(w http.ResponseWriter, req *http.Request) { ctx := req.Context() db := dbFromContext(ctx) -- 2.48.1