35 lines
698 B
Go
35 lines
698 B
Go
|
|
// Middleware to deal with sessions
|
||
|
|
package middleware
|
||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"log"
|
||
|
|
"net/http"
|
||
|
|
)
|
||
|
|
|
||
|
|
func SessionMiddleware(cache map[string]string, 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)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
user, ok := cache[sessionCookie.Value]
|
||
|
|
|
||
|
|
// Session expired
|
||
|
|
if !ok {
|
||
|
|
http.Redirect(w, r, "/login/", http.StatusUnauthorized)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
log.Printf("User is %s", user)
|
||
|
|
|
||
|
|
ctx := r.Context()
|
||
|
|
ctx = context.WithValue(ctx, "user", user)
|
||
|
|
|
||
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||
|
|
})
|
||
|
|
}
|