Compare commits

...

2 Commits

Author SHA1 Message Date
4b3d64c5cd add logout method 2025-04-08 21:30:42 -04:00
799bf784aa allow LoginCtx to handle anonymous users 2025-04-08 21:00:33 -04:00
3 changed files with 50 additions and 12 deletions

View File

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

View File

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

View File

@@ -32,28 +32,29 @@ func UserCtx(next http.Handler) http.Handler {
func Whoami(w http.ResponseWriter, r *http.Request) {
user, ok := r.Context().Value(userKey{}).(*User)
if !ok {
w.Write([]byte("undefined"))
return
} else {
w.Write([]byte(user.Name))
if !ok || user == nil {
// Anonymous user
w.Write([]byte("anonymous"))
return
}
w.Write([]byte(user.Name))
}
func LoginCtx(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var user *User
var err error
if username := r.Context().Value(usernameKey).(string); username != "" {
user, err = dbGetUserByName(username)
} else {
render.Render(w, r, ErrNotFound)
// Try to retrieve username from context
username, ok := r.Context().Value(usernameKey).(string)
if !ok || username == "" {
// No username provided, assume it's an anonymous user
next.ServeHTTP(w, r)
return
}
// Lookup user in the database
user, err := dbGetUserByName(username)
if err != nil {
// If user is specified and not found, throw an error
render.Render(w, r, ErrNotFound)
return
}