// MaybeUnauthorizedf checks if the cause of the given error is a Mongo
// authorization error, and if so, wraps the error with errors.Unauthorizedf.
173512
func MaybeUnauthorizedf(err error, message string, args ...interface{}) error {
	if isUnauthorized(errors.Cause(err)) {
		err = errors.Unauthorizedf("unauthorized mongo access: %s", err)
	}
	return errors.Annotatef(err, message, args...)
}
1283802
func (s *AuthorizationService) FindAuthorizations(ctx context.Context, filter platform.AuthorizationFilter, opt ...platform.FindOptions) (as []*platform.Authorization, i int, err error) {
	defer func() {
		if err != nil {
			s.Logger.Info("error finding authorizations", zap.Error(err))
		}
	}()

	return s.AuthorizationService.FindAuthorizations(ctx, filter, opt...)
}
1045047
func Unauthorized(w http.ResponseWriter, r *http.Request, domain string) {
	handlerMu.RLock()
	f, ok := handlerMap[http.StatusUnauthorized]
	handlerMu.RUnlock()
	if ok {
		r = ctxSetDomain(r, domain)
		f.ServeHTTP(w, r)
	} else {
		defaultUnauthorized(w, r, domain)
	}
}
1066505
func NOutOf(n int32, policies []*cb.SignaturePolicy) *cb.SignaturePolicy {
	return &cb.SignaturePolicy{
		Type: &cb.SignaturePolicy_NOutOf_{
			NOutOf: &cb.SignaturePolicy_NOutOf{
				N:     n,
				Rules: policies,
			},
		},
	}
}
470821
func (authorization Authorization) FilterAuthorizedScopes(requestedscopes []string) (authorizedScopes []string) {
	authorizedScopes = make([]string, 0, len(requestedscopes))
	for _, rawscope := range requestedscopes {
		scope := strings.TrimSpace(rawscope)
		if scope == "user:name" && authorization.Name {
			authorizedScopes = append(authorizedScopes, scope)
		}
		if strings.HasPrefix(scope, "user:memberof:") {
			requestedorgid := strings.TrimPrefix(scope, "user:memberof:")
			if authorization.ContainsOrganization(requestedorgid) {
				authorizedScopes = append(authorizedScopes, scope)
			}
		}
		if strings.HasPrefix(scope, "user:organizations:") {
			authorizedScopes = append(authorizedScopes, scope)
		}
		if scope == "user:github" && authorization.Github {
			authorizedScopes = append(authorizedScopes, scope)
		}
		if scope == "user:facebook" && authorization.Facebook {
			authorizedScopes = append(authorizedScopes, scope)
		}
		if strings.HasPrefix(scope, "user:address") && LabelledPropertyIsAuthorized(scope, "user:address", authorization.Addresses) {
			authorizedScopes = append(authorizedScopes, scope)
		}
		if strings.HasPrefix(scope, "user:bankaccount") && LabelledPropertyIsAuthorized(scope, "user:bankaccount", authorization.BankAccounts) {
			authorizedScopes = append(authorizedScopes, scope)
		}
		if strings.HasPrefix(scope, "user:digitalwalletaddress") && DigitalWalletIsAuthorized(scope, "user:digitalwalletaddress", authorization.DigitalWallet) {
			authorizedScopes = append(authorizedScopes, scope)
		}
		if strings.HasPrefix(scope, "user:email") && LabelledPropertyIsAuthorized(scope, "user:email", authorization.EmailAddresses) {
			authorizedScopes = append(authorizedScopes, scope)
		}
		if strings.HasPrefix(scope, "user:phone") && LabelledPropertyIsAuthorized(scope, "user:phone", authorization.Phonenumbers) {
			authorizedScopes = append(authorizedScopes, scope)
		}
		if strings.HasPrefix(scope, "user:validated:email") && LabelledPropertyIsAuthorized(scope, "user:validated:email", authorization.ValidatedEmailAddresses) {
			authorizedScopes = append(authorizedScopes, scope)
		}
		if strings.HasPrefix(scope, "user:validated:phone") && LabelledPropertyIsAuthorized(scope, "user:validated:phone", authorization.ValidatedPhonenumbers) {
			authorizedScopes = append(authorizedScopes, scope)
		}
		if strings.HasPrefix(scope, "user:publickey") && LabelledPropertyIsAuthorized(scope, "user:publickey", authorization.PublicKeys) {
			authorizedScopes = append(authorizedScopes, scope)
		}
		if strings.HasPrefix(scope, "user:ownerof:email") && OwnerOfIsAuthorized(scope, "user:ownerof:email", authorization.OwnerOf.EmailAddresses) {
			authorizedScopes = append(authorizedScopes, scope)
		}
		if strings.HasPrefix(scope, "user:avatar") && LabelledPropertyIsAuthorized(scope, "user:avatar", authorization.Avatars) {
			authorizedScopes = append(authorizedScopes, scope)
		}
		if scope == "user:keystore" && authorization.KeyStore {
			authorizedScopes = append(authorizedScopes, scope)
		}
		if scope == "user:see" && authorization.See {
			authorizedScopes = append(authorizedScopes, scope)
		}

		// oidc scopes
		if scope == "openid" {
			authorizedScopes = append(authorizedScopes, scope)
		}
	}

	return
}
1078050
func vpcNotUsablef(optionalCause error, format string, args ...interface{}) error {
	outerErr := errors.Errorf(format, args...)
	if optionalCause != nil {
		outerErr = errors.Maskf(optionalCause, format, args...)
	}

	innerErr, _ := outerErr.(*errors.Err) // cannot fail.
	return &vpcNotUsableError{*innerErr}
}
657111
func (s *AuthenticateOidcActionConfig) SetOnUnauthenticatedRequest(v string) *AuthenticateOidcActionConfig {
	s.OnUnauthenticatedRequest = &v
	return s
}
193247
func ForbiddenErrorf(format string, params ...interface{}) error {
	return forbidden(fmt.Sprintf(format, params...))
}
296511
func (c *Client) IsAuthenticated() bool {
	authHeader, ok := c.Headers["Authorization"]

	if !ok || (ok && authHeader == "token ") {
		return false
	}

	return true
}
1081196
func (s *AuthenticateCognitoActionConfig) SetOnUnauthenticatedRequest(v string) *AuthenticateCognitoActionConfig {
	s.OnUnauthenticatedRequest = &v
	return s
}
1035271
func BasicFunc(authfn func(string, string) bool) macaron.Handler {
	return func(res http.ResponseWriter, req *http.Request, c *macaron.Context) {
		auth := req.Header.Get("Authorization")
		n := len(basicPrefix)
		if len(auth) < n || auth[:n] != basicPrefix {
			basicUnauthorized(res)
			return
		}
		b, err := base64.StdEncoding.DecodeString(auth[n:])
		if err != nil {
			basicUnauthorized(res)
			return
		}
		tokens := strings.SplitN(string(b), ":", 2)
		if len(tokens) != 2 || !authfn(tokens[0], tokens[1]) {
			basicUnauthorized(res)
			return
		}
		c.Map(User(tokens[0]))
	}
}
1264448
func (provider *Provider) IsAuthorized(request *http.Request) (*string, error) {
	var err error
	var userParams map[string]string

	// start with the body/query params
	userParams, err = parseBody(request)
	if err != nil {
		return nil, err
	}

	// if the oauth params are in the Authorization header, grab them, and
	// let them override what's in userParams
	authHeader := request.Header.Get(HTTP_AUTH_HEADER)
	if len(authHeader) > 6 && strings.EqualFold(OAUTH_HEADER, authHeader[0:6]) {
		authHeader = authHeader[6:]
		params := strings.Split(authHeader, ",")
		for _, param := range params {
			vals := strings.SplitN(param, "=", 2)
			k := strings.Trim(vals[0], " ")
			v := strings.Trim(strings.Trim(vals[1], "\""), " ")
			if strings.HasPrefix(k, "oauth") {
				userParams[k], err = url.QueryUnescape(v)
				if err != nil {
					return nil, err
				}
			}
		}
	}

	// pop the request's signature, it's not included in our signature
	// calculation
	oauthSignature, ok := userParams[SIGNATURE_PARAM]
	if !ok {
		return nil, fmt.Errorf("no oauth signature")
	}
	delete(userParams, SIGNATURE_PARAM)

	// get the oauth consumer key
	consumerKey, ok := userParams[CONSUMER_KEY_PARAM]
	if !ok || consumerKey == "" {
		return nil, fmt.Errorf("no consumer key")
	}

	// use it to create a consumer object
	consumer, err := provider.ConsumerGetter(consumerKey, userParams)
	if err != nil {
		return nil, err
	}

	// Make sure timestamp is no more than 10 digits
	timestamp := userParams[TIMESTAMP_PARAM]
	if len(timestamp) > 10 {
		timestamp = timestamp[0:10]
	}

	// Check the timestamp
	if !consumer.serviceProvider.IgnoreTimestamp {
		oauthTimeNumber, err := strconv.Atoi(timestamp)
		if err != nil {
			return nil, err
		}

		if math.Abs(float64(int64(oauthTimeNumber)-provider.clock.Seconds())) > 5*60 {
			return nil, fmt.Errorf("too much clock skew")
		}
	}

	// Include the query string params in the base string
	if consumer.serviceProvider.SignQueryParams {
		for k, v := range request.URL.Query() {
			userParams[k] = strings.Join(v, "")
		}
	}

	// if our consumer supports bodyhash, check it
	if consumer.serviceProvider.BodyHash {
		bodyHash, err := calculateBodyHash(request, consumer.signer)
		if err != nil {
			return nil, err
		}

		sentHash, ok := userParams[BODY_HASH_PARAM]

		if bodyHash == "" && ok {
			return nil, fmt.Errorf("body_hash must not be set")
		} else if sentHash != bodyHash {
			return nil, fmt.Errorf("body_hash mismatch")
		}
	}

	allParams := NewOrderedParams()
	for key, value := range userParams {
		allParams.Add(key, value)
	}

	makeURLAbs(request.URL, request)
	baseString := consumer.requestString(request.Method, canonicalizeUrl(request.URL), allParams)
	err = consumer.signer.Verify(baseString, oauthSignature)
	if err != nil {
		return nil, err
	}

	return &consumerKey, nil
}
531855
func (s *AuthorizationService) FindAuthorizationByToken(ctx context.Context, t string) (a *platform.Authorization, err error) {
	defer func() {
		if err != nil {
			s.Logger.Info("error finding authorization by token", zap.Error(err))
		}
	}()

	return s.AuthorizationService.FindAuthorizationByToken(ctx, t)
}
697130
func Errorf(defaultValue string, args ...int) error {
	return errors.New(T(defaultValue, args...))
}
1230239
func Errorf(format string, args ...interface{}) {
	singltonLock.RLock()
	defer singltonLock.RUnlock()

	blog.Errorf(format, args...)
}
1092418
func IsAuthorizationValid(possibleScopes []string, authorizedScopes []string) bool {
	if len(possibleScopes) > len(authorizedScopes) {
		return false
	}
POSSIBLESCOPES:
	for _, possibleScope := range possibleScopes {
		for _, authorizedScope := range authorizedScopes {
			if possibleScope == authorizedScope {
				// Scope is already authorized, move on to the next one
				continue POSSIBLESCOPES
			}
		}
		// If we get here, it means the possibleScope is not in the authorizedScopes list
		// So the standing authorization is not valid
		return false
	}
	// Likewise, if we get here we did not yet return due to a missing scope authorization
	// and all possible scopes are exhausted. Therefore the standing authorization
	// is valid
	return true
}
1255020
func (c *UserConfig) ParseAuthorize(request *http.Request, service *Service) (string, string, error) {
	request.ParseForm()
	urlParts := request.URL.Query()
	token := urlParts.Get("oauth_token")
	verifier := urlParts.Get("oauth_verifier")
	if token == "" {
		token = request.Form.Get("oauth_token")
	}
	if verifier == "" {
		verifier = request.Form.Get("oauth_verifier")
	}
	if token == "" || verifier == "" {
		return "", "", fmt.Errorf("Token or verifier were missing from response")
	}
	return token, verifier, nil
}