add logout method
This commit is contained in:
@@ -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)
|
||||
})
|
||||
|
31
api/auth.go
31
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"
|
||||
|
Reference in New Issue
Block a user