admin/applyLimitClasses (#1210)

This commit is contained in:
Michael Quigley
2026-03-24 16:20:53 -04:00
parent b73aa57572
commit d2ecdc3b05
32 changed files with 1945 additions and 0 deletions
@@ -0,0 +1,62 @@
package main
import (
"strconv"
"github.com/michaelquigley/df/dl"
"github.com/openziti/zrok/v2/environment"
"github.com/openziti/zrok/v2/rest_client_zrok/admin"
"github.com/spf13/cobra"
)
func init() {
adminCreateCmd.AddCommand(newAdminCreateAppliedLimitClassesCommand().cmd)
}
type adminCreateAppliedLimitClassesCommand struct {
cmd *cobra.Command
}
func newAdminCreateAppliedLimitClassesCommand() *adminCreateAppliedLimitClassesCommand {
cmd := &cobra.Command{
Use: "applied-limit-classes <email> <limitClassId> [<limitClassId>...]",
Aliases: []string{"alcs"},
Short: "Apply one or more limit classes to the specified account",
Args: cobra.MinimumNArgs(2),
}
command := &adminCreateAppliedLimitClassesCommand{cmd: cmd}
cmd.Run = command.run
return command
}
func (cmd *adminCreateAppliedLimitClassesCommand) run(_ *cobra.Command, args []string) {
env, err := environment.LoadRoot()
if err != nil {
panic(err)
}
zrok, err := env.Client()
if err != nil {
panic(err)
}
var limitClassIds []int64
for _, arg := range args[1:] {
lcId, err := strconv.ParseInt(arg, 10, 64)
if err != nil {
panic(err)
}
limitClassIds = append(limitClassIds, lcId)
}
req := admin.NewApplyLimitClassesParams()
req.Body.Email = args[0]
req.Body.LimitClassIds = limitClassIds
_, err = zrok.Admin.ApplyLimitClasses(req, mustGetAdminAuth())
if err != nil {
panic(err)
}
dl.Infof("applied %d limit class(es) to '%v'", len(limitClassIds), args[0])
}
+53
View File
@@ -0,0 +1,53 @@
package controller
import (
"github.com/go-openapi/runtime/middleware"
"github.com/michaelquigley/df/dl"
"github.com/openziti/zrok/v2/controller/store"
"github.com/openziti/zrok/v2/rest_model_zrok"
"github.com/openziti/zrok/v2/rest_server_zrok/operations/admin"
)
type applyLimitClassesHandler struct{}
func newApplyLimitClassesHandler() *applyLimitClassesHandler {
return &applyLimitClassesHandler{}
}
func (h *applyLimitClassesHandler) Handle(params admin.ApplyLimitClassesParams, principal *rest_model_zrok.Principal) middleware.Responder {
if !principal.Admin {
dl.Error("invalid admin principal")
return admin.NewApplyLimitClassesUnauthorized()
}
trx, err := str.Begin()
if err != nil {
dl.Errorf("error starting transaction: %v", err)
return admin.NewApplyLimitClassesInternalServerError()
}
defer func() { _ = trx.Rollback() }()
acct, err := str.FindAccountWithEmail(params.Body.Email, trx)
if err != nil {
dl.Errorf("error finding account with email '%v': %v", params.Body.Email, err)
return admin.NewApplyLimitClassesNotFound()
}
for _, lcId := range params.Body.LimitClassIds {
if _, err := str.GetLimitClass(int(lcId), trx); err != nil {
dl.Errorf("error finding limit class '%v': %v", lcId, err)
return admin.NewApplyLimitClassesNotFound()
}
if _, err := str.ApplyLimitClass(&store.AppliedLimitClass{AccountId: acct.Id, LimitClassId: int(lcId)}, trx); err != nil {
dl.Errorf("error applying limit class '%v' to '%v': %v", lcId, params.Body.Email, err)
return admin.NewApplyLimitClassesInternalServerError()
}
}
if err := trx.Commit(); err != nil {
dl.Errorf("error committing transaction: %v", err)
return admin.NewApplyLimitClassesInternalServerError()
}
return admin.NewApplyLimitClassesOK()
}
+1
View File
@@ -60,6 +60,7 @@ func Run(inCfg *config.Config) error {
api.AdminAddNamespaceFrontendMappingHandler = newAddNamespaceFrontendMappingHandler()
api.AdminAddNamespaceGrantHandler = newAddNamespaceGrantHandler()
api.AdminAddOrganizationMemberHandler = newAddOrganizationMemberHandler()
api.AdminApplyLimitClassesHandler = newApplyLimitClassesHandler()
api.AdminCreateAccountHandler = newCreateAccountHandler()
api.AdminCreateFrontendHandler = newCreateFrontendHandler()
api.AdminCreateIdentityHandler = newCreateIdentityHandler()
+46
View File
@@ -108,6 +108,8 @@ type ClientService interface {
AddOrganizationMember(params *AddOrganizationMemberParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*AddOrganizationMemberCreated, error)
ApplyLimitClasses(params *ApplyLimitClassesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ApplyLimitClassesOK, error)
CreateAccount(params *CreateAccountParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateAccountCreated, error)
CreateFrontend(params *CreateFrontendParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*CreateFrontendCreated, error)
@@ -341,6 +343,50 @@ func (a *Client) AddOrganizationMember(params *AddOrganizationMemberParams, auth
panic(msg)
}
/*
ApplyLimitClasses apply limit classes API
*/
func (a *Client) ApplyLimitClasses(params *ApplyLimitClassesParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ApplyLimitClassesOK, error) {
// NOTE: parameters are not validated before sending
if params == nil {
params = NewApplyLimitClassesParams()
}
op := &runtime.ClientOperation{
ID: "applyLimitClasses",
Method: "POST",
PathPattern: "/applied-limit-class",
ProducesMediaTypes: []string{"application/zrok.v1+json"},
ConsumesMediaTypes: []string{"application/zrok.v1+json"},
Schemes: []string{"http"},
Params: params,
Reader: &ApplyLimitClassesReader{formats: a.formats},
AuthInfo: authInfo,
Context: params.Context,
Client: params.HTTPClient,
}
for _, opt := range opts {
opt(op)
}
result, err := a.transport.Submit(op)
if err != nil {
return nil, err
}
// only one success response has to be checked
success, ok := result.(*ApplyLimitClassesOK)
if ok {
return success, nil
}
// unexpected success response.
// no default response is defined.
//
// safeguard: normally, in the absence of a default response, unknown success responses return an error above: so this is a codegen issue
msg := fmt.Sprintf("unexpected success response for applyLimitClasses: API contract not enforced by server. Client expected to get an error, but got: %T", result)
panic(msg)
}
/*
CreateAccount create account API
*/
@@ -0,0 +1,146 @@
// Code generated by go-swagger; DO NOT EDIT.
package admin
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"net/http"
"time"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
cr "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
)
// NewApplyLimitClassesParams creates a new ApplyLimitClassesParams object,
// with the default timeout for this client.
//
// Default values are not hydrated, since defaults are normally applied by the API server side.
//
// To enforce default values in parameter, use SetDefaults or WithDefaults.
func NewApplyLimitClassesParams() *ApplyLimitClassesParams {
return &ApplyLimitClassesParams{
timeout: cr.DefaultTimeout,
}
}
// NewApplyLimitClassesParamsWithTimeout creates a new ApplyLimitClassesParams object
// with the ability to set a timeout on a request.
func NewApplyLimitClassesParamsWithTimeout(timeout time.Duration) *ApplyLimitClassesParams {
return &ApplyLimitClassesParams{
timeout: timeout,
}
}
// NewApplyLimitClassesParamsWithContext creates a new ApplyLimitClassesParams object
// with the ability to set a context for a request.
func NewApplyLimitClassesParamsWithContext(ctx context.Context) *ApplyLimitClassesParams {
return &ApplyLimitClassesParams{
Context: ctx,
}
}
// NewApplyLimitClassesParamsWithHTTPClient creates a new ApplyLimitClassesParams object
// with the ability to set a custom HTTPClient for a request.
func NewApplyLimitClassesParamsWithHTTPClient(client *http.Client) *ApplyLimitClassesParams {
return &ApplyLimitClassesParams{
HTTPClient: client,
}
}
/*
ApplyLimitClassesParams contains all the parameters to send to the API endpoint
for the apply limit classes operation.
Typically these are written to a http.Request.
*/
type ApplyLimitClassesParams struct {
// Body.
Body ApplyLimitClassesBody
timeout time.Duration
Context context.Context
HTTPClient *http.Client
}
// WithDefaults hydrates default values in the apply limit classes params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *ApplyLimitClassesParams) WithDefaults() *ApplyLimitClassesParams {
o.SetDefaults()
return o
}
// SetDefaults hydrates default values in the apply limit classes params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *ApplyLimitClassesParams) SetDefaults() {
// no default values defined for this parameter
}
// WithTimeout adds the timeout to the apply limit classes params
func (o *ApplyLimitClassesParams) WithTimeout(timeout time.Duration) *ApplyLimitClassesParams {
o.SetTimeout(timeout)
return o
}
// SetTimeout adds the timeout to the apply limit classes params
func (o *ApplyLimitClassesParams) SetTimeout(timeout time.Duration) {
o.timeout = timeout
}
// WithContext adds the context to the apply limit classes params
func (o *ApplyLimitClassesParams) WithContext(ctx context.Context) *ApplyLimitClassesParams {
o.SetContext(ctx)
return o
}
// SetContext adds the context to the apply limit classes params
func (o *ApplyLimitClassesParams) SetContext(ctx context.Context) {
o.Context = ctx
}
// WithHTTPClient adds the HTTPClient to the apply limit classes params
func (o *ApplyLimitClassesParams) WithHTTPClient(client *http.Client) *ApplyLimitClassesParams {
o.SetHTTPClient(client)
return o
}
// SetHTTPClient adds the HTTPClient to the apply limit classes params
func (o *ApplyLimitClassesParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithBody adds the body to the apply limit classes params
func (o *ApplyLimitClassesParams) WithBody(body ApplyLimitClassesBody) *ApplyLimitClassesParams {
o.SetBody(body)
return o
}
// SetBody adds the body to the apply limit classes params
func (o *ApplyLimitClassesParams) SetBody(body ApplyLimitClassesBody) {
o.Body = body
}
// WriteToRequest writes these params to a swagger request
func (o *ApplyLimitClassesParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
if err := r.SetTimeout(o.timeout); err != nil {
return err
}
var res []error
if err := r.SetBodyParam(o.Body); err != nil {
return err
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
@@ -0,0 +1,317 @@
// Code generated by go-swagger; DO NOT EDIT.
package admin
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"fmt"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// ApplyLimitClassesReader is a Reader for the ApplyLimitClasses structure.
type ApplyLimitClassesReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *ApplyLimitClassesReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (any, error) {
switch response.Code() {
case 200:
result := NewApplyLimitClassesOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
case 401:
result := NewApplyLimitClassesUnauthorized()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
case 404:
result := NewApplyLimitClassesNotFound()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
case 500:
result := NewApplyLimitClassesInternalServerError()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
default:
return nil, runtime.NewAPIError("[POST /applied-limit-class] applyLimitClasses", response, response.Code())
}
}
// NewApplyLimitClassesOK creates a ApplyLimitClassesOK with default headers values
func NewApplyLimitClassesOK() *ApplyLimitClassesOK {
return &ApplyLimitClassesOK{}
}
/*
ApplyLimitClassesOK describes a response with status code 200, with default header values.
applied
*/
type ApplyLimitClassesOK struct {
}
// IsSuccess returns true when this apply limit classes o k response has a 2xx status code
func (o *ApplyLimitClassesOK) IsSuccess() bool {
return true
}
// IsRedirect returns true when this apply limit classes o k response has a 3xx status code
func (o *ApplyLimitClassesOK) IsRedirect() bool {
return false
}
// IsClientError returns true when this apply limit classes o k response has a 4xx status code
func (o *ApplyLimitClassesOK) IsClientError() bool {
return false
}
// IsServerError returns true when this apply limit classes o k response has a 5xx status code
func (o *ApplyLimitClassesOK) IsServerError() bool {
return false
}
// IsCode returns true when this apply limit classes o k response a status code equal to that given
func (o *ApplyLimitClassesOK) IsCode(code int) bool {
return code == 200
}
// Code gets the status code for the apply limit classes o k response
func (o *ApplyLimitClassesOK) Code() int {
return 200
}
func (o *ApplyLimitClassesOK) Error() string {
return fmt.Sprintf("[POST /applied-limit-class][%d] applyLimitClassesOK", 200)
}
func (o *ApplyLimitClassesOK) String() string {
return fmt.Sprintf("[POST /applied-limit-class][%d] applyLimitClassesOK", 200)
}
func (o *ApplyLimitClassesOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
return nil
}
// NewApplyLimitClassesUnauthorized creates a ApplyLimitClassesUnauthorized with default headers values
func NewApplyLimitClassesUnauthorized() *ApplyLimitClassesUnauthorized {
return &ApplyLimitClassesUnauthorized{}
}
/*
ApplyLimitClassesUnauthorized describes a response with status code 401, with default header values.
unauthorized
*/
type ApplyLimitClassesUnauthorized struct {
}
// IsSuccess returns true when this apply limit classes unauthorized response has a 2xx status code
func (o *ApplyLimitClassesUnauthorized) IsSuccess() bool {
return false
}
// IsRedirect returns true when this apply limit classes unauthorized response has a 3xx status code
func (o *ApplyLimitClassesUnauthorized) IsRedirect() bool {
return false
}
// IsClientError returns true when this apply limit classes unauthorized response has a 4xx status code
func (o *ApplyLimitClassesUnauthorized) IsClientError() bool {
return true
}
// IsServerError returns true when this apply limit classes unauthorized response has a 5xx status code
func (o *ApplyLimitClassesUnauthorized) IsServerError() bool {
return false
}
// IsCode returns true when this apply limit classes unauthorized response a status code equal to that given
func (o *ApplyLimitClassesUnauthorized) IsCode(code int) bool {
return code == 401
}
// Code gets the status code for the apply limit classes unauthorized response
func (o *ApplyLimitClassesUnauthorized) Code() int {
return 401
}
func (o *ApplyLimitClassesUnauthorized) Error() string {
return fmt.Sprintf("[POST /applied-limit-class][%d] applyLimitClassesUnauthorized", 401)
}
func (o *ApplyLimitClassesUnauthorized) String() string {
return fmt.Sprintf("[POST /applied-limit-class][%d] applyLimitClassesUnauthorized", 401)
}
func (o *ApplyLimitClassesUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
return nil
}
// NewApplyLimitClassesNotFound creates a ApplyLimitClassesNotFound with default headers values
func NewApplyLimitClassesNotFound() *ApplyLimitClassesNotFound {
return &ApplyLimitClassesNotFound{}
}
/*
ApplyLimitClassesNotFound describes a response with status code 404, with default header values.
account or limit class not found
*/
type ApplyLimitClassesNotFound struct {
}
// IsSuccess returns true when this apply limit classes not found response has a 2xx status code
func (o *ApplyLimitClassesNotFound) IsSuccess() bool {
return false
}
// IsRedirect returns true when this apply limit classes not found response has a 3xx status code
func (o *ApplyLimitClassesNotFound) IsRedirect() bool {
return false
}
// IsClientError returns true when this apply limit classes not found response has a 4xx status code
func (o *ApplyLimitClassesNotFound) IsClientError() bool {
return true
}
// IsServerError returns true when this apply limit classes not found response has a 5xx status code
func (o *ApplyLimitClassesNotFound) IsServerError() bool {
return false
}
// IsCode returns true when this apply limit classes not found response a status code equal to that given
func (o *ApplyLimitClassesNotFound) IsCode(code int) bool {
return code == 404
}
// Code gets the status code for the apply limit classes not found response
func (o *ApplyLimitClassesNotFound) Code() int {
return 404
}
func (o *ApplyLimitClassesNotFound) Error() string {
return fmt.Sprintf("[POST /applied-limit-class][%d] applyLimitClassesNotFound", 404)
}
func (o *ApplyLimitClassesNotFound) String() string {
return fmt.Sprintf("[POST /applied-limit-class][%d] applyLimitClassesNotFound", 404)
}
func (o *ApplyLimitClassesNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
return nil
}
// NewApplyLimitClassesInternalServerError creates a ApplyLimitClassesInternalServerError with default headers values
func NewApplyLimitClassesInternalServerError() *ApplyLimitClassesInternalServerError {
return &ApplyLimitClassesInternalServerError{}
}
/*
ApplyLimitClassesInternalServerError describes a response with status code 500, with default header values.
internal server error
*/
type ApplyLimitClassesInternalServerError struct {
}
// IsSuccess returns true when this apply limit classes internal server error response has a 2xx status code
func (o *ApplyLimitClassesInternalServerError) IsSuccess() bool {
return false
}
// IsRedirect returns true when this apply limit classes internal server error response has a 3xx status code
func (o *ApplyLimitClassesInternalServerError) IsRedirect() bool {
return false
}
// IsClientError returns true when this apply limit classes internal server error response has a 4xx status code
func (o *ApplyLimitClassesInternalServerError) IsClientError() bool {
return false
}
// IsServerError returns true when this apply limit classes internal server error response has a 5xx status code
func (o *ApplyLimitClassesInternalServerError) IsServerError() bool {
return true
}
// IsCode returns true when this apply limit classes internal server error response a status code equal to that given
func (o *ApplyLimitClassesInternalServerError) IsCode(code int) bool {
return code == 500
}
// Code gets the status code for the apply limit classes internal server error response
func (o *ApplyLimitClassesInternalServerError) Code() int {
return 500
}
func (o *ApplyLimitClassesInternalServerError) Error() string {
return fmt.Sprintf("[POST /applied-limit-class][%d] applyLimitClassesInternalServerError", 500)
}
func (o *ApplyLimitClassesInternalServerError) String() string {
return fmt.Sprintf("[POST /applied-limit-class][%d] applyLimitClassesInternalServerError", 500)
}
func (o *ApplyLimitClassesInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
return nil
}
/*
ApplyLimitClassesBody apply limit classes body
swagger:model ApplyLimitClassesBody
*/
type ApplyLimitClassesBody struct {
// email
Email string `json:"email,omitempty"`
// limit class ids
LimitClassIds []int64 `json:"limitClassIds"`
}
// Validate validates this apply limit classes body
func (o *ApplyLimitClassesBody) Validate(formats strfmt.Registry) error {
return nil
}
// ContextValidate validates this apply limit classes body based on context it is used
func (o *ApplyLimitClassesBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (o *ApplyLimitClassesBody) MarshalBinary() ([]byte, error) {
if o == nil {
return nil, nil
}
return swag.WriteJSON(o)
}
// UnmarshalBinary interface implementation
func (o *ApplyLimitClassesBody) UnmarshalBinary(b []byte) error {
var res ApplyLimitClassesBody
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*o = res
return nil
}
+92
View File
@@ -969,6 +969,52 @@ func init() {
}
}
},
"/applied-limit-class": {
"post": {
"security": [
{
"key": []
}
],
"tags": [
"admin"
],
"operationId": "applyLimitClasses",
"parameters": [
{
"name": "body",
"in": "body",
"schema": {
"properties": {
"email": {
"type": "string"
},
"limitClassIds": {
"type": "array",
"items": {
"type": "integer"
}
}
}
}
}
],
"responses": {
"200": {
"description": "applied"
},
"401": {
"description": "unauthorized"
},
"404": {
"description": "account or limit class not found"
},
"500": {
"description": "internal server error"
}
}
}
},
"/applied-limit-class/list": {
"post": {
"security": [
@@ -5454,6 +5500,52 @@ func init() {
}
}
},
"/applied-limit-class": {
"post": {
"security": [
{
"key": []
}
],
"tags": [
"admin"
],
"operationId": "applyLimitClasses",
"parameters": [
{
"name": "body",
"in": "body",
"schema": {
"properties": {
"email": {
"type": "string"
},
"limitClassIds": {
"type": "array",
"items": {
"type": "integer"
}
}
}
}
}
],
"responses": {
"200": {
"description": "applied"
},
"401": {
"description": "unauthorized"
},
"404": {
"description": "account or limit class not found"
},
"500": {
"description": "internal server error"
}
}
}
},
"/applied-limit-class/list": {
"post": {
"security": [
@@ -0,0 +1,115 @@
// Code generated by go-swagger; DO NOT EDIT.
package admin
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"context"
"net/http"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/openziti/zrok/v2/rest_model_zrok"
)
// ApplyLimitClassesHandlerFunc turns a function with the right signature into a apply limit classes handler
type ApplyLimitClassesHandlerFunc func(ApplyLimitClassesParams, *rest_model_zrok.Principal) middleware.Responder
// Handle executing the request and returning a response
func (fn ApplyLimitClassesHandlerFunc) Handle(params ApplyLimitClassesParams, principal *rest_model_zrok.Principal) middleware.Responder {
return fn(params, principal)
}
// ApplyLimitClassesHandler interface for that can handle valid apply limit classes params
type ApplyLimitClassesHandler interface {
Handle(ApplyLimitClassesParams, *rest_model_zrok.Principal) middleware.Responder
}
// NewApplyLimitClasses creates a new http.Handler for the apply limit classes operation
func NewApplyLimitClasses(ctx *middleware.Context, handler ApplyLimitClassesHandler) *ApplyLimitClasses {
return &ApplyLimitClasses{Context: ctx, Handler: handler}
}
/*
ApplyLimitClasses swagger:route POST /applied-limit-class admin applyLimitClasses
ApplyLimitClasses apply limit classes API
*/
type ApplyLimitClasses struct {
Context *middleware.Context
Handler ApplyLimitClassesHandler
}
func (o *ApplyLimitClasses) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
*r = *rCtx
}
var Params = NewApplyLimitClassesParams()
uprinc, aCtx, err := o.Context.Authorize(r, route)
if err != nil {
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
if aCtx != nil {
*r = *aCtx
}
var principal *rest_model_zrok.Principal
if uprinc != nil {
principal = uprinc.(*rest_model_zrok.Principal) // this is really a rest_model_zrok.Principal, I promise
}
if err := o.Context.BindValidRequest(r, route, &Params); err != nil { // bind params
o.Context.Respond(rw, r, route.Produces, route, err)
return
}
res := o.Handler.Handle(Params, principal) // actually handle the request
o.Context.Respond(rw, r, route.Produces, route, res)
}
// ApplyLimitClassesBody apply limit classes body
//
// swagger:model ApplyLimitClassesBody
type ApplyLimitClassesBody struct {
// email
Email string `json:"email,omitempty"`
// limit class ids
LimitClassIds []int64 `json:"limitClassIds"`
}
// Validate validates this apply limit classes body
func (o *ApplyLimitClassesBody) Validate(formats strfmt.Registry) error {
return nil
}
// ContextValidate validates this apply limit classes body based on context it is used
func (o *ApplyLimitClassesBody) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (o *ApplyLimitClassesBody) MarshalBinary() ([]byte, error) {
if o == nil {
return nil, nil
}
return swag.WriteJSON(o)
}
// UnmarshalBinary interface implementation
func (o *ApplyLimitClassesBody) UnmarshalBinary(b []byte) error {
var res ApplyLimitClassesBody
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*o = res
return nil
}
@@ -0,0 +1,75 @@
// Code generated by go-swagger; DO NOT EDIT.
package admin
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/errors"
"github.com/go-openapi/runtime"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/validate"
)
// NewApplyLimitClassesParams creates a new ApplyLimitClassesParams object
//
// There are no default values defined in the spec.
func NewApplyLimitClassesParams() ApplyLimitClassesParams {
return ApplyLimitClassesParams{}
}
// ApplyLimitClassesParams contains all the bound params for the apply limit classes operation
// typically these are obtained from a http.Request
//
// swagger:parameters applyLimitClasses
type ApplyLimitClassesParams struct {
// HTTP Request Object
HTTPRequest *http.Request `json:"-"`
/*
In: body
*/
Body ApplyLimitClassesBody
}
// BindRequest both binds and validates a request, it assumes that complex things implement a Validatable(strfmt.Registry) error interface
// for simple values it will use straight method calls.
//
// To ensure default values, the struct must have been initialized with NewApplyLimitClassesParams() beforehand.
func (o *ApplyLimitClassesParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
var res []error
o.HTTPRequest = r
if runtime.HasBody(r) {
defer func() {
_ = r.Body.Close()
}()
var body ApplyLimitClassesBody
if err := route.Consumer.Consume(r.Body, &body); err != nil {
res = append(res, errors.NewParseError("body", "body", "", err))
} else {
// validate body object
if err := body.Validate(route.Formats); err != nil {
res = append(res, err)
}
ctx := validate.WithOperationRequest(r.Context())
if err := body.ContextValidate(ctx, route.Formats); err != nil {
res = append(res, err)
}
if len(res) == 0 {
o.Body = body
}
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
@@ -0,0 +1,112 @@
// Code generated by go-swagger; DO NOT EDIT.
package admin
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"net/http"
"github.com/go-openapi/runtime"
)
// ApplyLimitClassesOKCode is the HTTP code returned for type ApplyLimitClassesOK
const ApplyLimitClassesOKCode int = 200
/*
ApplyLimitClassesOK applied
swagger:response applyLimitClassesOK
*/
type ApplyLimitClassesOK struct {
}
// NewApplyLimitClassesOK creates ApplyLimitClassesOK with default headers values
func NewApplyLimitClassesOK() *ApplyLimitClassesOK {
return &ApplyLimitClassesOK{}
}
// WriteResponse to the client
func (o *ApplyLimitClassesOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.Header().Del(runtime.HeaderContentType) // Remove Content-Type on empty responses
rw.WriteHeader(200)
}
// ApplyLimitClassesUnauthorizedCode is the HTTP code returned for type ApplyLimitClassesUnauthorized
const ApplyLimitClassesUnauthorizedCode int = 401
/*
ApplyLimitClassesUnauthorized unauthorized
swagger:response applyLimitClassesUnauthorized
*/
type ApplyLimitClassesUnauthorized struct {
}
// NewApplyLimitClassesUnauthorized creates ApplyLimitClassesUnauthorized with default headers values
func NewApplyLimitClassesUnauthorized() *ApplyLimitClassesUnauthorized {
return &ApplyLimitClassesUnauthorized{}
}
// WriteResponse to the client
func (o *ApplyLimitClassesUnauthorized) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.Header().Del(runtime.HeaderContentType) // Remove Content-Type on empty responses
rw.WriteHeader(401)
}
// ApplyLimitClassesNotFoundCode is the HTTP code returned for type ApplyLimitClassesNotFound
const ApplyLimitClassesNotFoundCode int = 404
/*
ApplyLimitClassesNotFound account or limit class not found
swagger:response applyLimitClassesNotFound
*/
type ApplyLimitClassesNotFound struct {
}
// NewApplyLimitClassesNotFound creates ApplyLimitClassesNotFound with default headers values
func NewApplyLimitClassesNotFound() *ApplyLimitClassesNotFound {
return &ApplyLimitClassesNotFound{}
}
// WriteResponse to the client
func (o *ApplyLimitClassesNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.Header().Del(runtime.HeaderContentType) // Remove Content-Type on empty responses
rw.WriteHeader(404)
}
// ApplyLimitClassesInternalServerErrorCode is the HTTP code returned for type ApplyLimitClassesInternalServerError
const ApplyLimitClassesInternalServerErrorCode int = 500
/*
ApplyLimitClassesInternalServerError internal server error
swagger:response applyLimitClassesInternalServerError
*/
type ApplyLimitClassesInternalServerError struct {
}
// NewApplyLimitClassesInternalServerError creates ApplyLimitClassesInternalServerError with default headers values
func NewApplyLimitClassesInternalServerError() *ApplyLimitClassesInternalServerError {
return &ApplyLimitClassesInternalServerError{}
}
// WriteResponse to the client
func (o *ApplyLimitClassesInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.Header().Del(runtime.HeaderContentType) // Remove Content-Type on empty responses
rw.WriteHeader(500)
}
@@ -0,0 +1,87 @@
// Code generated by go-swagger; DO NOT EDIT.
package admin
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"errors"
"net/url"
golangswaggerpaths "path"
)
// ApplyLimitClassesURL generates an URL for the apply limit classes operation
type ApplyLimitClassesURL struct {
_basePath string
}
// WithBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *ApplyLimitClassesURL) WithBasePath(bp string) *ApplyLimitClassesURL {
o.SetBasePath(bp)
return o
}
// SetBasePath sets the base path for this url builder, only required when it's different from the
// base path specified in the swagger spec.
// When the value of the base path is an empty string
func (o *ApplyLimitClassesURL) SetBasePath(bp string) {
o._basePath = bp
}
// Build a url path and query string
func (o *ApplyLimitClassesURL) Build() (*url.URL, error) {
var _result url.URL
var _path = "/applied-limit-class"
_basePath := o._basePath
if _basePath == "" {
_basePath = "/api/v2"
}
_result.Path = golangswaggerpaths.Join(_basePath, _path)
return &_result, nil
}
// Must is a helper function to panic when the url builder returns an error
func (o *ApplyLimitClassesURL) Must(u *url.URL, err error) *url.URL {
if err != nil {
panic(err)
}
if u == nil {
panic("url can't be nil")
}
return u
}
// String returns the string representation of the path with query string
func (o *ApplyLimitClassesURL) String() string {
return o.Must(o.Build()).String()
}
// BuildFull builds a full url with scheme, host, path and query string
func (o *ApplyLimitClassesURL) BuildFull(scheme, host string) (*url.URL, error) {
if scheme == "" {
return nil, errors.New("scheme is required for a full url on ApplyLimitClassesURL")
}
if host == "" {
return nil, errors.New("host is required for a full url on ApplyLimitClassesURL")
}
base, err := o.Build()
if err != nil {
return nil, err
}
base.Scheme = scheme
base.Host = host
return base, nil
}
// StringFull returns the string representation of a complete url
func (o *ApplyLimitClassesURL) StringFull(scheme, host string) string {
return o.Must(o.BuildFull(scheme, host)).String()
}
+16
View File
@@ -85,6 +85,13 @@ func NewZrokAPI(spec *loads.Document) *ZrokAPI {
return middleware.NotImplemented("operation admin.AddOrganizationMember has not yet been implemented")
}),
AdminApplyLimitClassesHandler: admin.ApplyLimitClassesHandlerFunc(func(params admin.ApplyLimitClassesParams, principal *rest_model_zrok.Principal) middleware.Responder {
_ = params
_ = principal
return middleware.NotImplemented("operation admin.ApplyLimitClasses has not yet been implemented")
}),
AccountChangePasswordHandler: account.ChangePasswordHandlerFunc(func(params account.ChangePasswordParams, principal *rest_model_zrok.Principal) middleware.Responder {
_ = params
_ = principal
@@ -668,6 +675,8 @@ type ZrokAPI struct {
AdminAddNamespaceGrantHandler admin.AddNamespaceGrantHandler
// AdminAddOrganizationMemberHandler sets the operation handler for the add organization member operation
AdminAddOrganizationMemberHandler admin.AddOrganizationMemberHandler
// AdminApplyLimitClassesHandler sets the operation handler for the apply limit classes operation
AdminApplyLimitClassesHandler admin.ApplyLimitClassesHandler
// AccountChangePasswordHandler sets the operation handler for the change password operation
AccountChangePasswordHandler account.ChangePasswordHandler
// MetadataClientVersionCheckHandler sets the operation handler for the client version check operation
@@ -916,6 +925,9 @@ func (o *ZrokAPI) Validate() error {
if o.AdminAddOrganizationMemberHandler == nil {
unregistered = append(unregistered, "admin.AddOrganizationMemberHandler")
}
if o.AdminApplyLimitClassesHandler == nil {
unregistered = append(unregistered, "admin.ApplyLimitClassesHandler")
}
if o.AccountChangePasswordHandler == nil {
unregistered = append(unregistered, "account.ChangePasswordHandler")
}
@@ -1267,6 +1279,10 @@ func (o *ZrokAPI) initHandlerCache() {
if o.handlers["POST"] == nil {
o.handlers["POST"] = make(map[string]http.Handler)
}
o.handlers["POST"]["/applied-limit-class"] = admin.NewApplyLimitClasses(o.context, o.AdminApplyLimitClassesHandler)
if o.handlers["POST"] == nil {
o.handlers["POST"] = make(map[string]http.Handler)
}
o.handlers["POST"]["/changePassword"] = account.NewChangePassword(o.context, o.AccountChangePasswordHandler)
if o.handlers["POST"] == nil {
o.handlers["POST"] = make(map[string]http.Handler)
@@ -15,6 +15,7 @@ models/AddFrontendGrantRequest.ts
models/AddNamespaceFrontendMappingRequest.ts
models/AddNamespaceGrantRequest.ts
models/AddOrganizationMemberRequest.ts
models/ApplyLimitClassesRequest.ts
models/AuthUser.ts
models/ChangePasswordRequest.ts
models/ClientVersionCheckRequest.ts
+40
View File
@@ -19,6 +19,7 @@ import type {
AddNamespaceFrontendMappingRequest,
AddNamespaceGrantRequest,
AddOrganizationMemberRequest,
ApplyLimitClassesRequest,
CreateFrontend201Response,
CreateFrontendRequest,
CreateIdentity201Response,
@@ -53,6 +54,8 @@ import {
AddNamespaceGrantRequestToJSON,
AddOrganizationMemberRequestFromJSON,
AddOrganizationMemberRequestToJSON,
ApplyLimitClassesRequestFromJSON,
ApplyLimitClassesRequestToJSON,
CreateFrontend201ResponseFromJSON,
CreateFrontend201ResponseToJSON,
CreateFrontendRequestFromJSON,
@@ -119,6 +122,10 @@ export interface AddOrganizationMemberOperationRequest {
body?: AddOrganizationMemberRequest;
}
export interface ApplyLimitClassesOperationRequest {
body?: ApplyLimitClassesRequest;
}
export interface CreateAccountRequest {
body?: LoginRequest;
}
@@ -352,6 +359,39 @@ export class AdminApi extends runtime.BaseAPI {
await this.addOrganizationMemberRaw(requestParameters, initOverrides);
}
/**
*/
async applyLimitClassesRaw(requestParameters: ApplyLimitClassesOperationRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<void>> {
const queryParameters: any = {};
const headerParameters: runtime.HTTPHeaders = {};
headerParameters['Content-Type'] = 'application/zrok.v1+json';
if (this.configuration && this.configuration.apiKey) {
headerParameters["x-token"] = await this.configuration.apiKey("x-token"); // key authentication
}
let urlPath = `/applied-limit-class`;
const response = await this.request({
path: urlPath,
method: 'POST',
headers: headerParameters,
query: queryParameters,
body: ApplyLimitClassesRequestToJSON(requestParameters['body']),
}, initOverrides);
return new runtime.VoidApiResponse(response);
}
/**
*/
async applyLimitClasses(requestParameters: ApplyLimitClassesOperationRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<void> {
await this.applyLimitClassesRaw(requestParameters, initOverrides);
}
/**
*/
async createAccountRaw(requestParameters: CreateAccountRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<RegenerateAccountToken200Response>> {
@@ -0,0 +1,73 @@
/* tslint:disable */
/* eslint-disable */
/**
* zrok
* zrok client access
*
* The version of the OpenAPI document: 2.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { mapValues } from '../runtime';
/**
*
* @export
* @interface ApplyLimitClassesRequest
*/
export interface ApplyLimitClassesRequest {
/**
*
* @type {string}
* @memberof ApplyLimitClassesRequest
*/
email?: string;
/**
*
* @type {Array<number>}
* @memberof ApplyLimitClassesRequest
*/
limitClassIds?: Array<number>;
}
/**
* Check if a given object implements the ApplyLimitClassesRequest interface.
*/
export function instanceOfApplyLimitClassesRequest(value: object): value is ApplyLimitClassesRequest {
return true;
}
export function ApplyLimitClassesRequestFromJSON(json: any): ApplyLimitClassesRequest {
return ApplyLimitClassesRequestFromJSONTyped(json, false);
}
export function ApplyLimitClassesRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): ApplyLimitClassesRequest {
if (json == null) {
return json;
}
return {
'email': json['email'] == null ? undefined : json['email'],
'limitClassIds': json['limitClassIds'] == null ? undefined : json['limitClassIds'],
};
}
export function ApplyLimitClassesRequestToJSON(json: any): ApplyLimitClassesRequest {
return ApplyLimitClassesRequestToJSONTyped(json, false);
}
export function ApplyLimitClassesRequestToJSONTyped(value?: ApplyLimitClassesRequest | null, ignoreDiscriminator: boolean = false): any {
if (value == null) {
return value;
}
return {
'email': value['email'],
'limitClassIds': value['limitClassIds'],
};
}
+1
View File
@@ -8,6 +8,7 @@ export * from './AddFrontendGrantRequest';
export * from './AddNamespaceFrontendMappingRequest';
export * from './AddNamespaceGrantRequest';
export * from './AddOrganizationMemberRequest';
export * from './ApplyLimitClassesRequest';
export * from './AuthUser';
export * from './ChangePasswordRequest';
export * from './ClientVersionCheckRequest';
+3
View File
@@ -11,6 +11,7 @@ docs/AddNamespaceGrantRequest.md
docs/AddOrganizationMemberRequest.md
docs/AdminApi.md
docs/AgentApi.md
docs/ApplyLimitClassesRequest.md
docs/AuthUser.md
docs/ChangePasswordRequest.md
docs/ClientVersionCheckRequest.md
@@ -109,6 +110,7 @@ test/test_add_namespace_grant_request.py
test/test_add_organization_member_request.py
test/test_admin_api.py
test/test_agent_api.py
test/test_apply_limit_classes_request.py
test/test_auth_user.py
test/test_change_password_request.py
test/test_client_version_check_request.py
@@ -214,6 +216,7 @@ zrok_api/models/add_frontend_grant_request.py
zrok_api/models/add_namespace_frontend_mapping_request.py
zrok_api/models/add_namespace_grant_request.py
zrok_api/models/add_organization_member_request.py
zrok_api/models/apply_limit_classes_request.py
zrok_api/models/auth_user.py
zrok_api/models/change_password_request.py
zrok_api/models/client_version_check_request.py
+2
View File
@@ -104,6 +104,7 @@ Class | Method | HTTP request | Description
*AdminApi* | [**add_namespace_frontend_mapping**](docs/AdminApi.md#add_namespace_frontend_mapping) | **POST** /namespace/frontend/mapping |
*AdminApi* | [**add_namespace_grant**](docs/AdminApi.md#add_namespace_grant) | **POST** /namespace/grant |
*AdminApi* | [**add_organization_member**](docs/AdminApi.md#add_organization_member) | **POST** /organization/add |
*AdminApi* | [**apply_limit_classes**](docs/AdminApi.md#apply_limit_classes) | **POST** /applied-limit-class |
*AdminApi* | [**create_account**](docs/AdminApi.md#create_account) | **POST** /account |
*AdminApi* | [**create_frontend**](docs/AdminApi.md#create_frontend) | **POST** /frontend |
*AdminApi* | [**create_identity**](docs/AdminApi.md#create_identity) | **POST** /identity |
@@ -185,6 +186,7 @@ Class | Method | HTTP request | Description
- [AddNamespaceFrontendMappingRequest](docs/AddNamespaceFrontendMappingRequest.md)
- [AddNamespaceGrantRequest](docs/AddNamespaceGrantRequest.md)
- [AddOrganizationMemberRequest](docs/AddOrganizationMemberRequest.md)
- [ApplyLimitClassesRequest](docs/ApplyLimitClassesRequest.md)
- [AuthUser](docs/AuthUser.md)
- [ChangePasswordRequest](docs/ChangePasswordRequest.md)
- [ClientVersionCheckRequest](docs/ClientVersionCheckRequest.md)
+76
View File
@@ -8,6 +8,7 @@ Method | HTTP request | Description
[**add_namespace_frontend_mapping**](AdminApi.md#add_namespace_frontend_mapping) | **POST** /namespace/frontend/mapping |
[**add_namespace_grant**](AdminApi.md#add_namespace_grant) | **POST** /namespace/grant |
[**add_organization_member**](AdminApi.md#add_organization_member) | **POST** /organization/add |
[**apply_limit_classes**](AdminApi.md#apply_limit_classes) | **POST** /applied-limit-class |
[**create_account**](AdminApi.md#create_account) | **POST** /account |
[**create_frontend**](AdminApi.md#create_frontend) | **POST** /frontend |
[**create_identity**](AdminApi.md#create_identity) | **POST** /identity |
@@ -337,6 +338,81 @@ void (empty response body)
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **apply_limit_classes**
> apply_limit_classes(body=body)
### Example
* Api Key Authentication (key):
```python
import zrok_api
from zrok_api.models.apply_limit_classes_request import ApplyLimitClassesRequest
from zrok_api.rest import ApiException
from pprint import pprint
# Defining the host is optional and defaults to /api/v2
# See configuration.py for a list of all supported configuration parameters.
configuration = zrok_api.Configuration(
host = "/api/v2"
)
# The client must configure the authentication and authorization parameters
# in accordance with the API server security policy.
# Examples for each auth method are provided below, use the example that
# satisfies your auth use case.
# Configure API key authorization: key
configuration.api_key['key'] = os.environ["API_KEY"]
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
# configuration.api_key_prefix['key'] = 'Bearer'
# Enter a context with an instance of the API client
with zrok_api.ApiClient(configuration) as api_client:
# Create an instance of the API class
api_instance = zrok_api.AdminApi(api_client)
body = zrok_api.ApplyLimitClassesRequest() # ApplyLimitClassesRequest | (optional)
try:
api_instance.apply_limit_classes(body=body)
except Exception as e:
print("Exception when calling AdminApi->apply_limit_classes: %s\n" % e)
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**ApplyLimitClassesRequest**](ApplyLimitClassesRequest.md)| | [optional]
### Return type
void (empty response body)
### Authorization
[key](../README.md#key)
### HTTP request headers
- **Content-Type**: application/zrok.v1+json
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
**200** | applied | - |
**401** | unauthorized | - |
**404** | account or limit class not found | - |
**500** | internal server error | - |
[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)
# **create_account**
> RegenerateAccountToken200Response create_account(body=body)
@@ -0,0 +1,30 @@
# ApplyLimitClassesRequest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**email** | **str** | | [optional]
**limit_class_ids** | **List[int]** | | [optional]
## Example
```python
from zrok_api.models.apply_limit_classes_request import ApplyLimitClassesRequest
# TODO update the JSON string below
json = "{}"
# create an instance of ApplyLimitClassesRequest from a JSON string
apply_limit_classes_request_instance = ApplyLimitClassesRequest.from_json(json)
# print the JSON string representation of the object
print(ApplyLimitClassesRequest.to_json())
# convert the object into a dict
apply_limit_classes_request_dict = apply_limit_classes_request_instance.to_dict()
# create an instance of ApplyLimitClassesRequest from a dict
apply_limit_classes_request_from_dict = ApplyLimitClassesRequest.from_dict(apply_limit_classes_request_dict)
```
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
+6
View File
@@ -50,6 +50,12 @@ class TestAdminApi(unittest.TestCase):
"""
pass
def test_apply_limit_classes(self) -> None:
"""Test case for apply_limit_classes
"""
pass
def test_create_account(self) -> None:
"""Test case for create_account
@@ -0,0 +1,54 @@
# coding: utf-8
"""
zrok
zrok client access
The version of the OpenAPI document: 2.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
import unittest
from zrok_api.models.apply_limit_classes_request import ApplyLimitClassesRequest
class TestApplyLimitClassesRequest(unittest.TestCase):
"""ApplyLimitClassesRequest unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def make_instance(self, include_optional) -> ApplyLimitClassesRequest:
"""Test ApplyLimitClassesRequest
include_optional is a boolean, when False only required
params are included, when True both required and
optional params are included """
# uncomment below to create an instance of `ApplyLimitClassesRequest`
"""
model = ApplyLimitClassesRequest()
if include_optional:
return ApplyLimitClassesRequest(
email = '',
limit_class_ids = [
56
]
)
else:
return ApplyLimitClassesRequest(
)
"""
def testApplyLimitClassesRequest(self):
"""Test ApplyLimitClassesRequest"""
# inst_req_only = self.make_instance(include_optional=False)
# inst_req_and_optional = self.make_instance(include_optional=True)
if __name__ == '__main__':
unittest.main()
+2
View File
@@ -41,6 +41,7 @@ __all__ = [
"AddNamespaceFrontendMappingRequest",
"AddNamespaceGrantRequest",
"AddOrganizationMemberRequest",
"ApplyLimitClassesRequest",
"AuthUser",
"ChangePasswordRequest",
"ClientVersionCheckRequest",
@@ -152,6 +153,7 @@ from zrok_api.models.add_frontend_grant_request import AddFrontendGrantRequest a
from zrok_api.models.add_namespace_frontend_mapping_request import AddNamespaceFrontendMappingRequest as AddNamespaceFrontendMappingRequest
from zrok_api.models.add_namespace_grant_request import AddNamespaceGrantRequest as AddNamespaceGrantRequest
from zrok_api.models.add_organization_member_request import AddOrganizationMemberRequest as AddOrganizationMemberRequest
from zrok_api.models.apply_limit_classes_request import ApplyLimitClassesRequest as ApplyLimitClassesRequest
from zrok_api.models.auth_user import AuthUser as AuthUser
from zrok_api.models.change_password_request import ChangePasswordRequest as ChangePasswordRequest
from zrok_api.models.client_version_check_request import ClientVersionCheckRequest as ClientVersionCheckRequest
+274
View File
@@ -22,6 +22,7 @@ from zrok_api.models.add_frontend_grant_request import AddFrontendGrantRequest
from zrok_api.models.add_namespace_frontend_mapping_request import AddNamespaceFrontendMappingRequest
from zrok_api.models.add_namespace_grant_request import AddNamespaceGrantRequest
from zrok_api.models.add_organization_member_request import AddOrganizationMemberRequest
from zrok_api.models.apply_limit_classes_request import ApplyLimitClassesRequest
from zrok_api.models.create_frontend201_response import CreateFrontend201Response
from zrok_api.models.create_frontend_request import CreateFrontendRequest
from zrok_api.models.create_identity201_response import CreateIdentity201Response
@@ -1164,6 +1165,279 @@ class AdminApi:
@validate_call
def apply_limit_classes(
self,
body: Optional[ApplyLimitClassesRequest] = None,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> None:
"""apply_limit_classes
:param body:
:type body: ApplyLimitClassesRequest
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._apply_limit_classes_serialize(
body=body,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': None,
'401': None,
'404': None,
'500': None,
}
response_data = self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
response_data.read()
return self.api_client.response_deserialize(
response_data=response_data,
response_types_map=_response_types_map,
).data
@validate_call
def apply_limit_classes_with_http_info(
self,
body: Optional[ApplyLimitClassesRequest] = None,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> ApiResponse[None]:
"""apply_limit_classes
:param body:
:type body: ApplyLimitClassesRequest
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._apply_limit_classes_serialize(
body=body,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': None,
'401': None,
'404': None,
'500': None,
}
response_data = self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
response_data.read()
return self.api_client.response_deserialize(
response_data=response_data,
response_types_map=_response_types_map,
)
@validate_call
def apply_limit_classes_without_preload_content(
self,
body: Optional[ApplyLimitClassesRequest] = None,
_request_timeout: Union[
None,
Annotated[StrictFloat, Field(gt=0)],
Tuple[
Annotated[StrictFloat, Field(gt=0)],
Annotated[StrictFloat, Field(gt=0)]
]
] = None,
_request_auth: Optional[Dict[StrictStr, Any]] = None,
_content_type: Optional[StrictStr] = None,
_headers: Optional[Dict[StrictStr, Any]] = None,
_host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0,
) -> RESTResponseType:
"""apply_limit_classes
:param body:
:type body: ApplyLimitClassesRequest
:param _request_timeout: timeout setting for this request. If one
number provided, it will be total request
timeout. It can also be a pair (tuple) of
(connection, read) timeouts.
:type _request_timeout: int, tuple(int, int), optional
:param _request_auth: set to override the auth_settings for an a single
request; this effectively ignores the
authentication in the spec for a single request.
:type _request_auth: dict, optional
:param _content_type: force content-type for the request.
:type _content_type: str, Optional
:param _headers: set to override the headers for a single
request; this effectively ignores the headers
in the spec for a single request.
:type _headers: dict, optional
:param _host_index: set to override the host_index for a single
request; this effectively ignores the host_index
in the spec for a single request.
:type _host_index: int, optional
:return: Returns the result object.
""" # noqa: E501
_param = self._apply_limit_classes_serialize(
body=body,
_request_auth=_request_auth,
_content_type=_content_type,
_headers=_headers,
_host_index=_host_index
)
_response_types_map: Dict[str, Optional[str]] = {
'200': None,
'401': None,
'404': None,
'500': None,
}
response_data = self.api_client.call_api(
*_param,
_request_timeout=_request_timeout
)
return response_data.response
def _apply_limit_classes_serialize(
self,
body,
_request_auth,
_content_type,
_headers,
_host_index,
) -> RequestSerialized:
_host = None
_collection_formats: Dict[str, str] = {
}
_path_params: Dict[str, str] = {}
_query_params: List[Tuple[str, str]] = []
_header_params: Dict[str, Optional[str]] = _headers or {}
_form_params: List[Tuple[str, str]] = []
_files: Dict[
str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]]
] = {}
_body_params: Optional[bytes] = None
# process the path parameters
# process the query parameters
# process the header parameters
# process the form parameters
# process the body parameter
if body is not None:
_body_params = body
# set the HTTP header `Content-Type`
if _content_type:
_header_params['Content-Type'] = _content_type
else:
_default_content_type = (
self.api_client.select_header_content_type(
[
'application/zrok.v1+json'
]
)
)
if _default_content_type is not None:
_header_params['Content-Type'] = _default_content_type
# authentication setting
_auth_settings: List[str] = [
'key'
]
return self.api_client.param_serialize(
method='POST',
resource_path='/applied-limit-class',
path_params=_path_params,
query_params=_query_params,
header_params=_header_params,
body=_body_params,
post_params=_form_params,
files=_files,
auth_settings=_auth_settings,
collection_formats=_collection_formats,
_host=_host,
_request_auth=_request_auth
)
@validate_call
def create_account(
self,
@@ -22,6 +22,7 @@ from zrok_api.models.add_frontend_grant_request import AddFrontendGrantRequest
from zrok_api.models.add_namespace_frontend_mapping_request import AddNamespaceFrontendMappingRequest
from zrok_api.models.add_namespace_grant_request import AddNamespaceGrantRequest
from zrok_api.models.add_organization_member_request import AddOrganizationMemberRequest
from zrok_api.models.apply_limit_classes_request import ApplyLimitClassesRequest
from zrok_api.models.auth_user import AuthUser
from zrok_api.models.change_password_request import ChangePasswordRequest
from zrok_api.models.client_version_check_request import ClientVersionCheckRequest
@@ -0,0 +1,89 @@
# coding: utf-8
"""
zrok
zrok client access
The version of the OpenAPI document: 2.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
class ApplyLimitClassesRequest(BaseModel):
"""
ApplyLimitClassesRequest
""" # noqa: E501
email: Optional[StrictStr] = None
limit_class_ids: Optional[List[StrictInt]] = Field(default=None, alias="limitClassIds")
__properties: ClassVar[List[str]] = ["email", "limitClassIds"]
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
protected_namespaces=(),
)
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Optional[Self]:
"""Create an instance of ApplyLimitClassesRequest from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
excluded_fields: Set[str] = set([
])
_dict = self.model_dump(
by_alias=True,
exclude=excluded_fields,
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
"""Create an instance of ApplyLimitClassesRequest from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"email": obj.get("email"),
"limitClassIds": obj.get("limitClassIds")
})
return _obj
+28
View File
@@ -845,6 +845,34 @@
500:
description: internal server error
/applied-limit-class:
post:
tags:
- admin
security:
- key: []
operationId: applyLimitClasses
parameters:
- name: body
in: body
schema:
properties:
email:
type: string
limitClassIds:
type: array
items:
type: integer
responses:
200:
description: applied
401:
description: unauthorized
404:
description: account or limit class not found
500:
description: internal server error
/applied-limit-class/list:
post:
tags:
+28
View File
@@ -1069,6 +1069,34 @@ paths:
500:
description: internal server error
/applied-limit-class:
post:
tags:
- admin
security:
- key: []
operationId: applyLimitClasses
parameters:
- name: body
in: body
schema:
properties:
email:
type: string
limitClassIds:
type: array
items:
type: integer
responses:
200:
description: applied
401:
description: unauthorized
404:
description: account or limit class not found
500:
description: internal server error
/applied-limit-class/list:
post:
tags:
+1
View File
@@ -15,6 +15,7 @@ models/AddFrontendGrantRequest.ts
models/AddNamespaceFrontendMappingRequest.ts
models/AddNamespaceGrantRequest.ts
models/AddOrganizationMemberRequest.ts
models/ApplyLimitClassesRequest.ts
models/AuthUser.ts
models/ChangePasswordRequest.ts
models/ClientVersionCheckRequest.ts
+40
View File
@@ -19,6 +19,7 @@ import type {
AddNamespaceFrontendMappingRequest,
AddNamespaceGrantRequest,
AddOrganizationMemberRequest,
ApplyLimitClassesRequest,
CreateFrontend201Response,
CreateFrontendRequest,
CreateIdentity201Response,
@@ -53,6 +54,8 @@ import {
AddNamespaceGrantRequestToJSON,
AddOrganizationMemberRequestFromJSON,
AddOrganizationMemberRequestToJSON,
ApplyLimitClassesRequestFromJSON,
ApplyLimitClassesRequestToJSON,
CreateFrontend201ResponseFromJSON,
CreateFrontend201ResponseToJSON,
CreateFrontendRequestFromJSON,
@@ -119,6 +122,10 @@ export interface AddOrganizationMemberOperationRequest {
body?: AddOrganizationMemberRequest;
}
export interface ApplyLimitClassesOperationRequest {
body?: ApplyLimitClassesRequest;
}
export interface CreateAccountRequest {
body?: LoginRequest;
}
@@ -352,6 +359,39 @@ export class AdminApi extends runtime.BaseAPI {
await this.addOrganizationMemberRaw(requestParameters, initOverrides);
}
/**
*/
async applyLimitClassesRaw(requestParameters: ApplyLimitClassesOperationRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<void>> {
const queryParameters: any = {};
const headerParameters: runtime.HTTPHeaders = {};
headerParameters['Content-Type'] = 'application/zrok.v1+json';
if (this.configuration && this.configuration.apiKey) {
headerParameters["x-token"] = await this.configuration.apiKey("x-token"); // key authentication
}
let urlPath = `/applied-limit-class`;
const response = await this.request({
path: urlPath,
method: 'POST',
headers: headerParameters,
query: queryParameters,
body: ApplyLimitClassesRequestToJSON(requestParameters['body']),
}, initOverrides);
return new runtime.VoidApiResponse(response);
}
/**
*/
async applyLimitClasses(requestParameters: ApplyLimitClassesOperationRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<void> {
await this.applyLimitClassesRaw(requestParameters, initOverrides);
}
/**
*/
async createAccountRaw(requestParameters: CreateAccountRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<RegenerateAccountToken200Response>> {
@@ -0,0 +1,73 @@
/* tslint:disable */
/* eslint-disable */
/**
* zrok
* zrok client access
*
* The version of the OpenAPI document: 2.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { mapValues } from '../runtime';
/**
*
* @export
* @interface ApplyLimitClassesRequest
*/
export interface ApplyLimitClassesRequest {
/**
*
* @type {string}
* @memberof ApplyLimitClassesRequest
*/
email?: string;
/**
*
* @type {Array<number>}
* @memberof ApplyLimitClassesRequest
*/
limitClassIds?: Array<number>;
}
/**
* Check if a given object implements the ApplyLimitClassesRequest interface.
*/
export function instanceOfApplyLimitClassesRequest(value: object): value is ApplyLimitClassesRequest {
return true;
}
export function ApplyLimitClassesRequestFromJSON(json: any): ApplyLimitClassesRequest {
return ApplyLimitClassesRequestFromJSONTyped(json, false);
}
export function ApplyLimitClassesRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): ApplyLimitClassesRequest {
if (json == null) {
return json;
}
return {
'email': json['email'] == null ? undefined : json['email'],
'limitClassIds': json['limitClassIds'] == null ? undefined : json['limitClassIds'],
};
}
export function ApplyLimitClassesRequestToJSON(json: any): ApplyLimitClassesRequest {
return ApplyLimitClassesRequestToJSONTyped(json, false);
}
export function ApplyLimitClassesRequestToJSONTyped(value?: ApplyLimitClassesRequest | null, ignoreDiscriminator: boolean = false): any {
if (value == null) {
return value;
}
return {
'email': value['email'],
'limitClassIds': value['limitClassIds'],
};
}
+1
View File
@@ -8,6 +8,7 @@ export * from './AddFrontendGrantRequest';
export * from './AddNamespaceFrontendMappingRequest';
export * from './AddNamespaceGrantRequest';
export * from './AddOrganizationMemberRequest';
export * from './ApplyLimitClassesRequest';
export * from './AuthUser';
export * from './ChangePasswordRequest';
export * from './ClientVersionCheckRequest';