diff --git a/api/api.go b/api/api.go index 55d7963..9918bf5 100644 --- a/api/api.go +++ b/api/api.go @@ -72,6 +72,12 @@ func Start() { r.Post("/", Login) }) + r.Route("/logout", func(r chi.Router) { + r.Use(SessionAuthMiddleware) + + r.Post("/", Logout) + }) + r.Route("/register", func(r chi.Router) { r.Post("/", NewUser) }) diff --git a/api/auth.go b/api/auth.go index 9632d13..5aa3ae2 100644 --- a/api/auth.go +++ b/api/auth.go @@ -3,6 +3,7 @@ package api import ( "context" "net/http" + "time" "github.com/google/uuid" "golang.org/x/crypto/bcrypt" @@ -47,6 +48,29 @@ func Login(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Login successful")) } +func Logout(w http.ResponseWriter, r *http.Request) { + cookie, err := r.Cookie("session_token") + if err != nil { + http.Error(w, "No session cookie found. You are already logged out", http.StatusBadRequest) + return + } + + sessionToken := cookie.Value + username, valid := ValidateSession(sessionToken) + if !valid { + http.Error(w, "Session cookie could not be validated. You are already logged out", http.StatusBadRequest) + return + } + + DeleteSession(sessionToken) + + cookie.Expires = time.Now() + http.SetCookie(w, cookie) + + w.Write([]byte(username + " has been logged out")) + +} + var sessionStore = make(map[string]string) func CreateSession(username string) string { @@ -60,6 +84,13 @@ func ValidateSession(sessionToken string) (string, bool) { return username, exists } +func DeleteSession(sessionToken string) (string, bool) { + username, exists := sessionStore[sessionToken] + + delete(sessionStore, username) + return username, exists +} + type contextKey string const usernameKey contextKey = "username"