Add offline Swagger documentation export
This commit is contained in:
parent
e9c657e2ed
commit
3ab841c869
1
.vscode/settings.json
vendored
1
.vscode/settings.json
vendored
|
|
@ -21,4 +21,5 @@
|
||||||
"**/internal/web_server/handlers/**/*.go": "${filename}.handlers",
|
"**/internal/web_server/handlers/**/*.go": "${filename}.handlers",
|
||||||
},
|
},
|
||||||
"makefile.configureOnOpen": false,
|
"makefile.configureOnOpen": false,
|
||||||
|
"python.terminal.useEnvFile": true,
|
||||||
}
|
}
|
||||||
22
cmd/swagger-export/main.go
Normal file
22
cmd/swagger-export/main.go
Normal file
|
|
@ -0,0 +1,22 @@
|
||||||
|
// swagger-export builds portable, offline Swagger UI documentation.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"Rezina-Backend/internal/apidocs/offline"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
output := flag.String("out", "exports/swagger-offline", "Output directory; a ZIP will be written beside it")
|
||||||
|
flag.Parse()
|
||||||
|
archive, err := offline.Export(*output)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "Swagger export failed:", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
fmt.Println("Offline documentation:", filepath.Join(filepath.Dir(archive), filepath.Base(*output), "index.html"))
|
||||||
|
fmt.Println("ZIP archive:", archive)
|
||||||
|
}
|
||||||
|
|
@ -89,3 +89,14 @@ The admin and customer Swagger pages prune unrelated paths and models. Their Aut
|
||||||
Authentication/authorization middleware may return plain-text errors, while application handlers also
|
Authentication/authorization middleware may return plain-text errors, while application handlers also
|
||||||
return the JSON error shapes documented for their operations. Payment webhook authentication uses the
|
return the JSON error shapes documented for their operations. Payment webhook authentication uses the
|
||||||
provider signature headers, not a customer Bearer token.
|
provider signature headers, not a customer Bearer token.
|
||||||
|
|
||||||
|
## Offline export
|
||||||
|
|
||||||
|
Run `make swagger-export` to regenerate and package the current docs, or run
|
||||||
|
`go run ./cmd/swagger-export -out exports/swagger-offline` to export the already-generated specifications.
|
||||||
|
The command creates `exports/swagger-offline/index.html` and `exports/swagger-offline.zip`.
|
||||||
|
Extract the ZIP completely and open `index.html` directly in a browser. No server or internet connection
|
||||||
|
is required. Admin, customer, and complete API pages embed their specifications and use bundled Swagger UI
|
||||||
|
assets. JSON and YAML specs for all three views are included in `specs/` for importing into API tools.
|
||||||
|
API execution is disabled in the offline reference. Use the running application's Swagger UI when you
|
||||||
|
need to send requests. The export contains no account tokens, environment files, or server configuration.
|
||||||
|
|
|
||||||
167
internal/apidocs/offline/export.go
Normal file
167
internal/apidocs/offline/export.go
Normal file
|
|
@ -0,0 +1,167 @@
|
||||||
|
// Package offline builds a portable Swagger UI bundle with no backend or CDN requirement.
|
||||||
|
package offline
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/zip"
|
||||||
|
"bytes"
|
||||||
|
_ "embed"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"html/template"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"Rezina-Backend/internal/apidocs"
|
||||||
|
swaggerFiles "github.com/swaggo/files"
|
||||||
|
"go.yaml.in/yaml/v3"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed swagger_ui_license.txt
|
||||||
|
var thirdPartyLicense []byte
|
||||||
|
|
||||||
|
const pageTemplate = `<!doctype html>
|
||||||
|
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||||
|
<title>{{.Title}} - Offline documentation</title>
|
||||||
|
<link rel="stylesheet" href="assets/swagger-ui.css">
|
||||||
|
<style>body{margin:0;background:#fafafa}nav{padding:16px 24px;background:#172033;color:white;font:14px system-ui;display:flex;gap:20px;align-items:center;flex-wrap:wrap}nav a{color:#dbeafe}.notice{padding:12px 24px;background:#eff6ff;color:#1e3a5f;font:14px system-ui}.swagger-ui .wrapper{max-width:1400px}</style>
|
||||||
|
</head><body>
|
||||||
|
<nav><strong>{{.Title}}</strong><a href="index.html">All documentation</a><a href="admin.html">Admin API</a><a href="customer.html">Customer API</a><a href="specs/{{.Name}}.json" download>Download JSON</a><a href="specs/{{.Name}}.yaml" download>Download YAML</a></nav>
|
||||||
|
<div class="notice">Offline reference | {{.Count}} operations | API execution is disabled. No backend, CDN, or internet connection is required to read these docs.</div>
|
||||||
|
<div id="swagger-ui"></div>
|
||||||
|
<script src="assets/swagger-ui-bundle.js"></script>
|
||||||
|
<script>
|
||||||
|
window.ui=SwaggerUIBundle({
|
||||||
|
spec:{{.Spec}},dom_id:'#swagger-ui',deepLinking:true,
|
||||||
|
presets:[SwaggerUIBundle.presets.apis],layout:'BaseLayout',
|
||||||
|
validatorUrl:null,supportedSubmitMethods:[],tryItOutEnabled:false,persistAuthorization:false,
|
||||||
|
docExpansion:'list',defaultModelsExpandDepth:0,filter:true
|
||||||
|
});
|
||||||
|
</script></body></html>`
|
||||||
|
|
||||||
|
const indexTemplate = `<!doctype html>
|
||||||
|
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Rezina API - Offline documentation</title>
|
||||||
|
<style>body{margin:0;background:#f6f8fc;color:#172033;font:16px/1.6 system-ui,sans-serif}main{max-width:960px;margin:64px auto;padding:0 24px}h1{font-size:36px;line-height:1.2}.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:20px;margin:32px 0}.card{display:block;border:1px solid #dce3ee;border-radius:12px;background:white;padding:24px;text-decoration:none;color:inherit}.card:hover{border-color:#2563eb}.card h2{margin-top:0;color:#1d4ed8}code{background:#e9eef7;padding:2px 6px;border-radius:4px}.note{background:#eaf2ff;border-radius:10px;padding:20px}footer{margin-top:32px;color:#526174;font-size:14px}</style>
|
||||||
|
</head><body><main><h1>Rezina API documentation</h1><p>Browse the exported Swagger documentation locally. Everything needed to view these pages is included in this folder.</p>
|
||||||
|
<div class="cards"><a class="card" href="admin.html"><h2>Admin API</h2><p>Staff operations under <code>/api/v1/admin</code>.</p></a><a class="card" href="customer.html"><h2>Customer API</h2><p>Customer web and mobile operations under <code>/api/v1</code>.</p></a><a class="card" href="all.html"><h2>Complete API</h2><p>All documented operations, including gateway callbacks and integration routes.</p></a></div>
|
||||||
|
<div class="note"><strong>Works offline.</strong> Open this file directly in a browser after extracting the ZIP. API execution is disabled in this reference bundle; calling the live API requires a running backend and appropriate authorization.</div>
|
||||||
|
<footer>JSON and YAML specifications are included in <code>specs/</code> for import into API tools. Third-party licenses: <a href="THIRD_PARTY_LICENSE.txt">Swagger UI and packaging</a>.</footer>
|
||||||
|
</main></body></html>`
|
||||||
|
|
||||||
|
// Build returns a bundle in memory. Specifications are embedded in the HTML to avoid file:// fetch/CORS restrictions.
|
||||||
|
func Build() (map[string][]byte, error) {
|
||||||
|
files := map[string][]byte{"index.html": []byte(indexTemplate), "THIRD_PARTY_LICENSE.txt": thirdPartyLicense}
|
||||||
|
for _, asset := range []string{"swagger-ui.css", "swagger-ui-bundle.js"} {
|
||||||
|
content, err := swaggerFiles.ReadFile(asset)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("load Swagger UI asset %s: %w", asset, err)
|
||||||
|
}
|
||||||
|
files["assets/"+asset] = content
|
||||||
|
}
|
||||||
|
page, err := template.New("swagger").Parse(pageTemplate)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, audience := range []string{"admin", "client", "all"} {
|
||||||
|
spec, err := apidocs.Specification(audience)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
raw, err := json.MarshalIndent(spec, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
yamlSpec, err := yaml.Marshal(spec)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
name := audience
|
||||||
|
if audience == "client" {
|
||||||
|
name = "customer"
|
||||||
|
}
|
||||||
|
files["specs/"+name+".json"] = append(raw, '\n')
|
||||||
|
files["specs/"+name+".yaml"] = yamlSpec
|
||||||
|
title := "Rezina API"
|
||||||
|
if info, ok := spec["info"].(map[string]any); ok {
|
||||||
|
if value, ok := info["title"].(string); ok {
|
||||||
|
title = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
count := 0
|
||||||
|
if paths, ok := spec["paths"].(map[string]any); ok {
|
||||||
|
for _, value := range paths {
|
||||||
|
if operations, ok := value.(map[string]any); ok {
|
||||||
|
for method := range operations {
|
||||||
|
switch method {
|
||||||
|
case "get", "post", "put", "patch", "delete", "head", "options":
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var html bytes.Buffer
|
||||||
|
// encoding/json escapes HTML metacharacters, so the JSON cannot terminate the surrounding script element.
|
||||||
|
data := struct {
|
||||||
|
Title, Name string
|
||||||
|
Count int
|
||||||
|
Spec template.JS
|
||||||
|
}{title, name, count, template.JS(raw)}
|
||||||
|
if err := page.Execute(&html, data); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
files[name+".html"] = html.Bytes()
|
||||||
|
}
|
||||||
|
files["README.txt"] = []byte("Rezina offline API documentation\n\nExtract the ZIP completely, then open index.html in a modern browser.\nAdmin and customer pages use the same audience-specific specifications as the running application.\nAll JavaScript, CSS, and API specifications are local. No server, CDN, or internet connection is needed to read the documentation.\nAPI execution is disabled. Use the live Swagger pages to call a running API.\nJSON and YAML files for admin, customer, and all APIs are in specs/.\nRegenerate with: go run ./cmd/swagger-export -out exports/swagger-offline\n")
|
||||||
|
return files, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Export writes the folder and a ZIP beside it, without removing existing unrelated files.
|
||||||
|
func Export(output string) (string, error) {
|
||||||
|
files, err := Build()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
output, err = filepath.Abs(output)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if err := os.MkdirAll(output, 0755); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
names := make([]string, 0, len(files))
|
||||||
|
for name := range files {
|
||||||
|
names = append(names, name)
|
||||||
|
}
|
||||||
|
sort.Strings(names)
|
||||||
|
for _, name := range names {
|
||||||
|
target := filepath.Join(output, filepath.FromSlash(name))
|
||||||
|
if err := os.MkdirAll(filepath.Dir(target), 0755); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(target, files[name], 0644); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var archive bytes.Buffer
|
||||||
|
writer := zip.NewWriter(&archive)
|
||||||
|
for _, name := range names {
|
||||||
|
header := &zip.FileHeader{Name: filepath.Base(output) + "/" + strings.ReplaceAll(name, "\\", "/"), Method: zip.Deflate}
|
||||||
|
file, err := writer.CreateHeader(header)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if _, err := file.Write(files[name]); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := writer.Close(); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
zipPath := output + ".zip"
|
||||||
|
if err := os.WriteFile(zipPath, archive.Bytes(), 0644); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return zipPath, nil
|
||||||
|
}
|
||||||
96
internal/apidocs/offline/export_test.go
Normal file
96
internal/apidocs/offline/export_test.go
Normal file
|
|
@ -0,0 +1,96 @@
|
||||||
|
package offline
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/zip"
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestOfflineBundleIncludesLocalAssetsAndSeparatedSpecs(t *testing.T) {
|
||||||
|
files, err := Build()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, name := range []string{"index.html", "admin.html", "customer.html", "all.html", "assets/swagger-ui.css", "assets/swagger-ui-bundle.js", "specs/admin.json", "specs/admin.yaml", "specs/customer.json", "specs/customer.yaml", "specs/all.json", "specs/all.yaml", "README.txt", "THIRD_PARTY_LICENSE.txt"} {
|
||||||
|
if len(files[name]) == 0 {
|
||||||
|
t.Errorf("missing bundle file %s", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, audience := range []string{"admin", "customer", "all"} {
|
||||||
|
html := string(files[audience+".html"])
|
||||||
|
if !strings.Contains(html, "validatorUrl:null") || !strings.Contains(html, "supportedSubmitMethods:[]") {
|
||||||
|
t.Errorf("%s is not configured for offline viewing", audience)
|
||||||
|
}
|
||||||
|
if strings.Contains(html, `src="http`) || strings.Contains(html, `href="https://cdn`) {
|
||||||
|
t.Errorf("%s depends on remote assets", audience)
|
||||||
|
}
|
||||||
|
if !strings.Contains(html, "spec:") || strings.Contains(html, "url: 'specs/") {
|
||||||
|
t.Errorf("%s must embed its spec to support file URLs", audience)
|
||||||
|
}
|
||||||
|
var spec struct {
|
||||||
|
Paths map[string]any `json:"paths"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(files["specs/"+audience+".json"], &spec); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if len(spec.Paths) == 0 {
|
||||||
|
t.Errorf("empty %s spec", audience)
|
||||||
|
}
|
||||||
|
for path := range spec.Paths {
|
||||||
|
if audience == "admin" && !strings.HasPrefix(path, "/api/v1/admin/") {
|
||||||
|
t.Errorf("foreign path in admin spec: %s", path)
|
||||||
|
}
|
||||||
|
if audience == "customer" && strings.HasPrefix(path, "/api/v1/admin/") {
|
||||||
|
t.Errorf("admin path in customer spec: %s", path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExportCreatesPortableZIPWithoutUnrelatedFiles(t *testing.T) {
|
||||||
|
output := filepath.Join(t.TempDir(), "swagger-offline")
|
||||||
|
if err := os.MkdirAll(output, 0755); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
unrelated := filepath.Join(output, "private-notes.txt")
|
||||||
|
if err := os.WriteFile(unrelated, []byte("preserve"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
archive, err := Export(output)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.HasSuffix(archive, ".zip") {
|
||||||
|
t.Fatal("missing ZIP archive")
|
||||||
|
}
|
||||||
|
raw, err := os.ReadFile(archive)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
reader, err := zip.NewReader(bytes.NewReader(raw), int64(len(raw)))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
foundIndex := false
|
||||||
|
for _, file := range reader.File {
|
||||||
|
if file.Name == "swagger-offline/index.html" {
|
||||||
|
foundIndex = true
|
||||||
|
}
|
||||||
|
if strings.Contains(file.Name, "private-notes") {
|
||||||
|
t.Error("export included an unrelated local file")
|
||||||
|
}
|
||||||
|
if strings.Contains(file.Name, "..") || strings.Contains(file.Name, "\\") {
|
||||||
|
t.Errorf("unsafe archive path %s", file.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !foundIndex {
|
||||||
|
t.Error("ZIP does not contain the documentation index")
|
||||||
|
}
|
||||||
|
if data, err := os.ReadFile(unrelated); err != nil || string(data) != "preserve" {
|
||||||
|
t.Error("export changed an unrelated file")
|
||||||
|
}
|
||||||
|
}
|
||||||
231
internal/apidocs/offline/swagger_ui_license.txt
Normal file
231
internal/apidocs/offline/swagger_ui_license.txt
Normal file
|
|
@ -0,0 +1,231 @@
|
||||||
|
Swagger UI - Apache License 2.0
|
||||||
|
https://github.com/swagger-api/swagger-ui
|
||||||
|
|
||||||
|
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
|
|
||||||
|
|
||||||
|
Swaggo files packaging - MIT License
|
||||||
|
https://github.com/swaggo/files
|
||||||
|
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2019 Swaggo
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
82
internal/apidocs/specification.go
Normal file
82
internal/apidocs/specification.go
Normal file
|
|
@ -0,0 +1,82 @@
|
||||||
|
// 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
|
||||||
|
}
|
||||||
23
internal/apidocs/specification_test.go
Normal file
23
internal/apidocs/specification_test.go
Normal file
|
|
@ -0,0 +1,23 @@
|
||||||
|
package apidocs
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestSpecificationRejectsUnknownAudience(t *testing.T) {
|
||||||
|
if _, err := Specification("unknown"); err == nil {
|
||||||
|
t.Fatal("unknown audience accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func TestSpecificationsDoNotShareMutableState(t *testing.T) {
|
||||||
|
first, err := Specification("admin")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
first["paths"] = nil
|
||||||
|
second, err := Specification("admin")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if second["paths"] == nil {
|
||||||
|
t.Fatal("mutating an export changed later specifications")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,77 +1,17 @@
|
||||||
package httpserver
|
package httpserver
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"Rezina-Backend/docs"
|
"Rezina-Backend/internal/apidocs"
|
||||||
"encoding/json"
|
|
||||||
"github.com/gofiber/fiber/v2"
|
"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.
|
// audienceSpecification exposes only an audience's routes and referenced schemas.
|
||||||
func audienceSpecification(audience string) fiber.Handler {
|
func audienceSpecification(audience string) fiber.Handler {
|
||||||
return func(c *fiber.Ctx) error {
|
return func(c *fiber.Ctx) error {
|
||||||
var spec map[string]any
|
spec, err := apidocs.Specification(audience)
|
||||||
if err := json.Unmarshal([]byte(docs.SwaggerInfo.ReadDoc()), &spec); err != nil {
|
if err != nil {
|
||||||
return fiber.NewError(500, "Unable to load API documentation")
|
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)
|
return c.JSON(spec)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
4
makefile
4
makefile
|
|
@ -88,6 +88,10 @@ postgres_log:
|
||||||
.PHONY: swagger
|
.PHONY: swagger
|
||||||
swagger:
|
swagger:
|
||||||
@swag init -g cmd/main.go
|
@swag init -g cmd/main.go
|
||||||
|
.PHONY: swagger-export
|
||||||
|
swagger-export: swagger
|
||||||
|
@go run ./cmd/swagger-export -out exports/swagger-offline
|
||||||
|
|
||||||
.PHONY: swagger-check
|
.PHONY: swagger-check
|
||||||
swagger-check: swagger
|
swagger-check: swagger
|
||||||
@go test ./internal/web_server -run 'TestSwagger|TestGeneratedSwagger|TestAudienceSpecifications'
|
@go test ./internal/web_server -run 'TestSwagger|TestGeneratedSwagger|TestAudienceSpecifications'
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user