// TokenAuthorizedWhere retrieves all documents that the authorization is allowed to access.
773326
func TokenAuthorizedWhere(a *Authorization) func(DocumentIndex, DocumentDecorator) ([]ID, error) {
	// TODO(desa): what to do about retrieving all documents using auth? (e.g. write/read:documents/*)
	var ids []ID
	return func(idx DocumentIndex, _ DocumentDecorator) ([]ID, error) {
		if !a.IsActive() {
			return nil, &Error{
				Code: EUnauthorized,
				Msg:  "authorizer cannot access documents",
			}
		}

		for _, p := range a.Permissions {
			if p.Resource.Type == DocumentsResourceType && p.Resource.OrgID != nil {
				oids, err := idx.GetAccessorsDocuments("org", *p.Resource.OrgID)
				if err != nil {
					return nil, err
				}
				ids = append(ids, oids...)
			}

			if p.Resource.Type == DocumentsResourceType && p.Resource.ID != nil {
				ids = append(ids, *p.Resource.ID)
			}
		}

		return ids, nil
	}
}
24357
func (t *Template) GetAllAWSApiGatewayAuthorizerResources() map[string]*resources.AWSApiGatewayAuthorizer {
	results := map[string]*resources.AWSApiGatewayAuthorizer{}
	for name, untyped := range t.Resources {
		switch resource := untyped.(type) {
		case *resources.AWSApiGatewayAuthorizer:
			results[name] = resource
		}
	}
	return results
}
970567
func GetAccount(host, token, id string) (*map[string]interface{}, error) {
	path := variables.APIPathAccount
	path = strings.Replace(path, ":id", id, 1)
	return GenericRequest(host, path, token, nil)
}
309862
func AuthenticatedServer(token string, handler http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Allow the POST method only.
		if r.Method != "POST" {
			http.Error(w, "POST Method Expected", http.StatusMethodNotAllowed)
			return
		}

		// Make sure that the token query parameter is set correctly.
		if r.FormValue("token") != token && r.FormValue("access_token") != token {
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
			return
		}

		// If everything is ok, serve the user-defined handler.
		handler.ServeHTTP(w, r)
	})
}
422833
func (m *Middleware) IsAuthorized(r *http.Request) bool {
	return m.GetAuthorizationToken(r) != nil
}
933717
func (api *AuthAPI) GetTokensFromWindowsLogInContext() (tokenOptions *TokenOptions, err error) {
	oidcClient, err := api.buildOIDCClient()
	if err != nil {
		return
	}

	tokenResponse, err := oidcClient.GetTokensFromWindowsLogInContext()
	if err != nil {
		return
	}

	return api.toTokenOptions(tokenResponse), nil
}
531246
func (csa *CognitiveServicesAuthorizer) WithAuthorization() PrepareDecorator {
	headers := make(map[string]interface{})
	headers[apiKeyAuthorizerHeader] = csa.subscriptionKey
	headers[bingAPISdkHeader] = golangBingAPISdkHeaderValue

	return NewAPIKeyAuthorizerWithHeaders(headers).WithAuthorization()
}
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)
}
1148887
func RoleEscalationAuthorized(ctx context.Context, a authorizer.Authorizer) bool {
	if a == nil {
		return false
	}

	user, ok := genericapirequest.UserFrom(ctx)
	if !ok {
		return false
	}

	requestInfo, ok := genericapirequest.RequestInfoFrom(ctx)
	if !ok {
		return false
	}

	if !requestInfo.IsResourceRequest {
		return false
	}

	requestResource := schema.GroupResource{Group: requestInfo.APIGroup, Resource: requestInfo.Resource}
	if !roleResources[requestResource] {
		return false
	}

	attrs := authorizer.AttributesRecord{
		User:            user,
		Verb:            "escalate",
		APIGroup:        requestInfo.APIGroup,
		Resource:        requestInfo.Resource,
		Name:            requestInfo.Name,
		Namespace:       requestInfo.Namespace,
		ResourceRequest: true,
	}

	decision, _, err := a.Authorize(attrs)
	if err != nil {
		utilruntime.HandleError(fmt.Errorf(
			"error authorizing user %#v to escalate %#v named %q in namespace %q: %v",
			user, requestResource, requestInfo.Name, requestInfo.Namespace, err,
		))
	}
	return decision == authorizer.DecisionAllow
}
540485
func (service *Service) FilterAuthorizedScopes(r *http.Request, username string, grantedTo string, requestedscopes []string) (authorizedScopes []string, err error) {
	authorization, err := userdb.NewManager(r).GetAuthorization(username, grantedTo)
	if authorization == nil || err != nil {
		return
	}

	authorizedScopes = authorization.FilterAuthorizedScopes(requestedscopes)

	return
}
486184
func (a *authorizer) authorizeLocalUser(u LocalUser) (*AuthContext, error) {
	return contextForLocalUser(u.Username, a.identity, a.access)
}
1208727
func (r *InspectOAuthTokenGrantRPC) InspectOAuthTokenGrant(c context.Context, req *admin.InspectOAuthTokenGrantRequest) (*admin.InspectOAuthTokenGrantResponse, error) {
	inspection, err := InspectGrant(c, r.Signer, req.Token)
	if err != nil {
		return nil, status.Errorf(codes.Internal, err.Error())
	}

	resp := &admin.InspectOAuthTokenGrantResponse{
		Valid:            inspection.Signed && inspection.NonExpired,
		Signed:           inspection.Signed,
		NonExpired:       inspection.NonExpired,
		InvalidityReason: inspection.InvalidityReason,
	}

	addInvalidityReason := func(msg string, args ...interface{}) {
		reason := fmt.Sprintf(msg, args...)
		resp.Valid = false
		if resp.InvalidityReason == "" {
			resp.InvalidityReason = reason
		} else {
			resp.InvalidityReason += "; " + reason
		}
	}

	if env, _ := inspection.Envelope.(*tokenserver.OAuthTokenGrantEnvelope); env != nil {
		resp.SigningKeyId = env.KeyId
	}

	// Examine the body, even if the token is expired or unsigned. This helps to
	// debug expired or unsigned tokens...
	resp.TokenBody, _ = inspection.Body.(*tokenserver.OAuthTokenGrantBody)
	if resp.TokenBody != nil {
		rules, err := r.Rules(c)
		if err != nil {
			return nil, status.Errorf(codes.Internal, "failed to load service accounts rules")
		}

		// Always return the rule that matches the service account, even if the
		// token itself is not allowed by it (we check it separately below).
		rule, err := rules.Rule(c, resp.TokenBody.ServiceAccount, "")
		switch {
		case status.Code(err) == codes.PermissionDenied:
			s, _ := status.FromError(err)
			addInvalidityReason("%s", s.Message())
			return resp, nil
		case err != nil: // usually codes.Internal
			return nil, err
		default:
			resp.MatchingRule = rule.Rule
		}

		q := &RulesQuery{
			ServiceAccount: resp.TokenBody.ServiceAccount,
			Rule:           rule,
			Proxy:          identity.Identity(resp.TokenBody.Proxy),
			EndUser:        identity.Identity(resp.TokenBody.EndUser),
		}
		switch _, err = rules.Check(c, q); {
		case err == nil:
			resp.AllowedByRules = true
		case status.Code(err) == codes.Internal:
			return nil, err // a transient error when checking rules
		default: // fatal gRPC error => the rules forbid the token
			addInvalidityReason("not allowed by the rules (rev %s)", rules.ConfigRevision())
		}
	}

	return resp, nil
}
1004693
func NewTokenGetAuthenticatedAdminResult(AdminProfile *TeamMemberProfile) *TokenGetAuthenticatedAdminResult {
	s := new(TokenGetAuthenticatedAdminResult)
	s.AdminProfile = AdminProfile
	return s
}
1161121
func (o *OIDCAuthenticator) AuthenticateToken(ctx context.Context, rawtoken string) (*Claims, error) {
	idToken, err := o.verifier.Verify(ctx, rawtoken)
	if err != nil {
		return nil, fmt.Errorf("Token failed validation: %v", err)
	}

	// Check for required claims
	var claims map[string]interface{}
	if err := idToken.Claims(&claims); err != nil {
		return nil, fmt.Errorf("Unable to get claim map from token: %v", err)
	}
	for _, requiredClaim := range requiredClaims {
		if _, ok := claims[requiredClaim]; !ok {
			// Claim missing
			return nil, fmt.Errorf("Required claim %v missing from token", requiredClaim)
		}
	}

	return o.parseClaims(claims)
}
460202
func (s *AuthorizationService) FindAuthorizationByToken(ctx context.Context, t string) (*influxdb.Authorization, error) {
	a, err := s.s.FindAuthorizationByToken(ctx, t)
	if err != nil {
		return nil, err
	}

	if err := authorizeReadAuthorization(ctx, a.UserID); err != nil {
		return nil, err
	}

	return a, nil
}
69353
func NewAuthorizedConfig(token string, secret string) *UserConfig {
	return &UserConfig{AccessTokenKey: token, AccessTokenSecret: secret}
}
54156
func (a *Authorization) GetHashedToken() string {
	if a == nil || a.HashedToken == nil {
		return ""
	}
	return *a.HashedToken
}