Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add OAuth config and rework URL config #25

Merged
merged 10 commits into from
May 30, 2022
95 changes: 66 additions & 29 deletions swagger.go
Original file line number Diff line number Diff line change
@@ -1,25 +1,47 @@
package echoSwagger

import (
"html/template"
"net/http"
"regexp"

"github.com/labstack/echo/v4"
"github.com/swaggo/files"
"github.com/swaggo/swag"
"html/template"
"log"
"net/http"
"path"
)

// Config stores echoSwagger configuration variables.
type Config struct {
//The url pointing to API definition (normally swagger.json or swagger.yaml). Default is `doc.json`.
URL string
// If the Swagger specification JSON document is external to the web server, this should be set to the full URL
// to the specification document.
ExternalURL *string

// The information for OAuth2 integration, if any.
OAuth *OAuthConfig
}

// Configuration for Swagger UI OAuth2 integration. See
// https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/ for further details.
type OAuthConfig struct {
// The ID of the client sent to the OAuth2 IAM provider.
ClientId string

// The OAuth2 realm that the client should operate in. If not applicable, use empty string.
Realm string

// The name to display for the application in the authentication popup.
AppName string
}

type templateData struct {
SwaggerSpecFullURL string
Config
}

// URL presents the url pointing to API definition (normally swagger.json or swagger.yaml).
func URL(url string) func(c *Config) {
return func(c *Config) {
c.URL = url
c.ExternalURL = &url
}
}

Expand All @@ -31,44 +53,51 @@ func EchoWrapHandler(confs ...func(c *Config)) echo.HandlerFunc {

handler := swaggerFiles.Handler

config := &Config{
URL: "doc.json",
}
config := &Config{}

for _, c := range confs {
c(config)
}

// create a template with name
t := template.New("swagger_index.html")
index, _ := t.Parse(indexTempl)

type pro struct {
Host string
index, err := t.Parse(indexTempl)
if err != nil {
log.Fatal("Unable to parse index.html template for echo-swagger:", err)
}

var re = regexp.MustCompile(`(.*)(index\.html|doc\.json|favicon-16x16\.png|favicon-32x32\.png|/oauth2-redirect\.html|swagger-ui\.css|swagger-ui\.css\.map|swagger-ui\.js|swagger-ui\.js\.map|swagger-ui-bundle\.js|swagger-ui-bundle\.js\.map|swagger-ui-standalone-preset\.js|swagger-ui-standalone-preset\.js\.map)[\?|.]*`)

return func(c echo.Context) error {
var matches []string
if matches = re.FindStringSubmatch(c.Request().RequestURI); len(matches) != 3 {
prefix, pathFile := path.Split(c.Request().RequestURI)
handler.Prefix = prefix

return c.String(http.StatusNotFound, "404 page not found")
templateData := templateData{
SwaggerSpecFullURL: path.Join(prefix, "doc.json"),
Config: *config,
}
path := matches[2]
prefix := matches[1]
handler.Prefix = prefix

switch path {
case "index.html":
if config.ExternalURL != nil {
// Configuration specifies override for Swagger specification URL.
templateData.SwaggerSpecFullURL = *config.ExternalURL
}

index.Execute(c.Response().Writer, config)
switch pathFile {
case "":
fallthrough
case "index.html":
if err := index.Execute(c.Response().Writer, templateData); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err)
}
case "doc.json":
doc, _ := swag.ReadDoc()
c.Response().Write([]byte(doc))
doc, err := swag.ReadDoc()
if err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err)
}
c.Response().Header().Set("Content-Type", "application/json")
if _, err := c.Response().Write([]byte(doc)); err != nil {
return echo.NewHTTPError(http.StatusInternalServerError, err)
}
default:
handler.ServeHTTP(c.Response().Writer, c.Request())

}

return nil
Expand Down Expand Up @@ -150,7 +179,7 @@ const indexTempl = `<!-- HTML for static distribution bundle build -->
window.onload = function() {
// Build a system
const ui = SwaggerUIBundle({
url: "{{.URL}}",
url: "{{.SwaggerSpecFullURL}}",
dom_id: '#swagger-ui',
validatorUrl: null,
presets: [
Expand All @@ -163,6 +192,14 @@ window.onload = function() {
layout: "StandaloneLayout"
})

{{if .OAuth}}
ui.initOAuth({
clientId: "{{.OAuth.ClientId}}",
realm: "{{.OAuth.Realm}}",
appName: "{{.OAuth.AppName}}"
})
{{end}}

window.ui = ui
}
</script>
Expand Down
49 changes: 43 additions & 6 deletions swagger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,60 @@ import (
)

func TestWrapHandler(t *testing.T) {

router := echo.New()

router.GET("/*", WrapHandler)

w1 := performRequest("GET", "/index.html", router)
w1 := performRequest("GET", "/", router)
assert.Equal(t, 200, w1.Code)

w2 := performRequest("GET", "/doc.json", router)
w2 := performRequest("GET", "/index.html", router)
assert.Equal(t, 200, w2.Code)
assert.Equal(t, w1.Body.String(), w2.Body.String())

w3 := performRequest("GET", "/favicon-16x16.png", router)
w3 := performRequest("GET", "/doc.json", router)
assert.Equal(t, 200, w3.Code)

w4 := performRequest("GET", "/notfound", router)
assert.Equal(t, 404, w4.Code)
w4 := performRequest("GET", "/favicon-16x16.png", router)
assert.Equal(t, 200, w4.Code)

w5 := performRequest("GET", "/notfound", router)
assert.Equal(t, 404, w5.Code)

w6 := performRequest("GET", "/index.htmlnotfound", router)
assert.Equal(t, 404, w6.Code)
}

func TestConfig(t *testing.T) {
router := echo.New()

swaggerHandler := URL("http://example.org/swagger.json")
router.GET("/*", EchoWrapHandler(swaggerHandler))

w := performRequest("GET", "/", router)
assert.Equal(t, 200, w.Code)
assert.Contains(t, w.Body.String(), "url: \"http:\\/\\/example.org\\/swagger.json\"")
}

func TestConfigWithOAuth(t *testing.T) {
router := echo.New()

swaggerHandler := EchoWrapHandler(func(c *Config) {
c.OAuth = &OAuthConfig{
ClientId: "my-client-id",
Realm: "my-realm",
AppName: "My App Name",
}
})
router.GET("/*", swaggerHandler)

w := performRequest("GET", "/", router)
assert.Equal(t, 200, w.Code)
body := w.Body.String()
assert.Contains(t, body, "initOAuth({")
assert.Contains(t, body, "clientId: \"my-client-id\"")
assert.Contains(t, body, "realm: \"my-realm\"")
assert.Contains(t, body, "appName: \"My App Name\"")
}

func performRequest(method, target string, e *echo.Echo) *httptest.ResponseRecorder {
Expand Down