// DeactivateAuthorization2 deactivates a currently valid or pending authorization.
// This method is intended to deprecate DeactivateAuthorization.
166287
func (ssa *SQLStorageAuthority) DeactivateAuthorization2(ctx context.Context, req *sapb.AuthorizationID2) (*corepb.Empty, error) {
	_, err := ssa.dbMap.Exec(
		`UPDATE authz2 SET status = :deactivated WHERE id = :id and status IN (:valid,:pending)`,
		map[string]interface{}{
			"deactivated": statusUint(core.StatusDeactivated),
			"id":          *req.Id,
			"valid":       statusUint(core.StatusValid),
			"pending":     statusUint(core.StatusPending),
		},
	)
	if err != nil {
		return nil, err
	}
	return &corepb.Empty{}, nil
}
105841
func (c *Client) ReauthorizeAuthorization(authID string, a *Amount) (*Authorization, error) {
	buf := bytes.NewBuffer([]byte(`{"amount":{"currency":"` + a.Currency + `","total":"` + a.Total + `"}}`))
	req, err := http.NewRequest("POST", fmt.Sprintf("%s%s", c.APIBase, "/v2/payments/authorization/"+authID+"/reauthorize"), buf)
	if err != nil {
		return &Authorization{}, err
	}

	auth := &Authorization{}
	err = c.SendWithAuth(req, auth)
	return auth, err
}
802114
func (s *UpdateRouteInput) SetAuthorizerId(v string) *UpdateRouteInput {
	s.AuthorizerId = &v
	return s
}
498313
func (s *AuthorizationService) DeleteAuthorization(ctx context.Context, id platform.ID) (err error) {
	defer func() {
		if err != nil {
			s.Logger.Info("error deleting authorization", zap.Error(err))
		}
	}()

	return s.AuthorizationService.DeleteAuthorization(ctx, id)
}
1103115
func (ssa *SQLStorageAuthority) CountPendingAuthorizations2(ctx context.Context, req *sapb.RegistrationID) (*sapb.Count, error) {
	var count int64
	err := ssa.dbMap.WithContext(ctx).SelectOne(&count,
		`SELECT COUNT(1) FROM authz2 WHERE
		registrationID = :regID AND
		expires > :expires AND
		status = :status`,
		map[string]interface{}{
			"regID":   *req.Id,
			"expires": ssa.clk.Now(),
			"status":  statusUint(core.StatusPending),
		},
	)
	if err != nil {
		return nil, err
	}
	// also count old style authorizations and add those to the count of
	// new authorizations
	oldCount, err := ssa.CountPendingAuthorizations(ctx, *req.Id)
	if err != nil {
		return nil, err
	}
	count += int64(oldCount)
	return &sapb.Count{Count: &count}, nil
}
66187
func (s *AuthorizationService) DeleteAuthorization(ctx context.Context, id influxdb.ID) error {
	a, err := s.s.FindAuthorizationByID(ctx, id)
	if err != nil {
		return err
	}

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

	return s.s.DeleteAuthorization(ctx, id)
}
1265699
func (sa *StorageAuthority) NewAuthorizations2(ctx context.Context, req *sapb.AddPendingAuthorizationsRequest) (*sapb.Authorization2IDs, error) {
	return &sapb.Authorization2IDs{}, nil
}
1005109
func (ssa *SQLStorageAuthority) CountInvalidAuthorizations2(ctx context.Context, req *sapb.CountInvalidAuthorizationsRequest) (*sapb.Count, error) {
	var count int64
	err := ssa.dbMap.WithContext(ctx).SelectOne(
		&count,
		`SELECT COUNT(1) FROM authz2 WHERE
		registrationID = :regID AND
		identifierValue = :ident AND
		expires > :expiresEarliest AND
		expires <= :expiresLatest AND
		status = :status`,
		map[string]interface{}{
			"regID":           *req.RegistrationID,
			"ident":           *req.Hostname,
			"expiresEarliest": time.Unix(0, *req.Range.Earliest),
			"expiresLatest":   time.Unix(0, *req.Range.Latest),
			"status":          statusUint(core.StatusInvalid),
		},
	)
	if err != nil {
		return nil, err
	}
	// Also count old authorizations and add those to the new style
	// count
	oldCount, err := ssa.CountInvalidAuthorizations(ctx, req)
	if err != nil {
		return nil, err
	}
	count += *oldCount.Count
	return &sapb.Count{Count: &count}, nil
}
403709
func Authorized() runtime.Authorizer {
	return runtime.AuthorizerFunc(func(_ *http.Request, _ interface{}) error { return nil })
}
770592
func WithAuthorization(handler http.Handler, a authorizer.Authorizer, s runtime.NegotiatedSerializer) http.Handler {
	if a == nil {
		klog.Warningf("Authorization is disabled")
		return handler
	}
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		ctx := req.Context()
		ae := request.AuditEventFrom(ctx)

		attributes, err := GetAuthorizerAttributes(ctx)
		if err != nil {
			responsewriters.InternalError(w, req, err)
			return
		}
		authorized, reason, err := a.Authorize(attributes)
		// an authorizer like RBAC could encounter evaluation errors and still allow the request, so authorizer decision is checked before error here.
		if authorized == authorizer.DecisionAllow {
			audit.LogAnnotation(ae, decisionAnnotationKey, decisionAllow)
			audit.LogAnnotation(ae, reasonAnnotationKey, reason)
			handler.ServeHTTP(w, req)
			return
		}
		if err != nil {
			audit.LogAnnotation(ae, reasonAnnotationKey, reasonError)
			responsewriters.InternalError(w, req, err)
			return
		}

		klog.V(4).Infof("Forbidden: %#v, Reason: %q", req.RequestURI, reason)
		audit.LogAnnotation(ae, decisionAnnotationKey, decisionForbid)
		audit.LogAnnotation(ae, reasonAnnotationKey, reason)
		responsewriters.Forbidden(ctx, attributes, w, req, reason, s)
	})
}
759161
func (a *Authenticator) ValidAuthorization(ctx context.Context, serializedAuthorization string) (oauth2.Principal, error) {
	return oauth2.Principal{}, nil
}
1181940
func (c *NamedusersController) Deactivate(ctx *app.DeactivateNamedusersContext) error {
	isSvcAccount := token.IsSpecificServiceAccount(ctx, token.OnlineRegistration)
	if !isSvcAccount {
		log.Error(ctx, nil, "the account is not an authorized service account allowed to deprovision users")
		return jsonapi.JSONErrorResponse(ctx, errors.NewForbiddenError("account not authorized to deprovision users"))
	}

	identity, err := c.app.UserService().DeactivateUser(ctx, ctx.Username)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"err":      err,
			"username": ctx.Username,
		}, "error occurred while deactivating user")
		if notFound, _ := errors.IsNotFoundError(err); !notFound {
			return jsonapi.JSONErrorResponse(ctx, err)
		}
		// Ignore notFound error. If user has not found then we don't want the reg-app keep trying to deactivate it in auth.
		// We can add some dummy Identity in response here
		identity = &repository.Identity{}
	} else {
		log.Info(ctx, map[string]interface{}{
			"username": ctx.Username,
		}, "user deactivated")
	}

	return ctx.OK(ConvertToAppUser(ctx.RequestData, &identity.User, identity, true))
}
331985
func (s *CreateRouteInput) SetAuthorizationType(v string) *CreateRouteInput {
	s.AuthorizationType = &v
	return s
}
756309
func (s *PutMethodInput) SetAuthorizationType(v string) *PutMethodInput {
	s.AuthorizationType = &v
	return s
}
612319
func (s *CA) ActivateCertAuthority(id services.CertAuthID) error {
	item, err := s.Get(context.TODO(), backend.Key(authoritiesPrefix, deactivatedPrefix, string(id.Type), id.DomainName))
	if err != nil {
		if trace.IsNotFound(err) {
			return trace.BadParameter("can not activate cert authority %q which has not been deactivated", id.DomainName)
		}
		return trace.Wrap(err)
	}

	certAuthority, err := services.GetCertAuthorityMarshaler().UnmarshalCertAuthority(
		item.Value, services.WithResourceID(item.ID), services.WithExpires(item.Expires))
	if err != nil {
		return trace.Wrap(err)
	}

	err = s.UpsertCertAuthority(certAuthority)
	if err != nil {
		return trace.Wrap(err)
	}

	err = s.Delete(context.TODO(), backend.Key(authoritiesPrefix, deactivatedPrefix, string(id.Type), id.DomainName))
	if err != nil {
		return trace.Wrap(err)
	}

	return nil
}
717706
func (ssa *SQLStorageAuthority) RevokeAuthorizationsByDomain(ctx context.Context, ident core.AcmeIdentifier) (int64, int64, error) {
	identifierJSON, err := json.Marshal(ident)
	if err != nil {
		return 0, 0, err
	}
	identifier := string(identifierJSON)
	results := []int64{0, 0}

	now := ssa.clk.Now()
	for i, table := range authorizationTables {
		for {
			authz, err := getAuthorizationIDsByDomain(ssa.dbMap.WithContext(ctx), table, identifier, now)
			if err != nil {
				return results[0], results[1], err
			}
			numAuthz := len(authz)
			if numAuthz == 0 {
				break
			}

			numRevoked, err := revokeAuthorizations(ssa.dbMap.WithContext(ctx), table, authz)
			if err != nil {
				return results[0], results[1], err
			}
			results[i] += numRevoked
			if numRevoked < int64(numAuthz) {
				return results[0], results[1], fmt.Errorf("Didn't revoke all found authorizations")
			}
		}
	}

	return results[0], results[1], nil
}
134291
func (ssa *SQLStorageAuthority) RevokeAuthorizationsByDomain2(ctx context.Context, req *sapb.RevokeAuthorizationsByDomainRequest) (*corepb.Empty, error) {
	finalRevoked, pendingRevoked, err := ssa.RevokeAuthorizationsByDomain(
		ctx,
		core.AcmeIdentifier{
			Type:  core.IdentifierDNS,
			Value: *req.Domain,
		})
	if err != nil {
		return nil, err
	}

	var revokedTotal int64 = finalRevoked + pendingRevoked
	for {
		var ids []int64
		ids, err := ssa.getAuthorizationIDsByDomain2(ctx, *req.Domain)
		if err != nil {
			if err == sql.ErrNoRows {
				break
			}
			return nil, err
		}
		if len(ids) == 0 {
			break
		}
		if err = ssa.revokeAuthorizations2(ctx, ids); err != nil {
			return nil, err
		}
		revokedTotal += int64(len(ids))
	}
	// If no authorizations were revoked return a NotFoundError so that the caller
	// can decide whether that was an expected result or not. Some callers (e.g.
	// the admin-revoker tool) may wish to handle this case specifically.
	if revokedTotal == 0 {
		return nil, berrors.NotFoundError(
			"no authorizations to revoke for %q", *req.Domain)
	}
	return &corepb.Empty{}, nil
}