first round of files

This commit is contained in:
2026-05-06 23:13:06 +02:00
parent a30962474d
commit 2aa5d01307
24 changed files with 991 additions and 0 deletions
+68
View File
@@ -0,0 +1,68 @@
package middleware
import (
"context"
"net/http"
"github.com/gorilla/sessions"
)
type contextKey string
const (
ContextKeyUserID contextKey = "userID"
ContextKeyUsername contextKey = "username"
ContextKeyIsAdmin contextKey = "isAdmin"
)
type AuthMiddleware struct {
store sessions.Store
}
func NewAuth(store sessions.Store) *AuthMiddleware {
return &AuthMiddleware{store: store}
}
func (a *AuthMiddleware) Require(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, err := a.store.Get(r, "fb_session")
if err != nil || session.IsNew {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
userID, ok := session.Values["userID"].(int64)
if !ok || userID == 0 {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
ctx := context.WithValue(r.Context(), ContextKeyUserID, userID)
if username, ok := session.Values["username"].(string); ok {
ctx = context.WithValue(ctx, ContextKeyUsername, username)
}
if isAdmin, ok := session.Values["isAdmin"].(bool); ok {
ctx = context.WithValue(ctx, ContextKeyIsAdmin, isAdmin)
}
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func (a *AuthMiddleware) Optional(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
session, err := a.store.Get(r, "fb_session")
if err == nil && !session.IsNew {
if userID, ok := session.Values["userID"].(int64); ok && userID != 0 {
ctx := context.WithValue(r.Context(), ContextKeyUserID, userID)
r = r.WithContext(ctx)
}
}
next.ServeHTTP(w, r)
})
}
func UserIDFromContext(ctx context.Context) (int64, bool) {
id, ok := ctx.Value(ContextKeyUserID).(int64)
return id, ok
}
+16
View File
@@ -0,0 +1,16 @@
package middleware
import (
"net/http"
)
func RequireAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
isAdmin, _ := r.Context().Value(ContextKeyIsAdmin).(bool)
if !isAdmin {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}