+
+func checkAuth(handler http.HandlerFunc) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ username, password, gotAuth := r.BasicAuth()
+ var user *User
+ if gotAuth {
+ PasswordsM.RLock()
+ user = Passwords[username]
+ PasswordsM.RUnlock()
+ }
+ var passwordValid bool
+ if gotAuth && user != nil {
+ passwordValid = user.auther.Auth(password)
+ }
+ if (gotAuth && user == nil) ||
+ (user != nil && !passwordValid) ||
+ (*AuthRequired && !gotAuth) {
+ log.Println(r.RemoteAddr, "unauthenticated", username)
+ http.Error(w, "unauthenticated", http.StatusUnauthorized)
+ return
+ }
+ handler(w, r.WithContext(context.WithValue(r.Context(), CtxUserKey, user)))
+ }
+}