RezinaLMS-BackEnd/internal/web_server/api_docs.go

78 lines
2.8 KiB
Go

package httpserver
import (
"Rezina-Backend/docs"
"encoding/json"
"github.com/gofiber/fiber/v2"
"strings"
)
func specificationPathMatchesAudience(path, audience string) bool {
isAdmin := strings.HasPrefix(path, "/api/v1/admin/")
if audience == "admin" {
return isAdmin
}
if audience != "client" || !strings.HasPrefix(path, "/api/v1/") || isAdmin {
return false
}
switch path {
case "/api/v1/payments/webhook", "/api/v1/payments/chapa/callback", "/api/v1/payments/chapa/success", "/api/v1/payments/arifpay/success", "/api/v1/auth/google/callback":
return false
}
return true
}
// audienceSpecification exposes only an audience's routes and referenced schemas.
func audienceSpecification(audience string) fiber.Handler {
return func(c *fiber.Ctx) error {
var spec map[string]any
if err := json.Unmarshal([]byte(docs.SwaggerInfo.ReadDoc()), &spec); err != nil {
return fiber.NewError(500, "Unable to load API documentation")
}
paths, _ := spec["paths"].(map[string]any)
selected := map[string]any{}
for path, operation := range paths {
if specificationPathMatchesAudience(path, audience) {
selected[path] = operation
}
}
spec["paths"] = selected
if info, ok := spec["info"].(map[string]any); ok {
if audience == "admin" {
info["title"] = "Rezina Admin API"
info["description"] = "Admin panel operations use /api/v1/admin. Sign in through /api/v1/admin/team/login, then enter Bearer followed by a space and the access token in Authorize. Protected endpoints require a staff account and the relevant RBAC permission. WebSockets use the token query parameter."
} else {
info["title"] = "Rezina Customer API"
info["description"] = "Customer web and mobile operations retain /api/v1; there is no /client prefix. Public registration, login, and discovery endpoints do not require authorization. For protected endpoints, enter Bearer followed by a space and a customer access token in Authorize. Premium learning content requires an active EDUCATION subscription unless the account has an existing exemption. WebSockets use the token query parameter."
}
}
definitions, _ := spec["definitions"].(map[string]any)
used := map[string]any{}
var collect func(any)
collect = func(value any) {
switch node := value.(type) {
case map[string]any:
if ref, ok := node["$ref"].(string); ok && strings.HasPrefix(ref, "#/definitions/") {
name := strings.TrimPrefix(ref, "#/definitions/")
if _, seen := used[name]; !seen {
if definition, found := definitions[name]; found {
used[name] = definition
collect(definition)
}
}
}
for _, child := range node {
collect(child)
}
case []any:
for _, child := range node {
collect(child)
}
}
}
collect(selected)
spec["definitions"] = used
return c.JSON(spec)
}
}