| 1 |
package httphandler |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"net/http" |
| 6 |
"strings" |
| 7 |
|
| 8 |
"github.com/jkroepke/openvpn-auth-oauth2/v2/internal/config" |
| 9 |
"github.com/jkroepke/openvpn-auth-oauth2/v2/internal/oauth2" |
| 10 |
) |
| 11 |
|
| 12 |
// New returns a ServeMux with all HTTP endpoints for the management listener. |
| 13 |
// |
| 14 |
// The handlers are mounted under the base path from conf.HTTP.BaseURL and |
| 15 |
// register the following routes: |
| 16 |
// - GET <basePath>/ready readiness probe responding with "OK". |
| 17 |
// - GET <basePath>/assets/* serves embedded or custom static files. |
| 18 |
// - GET <basePath>/oauth2/start initiates the OAuth2 login flow. |
| 19 |
// - GET <basePath>/oauth2/callback handles the OAuth2 redirect. |
| 20 |
// All other paths respond with 404 via http.NotFoundHandler. |
| 21 |
// The returned mux can be passed to an HTTP server directly. |
| 22 |
|
| 23 |
func New(conf *config.Config, oAuth2Client *oauth2.Client) *http.ServeMux { |
| 24 |
basePath := strings.TrimSuffix(conf.HTTP.BaseURL.Path, "/") |
| 25 |
|
| 26 |
mux := http.NewServeMux() |
| 27 |
if basePath != "" { |
| 28 |
mux.Handle("/", http.NotFoundHandler()) |
| 29 |
} |
| 30 |
|
| 31 |
mux.Handle(fmt.Sprintf("GET %s/", basePath), noCacheHeaders(http.NotFoundHandler())) |
| 32 |
mux.Handle(fmt.Sprintf("GET %s/ready", basePath), http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 33 |
w.WriteHeader(http.StatusOK) |
| 34 |
_, _ = w.Write([]byte("OK")) |
| 35 |
})) |
| 36 |
mux.Handle(fmt.Sprintf("GET %s/assets/", basePath), http.StripPrefix(basePath+"/assets/", http.FileServerFS(conf.HTTP.AssetPath))) |
| 37 |
mux.Handle(fmt.Sprintf("GET %s/oauth2/start", basePath), noCacheHeaders(oAuth2Client.OAuth2Start())) |
| 38 |
mux.Handle(fmt.Sprintf("GET %s/oauth2/callback", basePath), noCacheHeaders(oAuth2Client.OAuth2Callback())) |
| 39 |
mux.Handle(fmt.Sprintf("POST %s/oauth2/profile-submit", basePath), noCacheHeaders(oAuth2Client.OAuth2ProfileSubmit())) |
| 40 |
|
| 41 |
return mux |
| 42 |
} |
| 43 |
|
| 44 |
func noCacheHeaders(h http.Handler) http.Handler { |
| 45 |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 46 |
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") |
| 47 |
w.Header().Set("Pragma", "no-cache") |
| 48 |
w.Header().Set("Expires", "0") |
| 49 |
h.ServeHTTP(w, r) |
| 50 |
}) |
| 51 |
} |