Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/mayask/go-sqlc-scope.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101package controller
import ( "encoding/json" "fmt" "net/http"
"github.com/example/scopedemo/internal/scope" "github.com/example/scopedemo/internal/usecase" "github.com/google/uuid")
type UserController struct { uc *usecase.UserUsecase}
func NewUserController(uc *usecase.UserUsecase) *UserController { return &UserController{uc: uc}}
// ListUsers handles GET /users?role=admin// Scope is determined from auth context (e.g., JWT claims).func (c *UserController) ListUsers(w http.ResponseWriter, r *http.Request) { s, err := scopeFromRequest(r) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return }
var role *string if r.URL.Query().Has("role") { v := r.URL.Query().Get("role") role = &v }
users, err := c.uc.ListUsers(r.Context(), s, role) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return }
json.NewEncoder(w).Encode(users)}
// GetUserByID handles GET /users/{id}func (c *UserController) GetUserByID(w http.ResponseWriter, r *http.Request) { s, err := scopeFromRequest(r) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return }
id, err := uuid.Parse(r.PathValue("id")) if err != nil { http.Error(w, "invalid id", http.StatusBadRequest) return }
user, err := c.uc.GetUserByID(r.Context(), s, id) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return }
json.NewEncoder(w).Encode(user)}
// ListAllUsers handles GET /admin/users — system scope only.func (c *UserController) ListAllUsers(w http.ResponseWriter, r *http.Request) { // In real code, you'd verify the caller has system-level access here. s := scope.NewSystemScope()
users, err := c.uc.ListAllUsers(r.Context(), s) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return }
json.NewEncoder(w).Encode(users)}
// scopeFromRequest extracts scope from request context.// In real code this would come from auth middleware (JWT claims, etc.)func scopeFromRequest(r *http.Request) (scope.Scope, error) { if bid := r.Header.Get("X-Business-ID"); bid != "" { id, err := uuid.Parse(bid) if err != nil { return nil, fmt.Errorf("invalid business ID: %w", err) } return scope.NewBusinessScope(id) } if tid := r.Header.Get("X-Tenant-ID"); tid != "" { id, err := uuid.Parse(tid) if err != nil { return nil, fmt.Errorf("invalid tenant ID: %w", err) } return scope.NewTenantScope(id) } return nil, fmt.Errorf("no scope in request")}