add logout method
This commit is contained in:
@@ -72,6 +72,12 @@ func Start() {
|
|||||||
r.Post("/", Login)
|
r.Post("/", Login)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
r.Route("/logout", func(r chi.Router) {
|
||||||
|
r.Use(SessionAuthMiddleware)
|
||||||
|
|
||||||
|
r.Post("/", Logout)
|
||||||
|
})
|
||||||
|
|
||||||
r.Route("/register", func(r chi.Router) {
|
r.Route("/register", func(r chi.Router) {
|
||||||
r.Post("/", NewUser)
|
r.Post("/", NewUser)
|
||||||
})
|
})
|
||||||
|
31
api/auth.go
31
api/auth.go
@@ -3,6 +3,7 @@ package api
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
@@ -47,6 +48,29 @@ func Login(w http.ResponseWriter, r *http.Request) {
|
|||||||
w.Write([]byte("Login successful"))
|
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)
|
var sessionStore = make(map[string]string)
|
||||||
|
|
||||||
func CreateSession(username string) string {
|
func CreateSession(username string) string {
|
||||||
@@ -60,6 +84,13 @@ func ValidateSession(sessionToken string) (string, bool) {
|
|||||||
return username, exists
|
return username, exists
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func DeleteSession(sessionToken string) (string, bool) {
|
||||||
|
username, exists := sessionStore[sessionToken]
|
||||||
|
|
||||||
|
delete(sessionStore, username)
|
||||||
|
return username, exists
|
||||||
|
}
|
||||||
|
|
||||||
type contextKey string
|
type contextKey string
|
||||||
|
|
||||||
const usernameKey contextKey = "username"
|
const usernameKey contextKey = "username"
|
||||||
|
Reference in New Issue
Block a user