// GetBasicAuth returns the decoded user and password from the context's
// 'Authorization' header.
425546
func (ctx *Context) GetBasicAuth() (string, string, error) {
	if len(ctx.Request.Header["Authorization"]) == 0 {
		return "", "", errors.New("No Authorization header provided")
	}
	authHeader := ctx.Request.Header["Authorization"][0]
	authString := strings.Split(string(authHeader), " ")
	if authString[0] != "Basic" {
		return "", "", errors.New("Not Basic Authentication")
	}
	decodedAuth, err := base64.StdEncoding.DecodeString(authString[1])
	if err != nil {
		return "", "", err
	}
	authSlice := strings.Split(string(decodedAuth), ":")
	if len(authSlice) != 2 {
		return "", "", errors.New("Error delimiting authString into username/password. Malformed input: " + authString[1])
	}
	return authSlice[0], authSlice[1], nil
}
403320
func MiddlewareBasicAuth(username, password string) Middleware {
	return func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
			// Basic auth
			if handleBasicAuth(username, password, rw, r) {
				return
			}

			// Next handler
			h.ServeHTTP(rw, r)
		})
	}
}
637761
func getBasicAuthInfo(r *http.Request) (string, string, bool, error) {
	// Retrieve the Authorization header and check whether it contains basic auth information
	const basicScheme string = "Basic "
	auth := r.Header.Get("Authorization")

	if !strings.HasPrefix(auth, basicScheme) {
		return "", "", false, nil
	}

	str, err := base64.StdEncoding.DecodeString(auth[len(basicScheme):])
	if err != nil {
		return "", "", false, errors.New("no valid base64 data in basic auth scheme found")
	}

	cred := strings.SplitN(string(str), ":", 2)
	if len(cred) < 2 {
		return "", "", false, errors.New("invalid Authorization header")
	}

	username, password := cred[0], cred[1]

	// empty user or pass is not an error but we do not want to try to authenticate in this case
	if len(username) == 0 || len(password) == 0 {
		return "", "", false, nil
	}

	return username, password, true, nil
}
257943
func (G *global_data) BasicAuth(user, passwd string) *global_data {
	G.Req.BasicAuth = request.BasicAuth{user, passwd}
	return G
}
729964
func (h *AuthorizationHandler) handleGetAuthorizations(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	req, err := decodeGetAuthorizationsRequest(ctx, r)
	if err != nil {
		h.Logger.Info("failed to decode request", zap.String("handler", "getAuthorizations"), zap.Error(err))
		EncodeError(ctx, err, w)
		return
	}

	opts := platform.FindOptions{}
	as, _, err := h.AuthorizationService.FindAuthorizations(ctx, req.filter, opts)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	auths := make([]*authResponse, 0, len(as))
	for _, a := range as {
		o, err := h.OrganizationService.FindOrganizationByID(ctx, a.OrgID)
		if err != nil {
			h.Logger.Info("failed to get organization", zap.String("handler", "getAuthorizations"), zap.String("orgID", a.OrgID.String()), zap.Error(err))
			continue
		}

		u, err := h.UserService.FindUserByID(ctx, a.UserID)
		if err != nil {
			h.Logger.Info("failed to get user", zap.String("handler", "getAuthorizations"), zap.String("userID", a.UserID.String()), zap.Error(err))
			continue
		}

		ps, err := newPermissionsResponse(ctx, a.Permissions, h.LookupService)
		if err != nil {
			EncodeError(ctx, err, w)
			return
		}

		auths = append(auths, newAuthResponse(a, o, u, ps))
	}

	if err := encodeResponse(ctx, w, http.StatusOK, newAuthsResponse(auths)); err != nil {
		EncodeError(ctx, err, w)
		return
	}
}
229590
func GetAuthorizer(ctx context.Context) (platform.Authorizer, error) {
	a, ok := ctx.Value(authorizerCtxKey).(platform.Authorizer)
	if !ok {
		return nil, &platform.Error{
			Msg:  "authorizer not found on context",
			Code: platform.EInternal,
		}
	}

	return a, nil
}
1252382
func BasicAuthFromContext(ctx context.Context) (*BasicAuth, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return nil, nil
	}
	authorization, ok := md["Authorization"]
	if !ok {
		authorization, ok = md["authorization"]
		if !ok {
			return nil, nil
		}
	}
	if len(authorization) != 1 {
		return nil, ErrInvalidAuthorization
	}
	if !strings.HasPrefix(authorization[0], "Basic ") {
		return nil, ErrInvalidAuthorization
	}
	decoded, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(authorization[0], "Basic "))
	if err != nil {
		return nil, err
	}
	split := strings.SplitN(string(decoded), ":", 2)
	if len(split) != 2 {
		return nil, ErrInvalidAuthorization
	}
	return &BasicAuth{
		Username: split[0],
		Password: split[1],
	}, nil
}
49628
func RouterMiddlewareBasicAuth(username, password string) RouterMiddleware {
	return func(h httprouter.Handle) httprouter.Handle {
		return func(rw http.ResponseWriter, r *http.Request, p httprouter.Params) {
			// Basic auth
			if handleBasicAuth(username, password, rw, r) {
				return
			}

			// Next handler
			h(rw, r, p)
		}
	}
}
187211
func BasicAuth(req *http.Request) (username, password string, err error) {
	auth := req.Header.Get("Authorization")
	if auth == "" {
		err = fmt.Errorf("Missing \"Authorization\" in header")
		return
	}
	matches := kBasicAuthPattern.FindStringSubmatch(auth)
	if len(matches) != 2 {
		err = fmt.Errorf("Bogus Authorization header")
		return
	}
	encoded := matches[1]
	enc := base64.StdEncoding
	decBuf := make([]byte, enc.DecodedLen(len(encoded)))
	n, err := enc.Decode(decBuf, []byte(encoded))
	if err != nil {
		return
	}
	pieces := strings.SplitN(string(decBuf[0:n]), ":", 2)
	if len(pieces) != 2 {
		err = fmt.Errorf("didn't get two pieces")
		return
	}
	return pieces[0], pieces[1], nil
}
365299
func (s *CreateBranchInput) SetBasicAuthCredentials(v string) *CreateBranchInput {
	s.BasicAuthCredentials = &v
	return s
}
506827
func (r Request) AddBasicAuth(username string, password string) Request {
	r.BasicAuth.Password = password
	r.BasicAuth.Username = username
	return r
}
50460
func (vb *VirtualBox) UseBasicAuth(flag bool) *VirtualBox {
	vb.useBasicAuth = true
	return vb
}
219152
func DecorateWithBasicAuth(next http.HandlerFunc, credentials *BasicAuthCredentials) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {

		user, password, ok := r.BasicAuth()
		w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)

		if !ok || !(credentials.Password == password && user == credentials.User) {

			w.WriteHeader(http.StatusUnauthorized)
			w.Write([]byte("invalid credentials"))
			return
		}

		next.ServeHTTP(w, r)
	}
}
41911
func (k *Client) SetBasicAuth(username string, password string) {
	k.BasicAuth = struct{ UserName, Password string }{username, password}

}
860386
func (s *Sling) SetBasicAuth(username, password string) *Sling {
	return s.Set("Authorization", "Basic "+basicAuth(username, password))
}
650550
func httpBasicAuth(username, password string) []byte {
	const header = "Basic "
	base64 := base64.StdEncoding

	b64InputLen := len(username) + len(":") + len(password)
	b64Input := make([]byte, 0, b64InputLen)
	b64Input = append(b64Input, username...)
	b64Input = append(b64Input, ':')
	b64Input = append(b64Input, password...)

	output := make([]byte, len(header)+base64.EncodedLen(b64InputLen))
	copy(output, header)
	base64.Encode(output[len(header):], b64Input)
	return output
}
628690
func getOAuth() *oauth.Config {
	return oauth.OAuth(viper.GetString("auth-server"), &oauth.Client{
		ID:     "ttnctl",
		Secret: "ttnctl",
		ExtraHeaders: map[string]string{
			"User-Agent": GetUserAgent(),
		},
	})
}