summaryrefslogtreecommitdiff
path: root/middleware/basic_auth.go
blob: 847ee79b261057694fc63de362fb7d12242b1f0d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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
			}
		})
	}
}