// NoAuthorization sets "team" and "uid" in the context without
// checking if the user/team is authorized.
184756
func NoAuthorization() func(tc *ginoauth2.TokenContainer, ctx *gin.Context) bool {
	return func(tc *ginoauth2.TokenContainer, ctx *gin.Context) bool {
		blob, err := RequestTeamInfo(tc, TeamAPI)
		var data []TeamInfo
		err = json.Unmarshal(blob, &data)
		if err != nil {
			glog.Errorf("[Gin-OAuth] JSON.Unmarshal failed, caused by: %s", err)
		}
		for _, teamInfo := range data {
			if teamInfo.Type == "official" {
				ctx.Set("uid", tc.Scopes["uid"].(string))
				ctx.Set("team", teamInfo.Id)
				return true
			}
		}
		return true
	}
}
1305845
func NewAuthorizationService() *AuthorizationService {
	return &AuthorizationService{
		FindAuthorizationByIDFn:    func(context.Context, platform.ID) (*platform.Authorization, error) { return nil, nil },
		FindAuthorizationByTokenFn: func(context.Context, string) (*platform.Authorization, error) { return nil, nil },
		FindAuthorizationsFn: func(context.Context, platform.AuthorizationFilter, ...platform.FindOptions) ([]*platform.Authorization, int, error) {
			return nil, 0, nil
		},
		CreateAuthorizationFn:    func(context.Context, *platform.Authorization) error { return nil },
		DeleteAuthorizationFn:    func(context.Context, platform.ID) error { return nil },
		SetAuthorizationStatusFn: func(context.Context, platform.ID, platform.Status) error { return nil },
	}
}
419703
func (ra *RegistrationAuthorityImpl) NewAuthorization(ctx context.Context, request core.Authorization, regID int64) (core.Authorization, error) {
	identifier := request.Identifier
	identifier.Value = strings.ToLower(identifier.Value)

	// Check that the identifier is present and appropriate
	if err := ra.PA.WillingToIssue(identifier); err != nil {
		return core.Authorization{}, err
	}

	if err := ra.checkPendingAuthorizationLimit(ctx, regID); err != nil {
		return core.Authorization{}, err
	}

	if err := ra.checkInvalidAuthorizationLimit(ctx, regID, identifier.Value); err != nil {
		return core.Authorization{}, err
	}

	if ra.reuseValidAuthz {
		auths, err := ra.SA.GetValidAuthorizations(ctx, regID, []string{identifier.Value}, ra.clk.Now())
		if err != nil {
			outErr := berrors.InternalServerError(
				"unable to get existing validations for regID: %d, identifier: %s, %s",
				regID,
				identifier.Value,
				err,
			)
			ra.log.Warning(outErr.Error())
			return core.Authorization{}, outErr
		}

		if existingAuthz, ok := auths[identifier.Value]; ok {
			// Use the valid existing authorization's ID to find a fully populated version
			// The results from `GetValidAuthorizations` are most notably missing
			// `Challenge` values that the client expects in the result.
			populatedAuthz, err := ra.SA.GetAuthorization(ctx, existingAuthz.ID)
			if err != nil {
				outErr := berrors.InternalServerError(
					"unable to get existing authorization for auth ID: %s",
					existingAuthz.ID,
				)
				ra.log.Warningf("%s: %s", outErr.Error(), existingAuthz.ID)
				return core.Authorization{}, outErr
			}
			if ra.authzValidChallengeEnabled(&populatedAuthz) {
				// The existing authorization must not expire within the next 24 hours for
				// it to be OK for reuse
				reuseCutOff := ra.clk.Now().Add(time.Hour * 24)
				if populatedAuthz.Expires.After(reuseCutOff) {
					ra.stats.Inc("ReusedValidAuthz", 1)
					return populatedAuthz, nil
				}
			}
		}
	}

	nowishNano := ra.clk.Now().Add(time.Hour).UnixNano()
	identifierTypeString := string(identifier.Type)
	pendingAuth, err := ra.SA.GetPendingAuthorization(ctx, &sapb.GetPendingAuthorizationRequest{
		RegistrationID:  &regID,
		IdentifierType:  &identifierTypeString,
		IdentifierValue: &identifier.Value,
		ValidUntil:      &nowishNano,
	})
	if err != nil && !berrors.Is(err, berrors.NotFound) {
		return core.Authorization{}, berrors.InternalServerError(
			"unable to get pending authorization for regID: %d, identifier: %s: %s",
			regID,
			identifier.Value,
			err)
	} else if err == nil {
		return *pendingAuth, nil
	}

	v2 := features.Enabled(features.NewAuthorizationSchema)
	authzPB, err := ra.createPendingAuthz(ctx, regID, identifier, v2)
	if err != nil {
		return core.Authorization{}, err
	}

	if v2 {
		authzIDs, err := ra.SA.NewAuthorizations2(ctx, &sapb.AddPendingAuthorizationsRequest{
			Authz: []*corepb.Authorization{authzPB},
		})
		if err != nil {
			return core.Authorization{}, err
		}
		if len(authzIDs.Ids) != 1 {
			return core.Authorization{}, berrors.InternalServerError("unexpected number of authorization IDs returned from NewAuthorizations2: expected 1, got %d", len(authzIDs.Ids))
		}
		// The current internal authorization objects use a string for the ID, the new
		// storage format uses a integer ID. In order to maintain compatibility we
		// convert the integer ID to a string.
		id := fmt.Sprintf("%d", authzIDs.Ids[0])
		authzPB.Id = &id
		return bgrpc.PBToAuthz(authzPB)
	}

	authz, err := bgrpc.PBToAuthz(authzPB)
	if err != nil {
		return core.Authorization{}, err
	}
	result, err := ra.SA.NewPendingAuthorization(ctx, authz)
	if err != nil {
		// berrors.InternalServerError since the user-data was validated before being
		// passed to the SA.
		err = berrors.InternalServerError("failed to store new pending authorization: %s", err)
		return core.Authorization{}, err
	}
	return result, nil
}
292306
func (s *Service) UpdateAuthorization(ctx context.Context, id influxdb.ID, upd *influxdb.AuthorizationUpdate) (*influxdb.Authorization, error) {
	var a *influxdb.Authorization
	var err error
	err = s.kv.Update(ctx, func(tx Tx) error {
		a, err = s.updateAuthorization(ctx, tx, id, upd)
		return err
	})
	return a, err
}
711267
func (s *CreateRouteOutput) SetAuthorizationType(v string) *CreateRouteOutput {
	s.AuthorizationType = &v
	return s
}
1187512
func (o *BuiltInAuthenticationOptions) ApplyAuthorization(authorization *BuiltInAuthorizationOptions) {
	if o == nil || authorization == nil || o.Anonymous == nil {
		return
	}

	// authorization ModeAlwaysAllow cannot be combined with AnonymousAuth.
	// in such a case the AnonymousAuth is stomped to false and you get a message
	if o.Anonymous.Allow && sets.NewString(authorization.Modes...).Has(authzmodes.ModeAlwaysAllow) {
		klog.Warningf("AnonymousAuth is not allowed with the AlwaysAllow authorizer. Resetting AnonymousAuth to false. You should use a different authorizer")
		o.Anonymous.Allow = false
	}
}
1233638
func TokenAuthorizedWithOrg(a *Authorization, org string) func(ID, DocumentIndex) error {
	return func(id ID, idx DocumentIndex) error {
		if !a.IsActive() {
			return &Error{
				Code: EUnauthorized,
				Msg:  "authorization cannot add org as document owner",
			}
		}

		oid, err := idx.FindOrganizationByName(org)
		if err != nil {
			return err
		}

		p := Permission{
			Action: WriteAction,
			Resource: Resource{
				Type:  DocumentsResourceType,
				OrgID: &oid,
			},
		}

		if !a.Allowed(p) {
			return &Error{
				Code: EUnauthorized,
				Msg:  "authorization cannot add org as document owner",
			}
		}

		return idx.AddDocumentOwner(id, "org", oid)
	}
}
438758
func (s *Service) UpdateAuthorization(ctx context.Context, id platform.ID, upd *platform.AuthorizationUpdate) (*platform.Authorization, error) {
	op := OpPrefix + platform.OpUpdateAuthorization
	a, err := s.FindAuthorizationByID(ctx, id)
	if err != nil {
		return nil, &platform.Error{
			Err: err,
			Op:  op,
		}
	}

	if upd.Status != nil {
		status := *upd.Status
		switch status {
		case platform.Active, platform.Inactive:
		default:
			return nil, &platform.Error{
				Code: platform.EInvalid,
				Msg:  "unknown authorization status",
				Op:   op,
			}
		}
		a.Status = status
	}

	if upd.Description != nil {
		a.Description = *upd.Description
	}

	return a, s.PutAuthorization(ctx, a)
}
655446
func (s *Server) WithAuthorization(scheme AuthorizationScheme) *Server {
	s.authorization = scheme
	return s
}
331985
func (s *CreateRouteInput) SetAuthorizationType(v string) *CreateRouteInput {
	s.AuthorizationType = &v
	return s
}
1177956
func ToDefaultAuthorizationAttributes(user user.Info, namespace string, in authorizationapi.Action) authorizer.Attributes {
	tokens := strings.SplitN(in.Resource, "/", 2)
	resource := ""
	subresource := ""
	switch {
	case len(tokens) == 2:
		subresource = tokens[1]
		fallthrough
	case len(tokens) == 1:
		resource = tokens[0]
	}

	return &authorizer.AttributesRecord{
		User:            user,
		Verb:            in.Verb,
		Namespace:       namespace,
		APIGroup:        in.Group,
		APIVersion:      in.Version,
		Resource:        resource,
		Subresource:     subresource,
		Name:            in.ResourceName,
		ResourceRequest: !in.IsNonResourceURL,
		Path:            in.Path,
	}
}
1369551
func (c *Client) PutAuthorization(ctx context.Context, a *platform.Authorization) (err error) {
	return c.db.Update(func(tx *bolt.Tx) error {
		pe := c.putAuthorization(ctx, tx, a)
		if pe != nil {
			err = pe
		}
		return err
	})
}
714547
func (s *CreateRouteOutput) SetAuthorizerId(v string) *CreateRouteOutput {
	s.AuthorizerId = &v
	return s
}
734902
func (s *Service) FindAuthorizationByID(ctx context.Context, id platform.ID) (*platform.Authorization, error) {
	var err error
	a, pe := s.loadAuthorization(ctx, id)
	if pe != nil {
		pe.Op = OpPrefix + platform.OpFindAuthorizationByID
		err = pe
	}
	return a, err
}
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
}
283152
func (c *ACLCaches) GetAuthorizer(id string) *AuthorizerCacheEntry {
	if c == nil || c.authorizers == nil {
		return nil
	}

	if raw, ok := c.authorizers.Get(id); ok {
		return raw.(*AuthorizerCacheEntry)
	}

	return nil
}
77493
func AuthorizedWithOrg(a Authorizer, org string) func(ID, DocumentIndex) error {
	switch t := a.(type) {
	case *Authorization:
		return TokenAuthorizedWithOrg(t, org)
	}

	return func(id ID, idx DocumentIndex) error {
		oid, err := idx.FindOrganizationByName(org)
		if err != nil {
			return err
		}

		if err := idx.IsOrgAccessor(a.GetUserID(), oid); err != nil {
			return err
		}

		return idx.AddDocumentOwner(id, "org", oid)
	}
}