Add half arsed user separation

This commit is contained in:
Maximilian Friedersdorff 2025-07-30 13:41:03 +01:00
parent 3c792decd6
commit 25bcf4d706
6 changed files with 125 additions and 41 deletions

View file

@ -1,33 +1,77 @@
// Middleware to deal with sessions
// Package middleware to deal with sessions
package middleware
import (
"context"
"log"
"crypto/rand"
"net/http"
)
func SessionMiddleware(cache map[string]string, next http.Handler) http.Handler {
type Session struct {
User string
}
type SessionStore struct {
sessions map[string]Session
}
type ContextKey string
func NewSessionStore() SessionStore {
return SessionStore{sessions: make(map[string]Session, 10)}
}
func (s *SessionStore) Login(user string, w http.ResponseWriter) {
sessionID := rand.Text()
s.sessions[sessionID] = Session{User: user}
cookie := http.Cookie{
Name: "id", Value: sessionID, MaxAge: 3600,
Secure: true, HttpOnly: true, Path: "/",
}
http.SetCookie(w, &cookie)
}
func (s *SessionStore) Logout(w http.ResponseWriter, r *http.Request) {
session := r.Context().Value(ContextKey("session")).(string)
delete(s.sessions, session)
cookie := http.Cookie{
Name: "id", Value: "", MaxAge: -1,
Secure: true, HttpOnly: true, Path: "/",
}
http.SetCookie(w, &cookie)
}
func (s *SessionStore) AsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sessionCookie, err := r.Cookie("id")
// No session yet
if err != nil {
http.Redirect(w, r, "/login/", http.StatusUnauthorized)
http.Redirect(w, r, "/login/", http.StatusFound)
return
}
user, ok := cache[sessionCookie.Value]
session, ok := s.sessions[sessionCookie.Value]
// Session expired
if !ok {
http.Redirect(w, r, "/login/", http.StatusUnauthorized)
http.Redirect(w, r, "/login/", http.StatusFound)
return
}
log.Printf("User is %s", user)
ctx := r.Context()
ctx = context.WithValue(ctx, "user", user)
ctx = context.WithValue(
context.WithValue(
ctx,
ContextKey("user"),
session.User,
),
ContextKey("session"),
sessionCookie.Value,
)
next.ServeHTTP(w, r.WithContext(ctx))
})