RezinaLMS-BackEnd/internal/apidocs/specification.go

83 lines
2.9 KiB
Go

// Package apidocs provides the same audience-specific Swagger specifications to HTTP handlers and offline exports.
package apidocs
import (
"Rezina-Backend/docs"
"encoding/json"
"fmt"
"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
}
// Specification returns an independently decoded specification for admin, client, or all operations.
func Specification(audience string) (map[string]any, error) {
var spec map[string]any
if err := json.Unmarshal([]byte(docs.SwaggerInfo.ReadDoc()), &spec); err != nil {
return nil, err
}
if audience == "all" {
return spec, nil
}
if audience != "admin" && audience != "client" {
return nil, fmt.Errorf("unknown Swagger audience %q", audience)
}
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 spec, nil
}