// BasicAuthHandler is middleware to check HTTP Basic Authentication
// if an authorisation function is defined.
512064
func BasicAuthHandler(h http.Handler) http.Handler {
	f := func(w http.ResponseWriter, req *http.Request) {
		if Authorised == nil {
			h.ServeHTTP(w, req)
			return
		}

		u, pw, ok := req.BasicAuth()
		if !ok || !Authorised(u, pw) {
			w.Header().Set("WWW-Authenticate", "Basic")
			w.WriteHeader(401)
			return
		}
		h.ServeHTTP(w, req)
	}

	return http.HandlerFunc(f)
}
1374557
func BasicAuth(username, password string) http.HandlerFunc {
	// Inspired by https://github.com/codegangsta/martini-contrib/blob/master/auth/
	return func(res http.ResponseWriter, req *http.Request) {
		if !secureCompare(req.Header.Get("Authorization"),
			"Basic "+base64.StdEncoding.EncodeToString([]byte(username+":"+password)),
		) {
			res.Header().Set("WWW-Authenticate",
				"Basic realm=\"Authorization Required\"",
			)
			http.Error(res, "Not Authorized", http.StatusUnauthorized)
		}
	}
}
1163391
func WrapHandlerForAuthCreds(h http.Handler, adminuser, adminpass, authrealm string) http.Handler {
	if adminuser == "" && adminpass == "" {
		return h
	}
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if isAuthenticated(r, adminuser, adminpass) {
			if AuthRequest != nil {
				AuthRequest(r, AuthSuccess)
			}
			h.ServeHTTP(w, r)
		} else {
			if AuthRequest != nil {
				AuthRequest(r, AuthFailure)
			}
			w.Header().Set("WWW-Authenticate", `Basic realm="`+authrealm+`"`)
			w.WriteHeader(http.StatusUnauthorized)
			w.Write([]byte("Unauthorized\n"))
		}
	})
}
1127476
func (a *Auth) Handler(h http.Handler) http.Handler {
	a.ensureDefaults()
	return &handler{Auth: a, handler: h}
}
814649
func BasicAuthHandlerFunc(h http.HandlerFunc,
	authFn func(string, string) (interface{}, bool), realm string) http.HandlerFunc {
	return BasicAuthHandler(h, authFn, realm)
}
1154472
func UseAuthenticator(a BasicHTTPAuthenticator) Option {
	return func(p *Plugin) {
		p.Deps.Authenticator = a
	}
}
1253746
func BasicAuth(username, password string) ClientOpt {
	return func(c *Client) {
		c.Handlers.Build.Append(request.BasicAuther(username, password))
	}
}
1360130
func authHandler(handler http.Handler) http.Handler {
	auth := readBasicAuth()
	if auth.Username != "" && auth.Password != "" {
		log.Infoln("HTTP Basic authentication is enabled.")
		return &basicAuthHandler{basicAuth: *auth, nextHandler: handler}
	}

	return handler
}
264702
func (b *basicAuth) simpleBasicAuthFunc(user, pass string, r *http.Request) bool {
	// Equalize lengths of supplied and required credentials
	// by hashing them
	givenUser := sha256.Sum256([]byte(user))
	givenPass := sha256.Sum256([]byte(pass))
	requiredUser := sha256.Sum256([]byte(b.opts.User))
	requiredPass := sha256.Sum256([]byte(b.opts.Password))

	// Compare the supplied credentials to those set in our options
	if subtle.ConstantTimeCompare(givenUser[:], requiredUser[:]) == 1 &&
		subtle.ConstantTimeCompare(givenPass[:], requiredPass[:]) == 1 {
		return true
	}

	return false
}
868348
func (a *authenticator) loginHandler(w http.ResponseWriter, req *http.Request) {
	// GET returns login page. Submit redirects to authenticate.
	if req.Method == http.MethodGet {
		r := render.New(render.Options{
			Directory:  "templates",
			Asset:      Asset,
			AssetNames: AssetNames,
		})
		r.HTML(w, http.StatusOK, "login", nil)
	} else {
		// POST decodes provided credentials
		credentials := &credentials{}
		decoder := json.NewDecoder(req.Body)
		err := decoder.Decode(&credentials)
		if err != nil {
			errStr := fmt.Sprintf("500 internal server error: failed to decode json: %v", err)
			a.formatter.Text(w, http.StatusInternalServerError, errStr)
			return
		}
		token, errCode, err := a.getTokenFor(credentials)
		if err != nil {
			a.formatter.Text(w, errCode, err.Error())
			return
		}

		// Returns token string.
		a.formatter.Text(w, http.StatusOK, token)
	}
}
757451
func (a *authenticator) authenticationHandler(w http.ResponseWriter, req *http.Request) {
	// Read name and password from the form (if accessed from browser)
	credentials := &credentials{
		Username: req.FormValue("name"),
		Password: req.FormValue("password"),
	}
	token, errCode, err := a.getTokenFor(credentials)
	if err != nil {
		a.formatter.Text(w, errCode, err.Error())
		return
	}
	// Writes cookie with token.
	http.SetCookie(w, &http.Cookie{
		Name:   cookieName,
		Path:   "/",
		MaxAge: int(a.expTime.Seconds()),
		Value:  token,
		Secure: false,
	})
	// Automatically move to index page.
	target := "/"
	http.Redirect(w, req, target, http.StatusMovedPermanently)
}
379396
func BasicAuth(username, passwd string) ConfigOpt {
	// TODO(jdef) this could be more efficient. according to the stdlib we're not supposed to
	// mutate the original Request, so we copy here (including headers). another approach would
	// be to generate a functional RequestOpt that adds the right header.
	return WrapRoundTripper(func(rt http.RoundTripper) http.RoundTripper {
		return roundTripperFunc(func(req *http.Request) (*http.Response, error) {
			var h http.Header
			if req.Header != nil {
				h = make(http.Header, len(req.Header))
				for k, v := range req.Header {
					h[k] = append(make([]string, 0, len(v)), v...)
				}
			}
			clonedReq := *req
			clonedReq.Header = h
			clonedReq.SetBasicAuth(username, passwd)
			return rt.RoundTrip(&clonedReq)
		})
	})
}
983220
func (statics *AssestStruct) HttpHandler(pdir string) http.Handler {
	return &_assestFileServer{sf: statics, pdir: pdir}
}
558053
func NewAuthorizationHandler(userService platform.UserService) *AuthorizationHandler {
	h := &AuthorizationHandler{
		Router:      NewRouter(),
		Logger:      zap.NewNop(),
		UserService: userService,
	}

	h.HandlerFunc("POST", "/api/v2/authorizations", h.handlePostAuthorization)
	h.HandlerFunc("GET", "/api/v2/authorizations", h.handleGetAuthorizations)
	h.HandlerFunc("GET", "/api/v2/authorizations/:id", h.handleGetAuthorization)
	h.HandlerFunc("PATCH", "/api/v2/authorizations/:id", h.handleSetAuthorizationStatus)
	h.HandlerFunc("DELETE", "/api/v2/authorizations/:id", h.handleDeleteAuthorization)
	return h
}
173383
func BasicAuth(fn BasicAuthValidator) echo.MiddlewareFunc {
	c := DefaultBasicAuthConfig
	c.Validator = fn
	return BasicAuthWithConfig(c)
}
487285
func BasicAuthSecurity(name string, dsl ...func()) *design.SecuritySchemeDefinition {
	switch dslengine.CurrentDefinition().(type) {
	case *design.APIDefinition, *dslengine.TopLevelDefinition:
	default:
		dslengine.IncompatibleDSL()
		return nil
	}

	if securitySchemeRedefined(name) {
		return nil
	}

	def := &design.SecuritySchemeDefinition{
		Kind:       design.BasicAuthSecurityKind,
		SchemeName: name,
		Type:       "basic",
	}

	if len(dsl) != 0 {
		def.DSLFunc = dsl[0]
	}

	design.Design.SecuritySchemes = append(design.Design.SecuritySchemes, def)

	return def
}
1037753
func (c *BasicAuth) GetAuthorization() string {
	return fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", c.Username, c.Password))))
}