Split user and workspace contexts

This commit is contained in:
2024-11-03 22:02:39 +01:00
parent c8cc854fd6
commit 927d1feb05
3 changed files with 34 additions and 29 deletions

View File

@@ -5,44 +5,48 @@ import (
"novamd/internal/auth"
"novamd/internal/db"
"novamd/internal/httpcontext"
"novamd/internal/models"
"github.com/go-chi/chi/v5"
)
// WithHandlerContext middleware populates the HandlerContext for the request
// This should be placed after authentication middleware
func WithHandlerContext(db *db.DB) func(http.Handler) http.Handler {
// User ID and User Role context
func WithUserContext(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
claims, err := auth.GetUserFromContext(r.Context())
if err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
hctx := &httpcontext.HandlerContext{
UserID: claims.UserID,
UserRole: claims.Role,
}
r = httpcontext.WithHandlerContext(r, hctx)
next.ServeHTTP(w, r)
})
}
// Workspace context
func WithWorkspaceContext(db *db.DB) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get user claims from auth middleware
claims, err := auth.GetUserFromContext(r.Context())
if err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
ctx, ok := httpcontext.GetRequestContext(w, r)
if !ok {
return
}
// Try to get workspace from URL if it exists
workspaceName := chi.URLParam(r, "workspaceName")
var workspace *models.Workspace
if workspaceName != "" {
workspace, err = db.GetWorkspaceByName(claims.UserID, workspaceName)
if err != nil {
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
workspace, err := db.GetWorkspaceByName(ctx.UserID, workspaceName)
if err != nil {
http.Error(w, "Workspace not found", http.StatusNotFound)
return
}
// Create handler context with user and workspace info
hctx := &httpcontext.HandlerContext{
UserID: claims.UserID,
UserRole: claims.Role,
Workspace: workspace,
}
// Add context to request
r = httpcontext.WithHandlerContext(r, hctx)
// Update existing context with workspace
ctx.Workspace = workspace
r = httpcontext.WithHandlerContext(r, ctx)
next.ServeHTTP(w, r)
})
}