diff options
author | Alexander Neonxp Kiryukhin <i@neonxp.ru> | 2024-08-31 02:05:36 +0300 |
---|---|---|
committer | Alexander Neonxp Kiryukhin <i@neonxp.ru> | 2024-08-31 02:05:36 +0300 |
commit | 5094ebf213243023c6325310b3f710a0974025dd (patch) | |
tree | 98b501b07271645f924b70af00bf8792d6062d65 /middleware | |
parent | 376839b264c7f77b2540ad9f83bd8baf44063f17 (diff) |
Обновление muxv0.0.1
Diffstat (limited to 'middleware')
-rw-r--r-- | middleware/basic_auth.go | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/middleware/basic_auth.go b/middleware/basic_auth.go new file mode 100644 index 0000000..847ee79 --- /dev/null +++ b/middleware/basic_auth.go @@ -0,0 +1,44 @@ +package middleware + +import ( + "fmt" + "net/http" + "strings" + + "go.neonxp.ru/mux" +) + +const basicAuthScheme = "Basic" + +type BasicAuthConfig struct { + Skipper func(r *http.Request) bool + Realm string + Validator func(r *http.Request, login, password string) error +} + +func DefaultSkipper(*http.Request) bool { + return false +} + +func BasicAuth(config BasicAuthConfig) mux.Middleware { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if config.Skipper(r) { + next.ServeHTTP(w, r) + return + } + authString := r.Header.Get("Authorization") + if authString == "" { + w.Header().Set("WWW-Authenticate", fmt.Sprintf(`%s realm="%s", charset="UTF-8"`, basicAuthScheme, config.Realm)) + w.WriteHeader(http.StatusUnauthorized) + return + } + parts := strings.SplitN(authString, " ", 2) + if strings.EqualFold(parts[0], basicAuthScheme) { + w.Header().Set("WWW-Authenticate", fmt.Sprintf(`%s realm="%s", charset="UTF-8"`, basicAuthScheme, config.Realm)) + w.WriteHeader(http.StatusUnauthorized) + return + } + }) + } +} |