initial implementation of 'orgAccountOverview' (#537)

This commit is contained in:
Michael Quigley 2024-12-10 11:46:01 -05:00
parent 7c17cce8f0
commit 65104e9e18
No known key found for this signature in database
GPG Key ID: 9B60314A9DD20A62
17 changed files with 1313 additions and 6 deletions

View File

@ -77,6 +77,7 @@ func Run(inCfg *config.Config) error {
api.MetadataGetEnvironmentDetailHandler = newEnvironmentDetailHandler()
api.MetadataGetFrontendDetailHandler = newGetFrontendDetailHandler()
api.MetadataGetShareDetailHandler = newShareDetailHandler()
api.MetadataOrgAccountOverviewHandler = newOrgAccountOverviewHandler()
api.MetadataOverviewHandler = newOverviewHandler()
api.MetadataVersionHandler = metadata.VersionHandlerFunc(versionHandler)
api.ShareAccessHandler = newAccessHandler()

View File

@ -0,0 +1,159 @@
package controller
import (
"github.com/go-openapi/runtime/middleware"
"github.com/jmoiron/sqlx"
"github.com/openziti/zrok/controller/store"
"github.com/openziti/zrok/rest_model_zrok"
"github.com/openziti/zrok/rest_server_zrok/operations/metadata"
"github.com/sirupsen/logrus"
)
type orgAccountOverviewHandler struct{}
func newOrgAccountOverviewHandler() *orgAccountOverviewHandler {
return &orgAccountOverviewHandler{}
}
func (h *orgAccountOverviewHandler) Handle(params metadata.OrgAccountOverviewParams, principal *rest_model_zrok.Principal) middleware.Responder {
trx, err := str.Begin()
if err != nil {
logrus.Errorf("error starting transaction: %v", err)
return metadata.NewOrgAccountOverviewInternalServerError()
}
defer func() { _ = trx.Rollback() }()
org, err := str.FindOrganizationByToken(params.OrganizationToken, trx)
if err != nil {
logrus.Errorf("error finding organization by token: %v", err)
return metadata.NewOrgAccountOverviewNotFound()
}
admin, err := str.IsAccountAdminOfOrganization(int(principal.ID), org.Id, trx)
if err != nil {
logrus.Errorf("error checking account admin: %v", err)
return metadata.NewOrgAccountOverviewNotFound()
}
if !admin {
logrus.Errorf("requesting account '%v' is not admin of organization '%v'", principal.Email, org.Token)
return metadata.NewOrgAccountOverviewNotFound()
}
acct, err := str.FindAccountWithEmail(params.AccountEmail, trx)
if err != nil {
logrus.Errorf("error finding account by email: %v", err)
return metadata.NewOrgAccountOverviewNotFound()
}
inOrg, err := str.IsAccountInOrganization(acct.Id, org.Id, trx)
if err != nil {
logrus.Errorf("error checking account '%v' organization membership: %v", acct.Email, err)
return metadata.NewOrgAccountOverviewNotFound()
}
if !inOrg {
logrus.Errorf("account '%v' is not a member of organization '%v'", acct.Email, org.Token)
return metadata.NewOrgAccountOverviewNotFound()
}
envs, err := str.FindEnvironmentsForAccount(acct.Id, trx)
if err != nil {
logrus.Errorf("error finding environments for '%v': %v", acct.Email, err)
return metadata.NewOrgAccountOverviewNotFound()
}
accountLimited, err := h.isAccountLimited(acct.Id, trx)
if err != nil {
logrus.Errorf("error checking account '%v' limited: %v", acct.Email, err)
}
ovr := &rest_model_zrok.Overview{AccountLimited: accountLimited}
for _, env := range envs {
ear := &rest_model_zrok.EnvironmentAndResources{
Environment: &rest_model_zrok.Environment{
Address: env.Address,
Description: env.Description,
Host: env.Host,
ZID: env.ZId,
CreatedAt: env.CreatedAt.UnixMilli(),
UpdatedAt: env.UpdatedAt.UnixMilli(),
},
}
shrs, err := str.FindSharesForEnvironment(env.Id, trx)
if err != nil {
logrus.Errorf("error finding shares for environment '%v': %v", env.ZId, err)
return metadata.NewOverviewInternalServerError()
}
for _, shr := range shrs {
feEndpoint := ""
if shr.FrontendEndpoint != nil {
feEndpoint = *shr.FrontendEndpoint
}
feSelection := ""
if shr.FrontendSelection != nil {
feSelection = *shr.FrontendSelection
}
beProxyEndpoint := ""
if shr.BackendProxyEndpoint != nil {
beProxyEndpoint = *shr.BackendProxyEndpoint
}
envShr := &rest_model_zrok.Share{
Token: shr.Token,
ZID: shr.ZId,
ShareMode: shr.ShareMode,
BackendMode: shr.BackendMode,
FrontendSelection: feSelection,
FrontendEndpoint: feEndpoint,
BackendProxyEndpoint: beProxyEndpoint,
Reserved: shr.Reserved,
CreatedAt: shr.CreatedAt.UnixMilli(),
UpdatedAt: shr.UpdatedAt.UnixMilli(),
}
ear.Shares = append(ear.Shares, envShr)
}
fes, err := str.FindFrontendsForEnvironment(env.Id, trx)
if err != nil {
logrus.Errorf("error finding frontends for environment '%v': %v", env.ZId, err)
return metadata.NewOverviewInternalServerError()
}
for _, fe := range fes {
envFe := &rest_model_zrok.Frontend{
ID: int64(fe.Id),
Token: fe.Token,
ZID: fe.ZId,
CreatedAt: fe.CreatedAt.UnixMilli(),
UpdatedAt: fe.UpdatedAt.UnixMilli(),
}
if fe.PrivateShareId != nil {
feShr, err := str.GetShare(*fe.PrivateShareId, trx)
if err != nil {
logrus.Errorf("error getting share for frontend '%v': %v", fe.ZId, err)
return metadata.NewOverviewInternalServerError()
}
envFe.ShrToken = feShr.Token
}
ear.Frontends = append(ear.Frontends, envFe)
}
ovr.Environments = append(ovr.Environments, ear)
}
return metadata.NewOrgAccountOverviewOK().WithPayload(ovr)
}
func (h *orgAccountOverviewHandler) isAccountLimited(acctId int, trx *sqlx.Tx) (bool, error) {
var je *store.BandwidthLimitJournalEntry
jEmpty, err := str.IsBandwidthLimitJournalEmpty(acctId, trx)
if err != nil {
return false, err
}
if !jEmpty {
je, err = str.FindLatestBandwidthLimitJournal(acctId, trx)
if err != nil {
return false, err
}
}
return je != nil && je.Action == store.LimitLimitAction, nil
}

View File

@ -22,18 +22,21 @@ func (h *overviewHandler) Handle(_ metadata.OverviewParams, principal *rest_mode
return metadata.NewOverviewInternalServerError()
}
defer func() { _ = trx.Rollback() }()
envs, err := str.FindEnvironmentsForAccount(int(principal.ID), trx)
if err != nil {
logrus.Errorf("error finding environments for '%v': %v", principal.Email, err)
return metadata.NewOverviewInternalServerError()
}
accountLimited, err := h.isAccountLimited(principal, trx)
if err != nil {
logrus.Errorf("error checking account limited for '%v': %v", principal.Email, err)
}
ovr := &rest_model_zrok.Overview{AccountLimited: accountLimited}
for _, env := range envs {
envRes := &rest_model_zrok.EnvironmentAndResources{
ear := &rest_model_zrok.EnvironmentAndResources{
Environment: &rest_model_zrok.Environment{
Address: env.Address,
Description: env.Description,
@ -43,6 +46,7 @@ func (h *overviewHandler) Handle(_ metadata.OverviewParams, principal *rest_mode
UpdatedAt: env.UpdatedAt.UnixMilli(),
},
}
shrs, err := str.FindSharesForEnvironment(env.Id, trx)
if err != nil {
logrus.Errorf("error finding shares for environment '%v': %v", env.ZId, err)
@ -73,7 +77,7 @@ func (h *overviewHandler) Handle(_ metadata.OverviewParams, principal *rest_mode
CreatedAt: shr.CreatedAt.UnixMilli(),
UpdatedAt: shr.UpdatedAt.UnixMilli(),
}
envRes.Shares = append(envRes.Shares, envShr)
ear.Shares = append(ear.Shares, envShr)
}
fes, err := str.FindFrontendsForEnvironment(env.Id, trx)
if err != nil {
@ -96,10 +100,12 @@ func (h *overviewHandler) Handle(_ metadata.OverviewParams, principal *rest_mode
}
envFe.ShrToken = feShr.Token
}
envRes.Frontends = append(envRes.Frontends, envFe)
ear.Frontends = append(ear.Frontends, envFe)
}
ovr.Environments = append(ovr.Environments, envRes)
ovr.Environments = append(ovr.Environments, ear)
}
return metadata.NewOverviewOK().WithPayload(ovr)
}

View File

@ -39,7 +39,7 @@ func (str *Store) FindAccountsForOrganization(orgId int, trx *sqlx.Tx) ([]*Organ
}
func (str *Store) IsAccountInOrganization(acctId, orgId int, trx *sqlx.Tx) (bool, error) {
stmt, err := trx.Prepare("select count(0) from organization_members where organization_id = $1 and account_id = $2")
stmt, err := trx.Prepare("select count(0) from organization_members where account_id = $1 and organization_id = $2")
if err != nil {
return false, errors.Wrap(err, "error preparing organization_members count statement")
}
@ -51,7 +51,7 @@ func (str *Store) IsAccountInOrganization(acctId, orgId int, trx *sqlx.Tx) (bool
}
func (str *Store) IsAccountAdminOfOrganization(acctId, orgId int, trx *sqlx.Tx) (bool, error) {
stmt, err := trx.Prepare("select count(0) from organization_members where organization_id = $1 and account_id = $2 and admin")
stmt, err := trx.Prepare("select count(0) from organization_members where account_id = $1 and organization_id = $2 and admin")
if err != nil {
return false, errors.Wrap(err, "error preparing organization_members count statement")
}

View File

@ -46,6 +46,8 @@ type ClientService interface {
GetShareMetrics(params *GetShareMetricsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*GetShareMetricsOK, error)
OrgAccountOverview(params *OrgAccountOverviewParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*OrgAccountOverviewOK, error)
Overview(params *OverviewParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*OverviewOK, error)
Version(params *VersionParams, opts ...ClientOption) (*VersionOK, error)
@ -364,6 +366,45 @@ func (a *Client) GetShareMetrics(params *GetShareMetricsParams, authInfo runtime
panic(msg)
}
/*
OrgAccountOverview org account overview API
*/
func (a *Client) OrgAccountOverview(params *OrgAccountOverviewParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*OrgAccountOverviewOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewOrgAccountOverviewParams()
}
op := &runtime.ClientOperation{
ID: "orgAccountOverview",
Method: "GET",
PathPattern: "/overview/{organizationToken}/{accountEmail}",
ProducesMediaTypes: []string{"application/zrok.v1+json"},
ConsumesMediaTypes: []string{"application/zrok.v1+json"},
Schemes: []string{"http"},
Params: params,
Reader: &OrgAccountOverviewReader{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
}
success, ok := result.(*OrgAccountOverviewOK)
if ok {
return success, nil
}
// unexpected success response
// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue
msg := fmt.Sprintf("unexpected success response for orgAccountOverview: API contract not enforced by server. Client expected to get an error, but got: %T", result)
panic(msg)
}
/*
Overview overview API
*/

View File

@ -0,0 +1,167 @@
// Code generated by go-swagger; DO NOT EDIT.
package metadata
// 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"
)
// NewOrgAccountOverviewParams creates a new OrgAccountOverviewParams 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 NewOrgAccountOverviewParams() *OrgAccountOverviewParams {
return &OrgAccountOverviewParams{
timeout: cr.DefaultTimeout,
}
}
// NewOrgAccountOverviewParamsWithTimeout creates a new OrgAccountOverviewParams object
// with the ability to set a timeout on a request.
func NewOrgAccountOverviewParamsWithTimeout(timeout time.Duration) *OrgAccountOverviewParams {
return &OrgAccountOverviewParams{
timeout: timeout,
}
}
// NewOrgAccountOverviewParamsWithContext creates a new OrgAccountOverviewParams object
// with the ability to set a context for a request.
func NewOrgAccountOverviewParamsWithContext(ctx context.Context) *OrgAccountOverviewParams {
return &OrgAccountOverviewParams{
Context: ctx,
}
}
// NewOrgAccountOverviewParamsWithHTTPClient creates a new OrgAccountOverviewParams object
// with the ability to set a custom HTTPClient for a request.
func NewOrgAccountOverviewParamsWithHTTPClient(client *http.Client) *OrgAccountOverviewParams {
return &OrgAccountOverviewParams{
HTTPClient: client,
}
}
/*
OrgAccountOverviewParams contains all the parameters to send to the API endpoint
for the org account overview operation.
Typically these are written to a http.Request.
*/
type OrgAccountOverviewParams struct {
// AccountEmail.
AccountEmail string
// OrganizationToken.
OrganizationToken string
timeout time.Duration
Context context.Context
HTTPClient *http.Client
}
// WithDefaults hydrates default values in the org account overview params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *OrgAccountOverviewParams) WithDefaults() *OrgAccountOverviewParams {
o.SetDefaults()
return o
}
// SetDefaults hydrates default values in the org account overview params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *OrgAccountOverviewParams) SetDefaults() {
// no default values defined for this parameter
}
// WithTimeout adds the timeout to the org account overview params
func (o *OrgAccountOverviewParams) WithTimeout(timeout time.Duration) *OrgAccountOverviewParams {
o.SetTimeout(timeout)
return o
}
// SetTimeout adds the timeout to the org account overview params
func (o *OrgAccountOverviewParams) SetTimeout(timeout time.Duration) {
o.timeout = timeout
}
// WithContext adds the context to the org account overview params
func (o *OrgAccountOverviewParams) WithContext(ctx context.Context) *OrgAccountOverviewParams {
o.SetContext(ctx)
return o
}
// SetContext adds the context to the org account overview params
func (o *OrgAccountOverviewParams) SetContext(ctx context.Context) {
o.Context = ctx
}
// WithHTTPClient adds the HTTPClient to the org account overview params
func (o *OrgAccountOverviewParams) WithHTTPClient(client *http.Client) *OrgAccountOverviewParams {
o.SetHTTPClient(client)
return o
}
// SetHTTPClient adds the HTTPClient to the org account overview params
func (o *OrgAccountOverviewParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithAccountEmail adds the accountEmail to the org account overview params
func (o *OrgAccountOverviewParams) WithAccountEmail(accountEmail string) *OrgAccountOverviewParams {
o.SetAccountEmail(accountEmail)
return o
}
// SetAccountEmail adds the accountEmail to the org account overview params
func (o *OrgAccountOverviewParams) SetAccountEmail(accountEmail string) {
o.AccountEmail = accountEmail
}
// WithOrganizationToken adds the organizationToken to the org account overview params
func (o *OrgAccountOverviewParams) WithOrganizationToken(organizationToken string) *OrgAccountOverviewParams {
o.SetOrganizationToken(organizationToken)
return o
}
// SetOrganizationToken adds the organizationToken to the org account overview params
func (o *OrgAccountOverviewParams) SetOrganizationToken(organizationToken string) {
o.OrganizationToken = organizationToken
}
// WriteToRequest writes these params to a swagger request
func (o *OrgAccountOverviewParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
if err := r.SetTimeout(o.timeout); err != nil {
return err
}
var res []error
// path param accountEmail
if err := r.SetPathParam("accountEmail", o.AccountEmail); err != nil {
return err
}
// path param organizationToken
if err := r.SetPathParam("organizationToken", o.OrganizationToken); err != nil {
return err
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@ -0,0 +1,227 @@
// Code generated by go-swagger; DO NOT EDIT.
package metadata
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
"github.com/openziti/zrok/rest_model_zrok"
)
// OrgAccountOverviewReader is a Reader for the OrgAccountOverview structure.
type OrgAccountOverviewReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *OrgAccountOverviewReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewOrgAccountOverviewOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
case 404:
result := NewOrgAccountOverviewNotFound()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
case 500:
result := NewOrgAccountOverviewInternalServerError()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
default:
return nil, runtime.NewAPIError("[GET /overview/{organizationToken}/{accountEmail}] orgAccountOverview", response, response.Code())
}
}
// NewOrgAccountOverviewOK creates a OrgAccountOverviewOK with default headers values
func NewOrgAccountOverviewOK() *OrgAccountOverviewOK {
return &OrgAccountOverviewOK{}
}
/*
OrgAccountOverviewOK describes a response with status code 200, with default header values.
ok
*/
type OrgAccountOverviewOK struct {
Payload *rest_model_zrok.Overview
}
// IsSuccess returns true when this org account overview o k response has a 2xx status code
func (o *OrgAccountOverviewOK) IsSuccess() bool {
return true
}
// IsRedirect returns true when this org account overview o k response has a 3xx status code
func (o *OrgAccountOverviewOK) IsRedirect() bool {
return false
}
// IsClientError returns true when this org account overview o k response has a 4xx status code
func (o *OrgAccountOverviewOK) IsClientError() bool {
return false
}
// IsServerError returns true when this org account overview o k response has a 5xx status code
func (o *OrgAccountOverviewOK) IsServerError() bool {
return false
}
// IsCode returns true when this org account overview o k response a status code equal to that given
func (o *OrgAccountOverviewOK) IsCode(code int) bool {
return code == 200
}
// Code gets the status code for the org account overview o k response
func (o *OrgAccountOverviewOK) Code() int {
return 200
}
func (o *OrgAccountOverviewOK) Error() string {
return fmt.Sprintf("[GET /overview/{organizationToken}/{accountEmail}][%d] orgAccountOverviewOK %+v", 200, o.Payload)
}
func (o *OrgAccountOverviewOK) String() string {
return fmt.Sprintf("[GET /overview/{organizationToken}/{accountEmail}][%d] orgAccountOverviewOK %+v", 200, o.Payload)
}
func (o *OrgAccountOverviewOK) GetPayload() *rest_model_zrok.Overview {
return o.Payload
}
func (o *OrgAccountOverviewOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(rest_model_zrok.Overview)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
// NewOrgAccountOverviewNotFound creates a OrgAccountOverviewNotFound with default headers values
func NewOrgAccountOverviewNotFound() *OrgAccountOverviewNotFound {
return &OrgAccountOverviewNotFound{}
}
/*
OrgAccountOverviewNotFound describes a response with status code 404, with default header values.
not found
*/
type OrgAccountOverviewNotFound struct {
}
// IsSuccess returns true when this org account overview not found response has a 2xx status code
func (o *OrgAccountOverviewNotFound) IsSuccess() bool {
return false
}
// IsRedirect returns true when this org account overview not found response has a 3xx status code
func (o *OrgAccountOverviewNotFound) IsRedirect() bool {
return false
}
// IsClientError returns true when this org account overview not found response has a 4xx status code
func (o *OrgAccountOverviewNotFound) IsClientError() bool {
return true
}
// IsServerError returns true when this org account overview not found response has a 5xx status code
func (o *OrgAccountOverviewNotFound) IsServerError() bool {
return false
}
// IsCode returns true when this org account overview not found response a status code equal to that given
func (o *OrgAccountOverviewNotFound) IsCode(code int) bool {
return code == 404
}
// Code gets the status code for the org account overview not found response
func (o *OrgAccountOverviewNotFound) Code() int {
return 404
}
func (o *OrgAccountOverviewNotFound) Error() string {
return fmt.Sprintf("[GET /overview/{organizationToken}/{accountEmail}][%d] orgAccountOverviewNotFound ", 404)
}
func (o *OrgAccountOverviewNotFound) String() string {
return fmt.Sprintf("[GET /overview/{organizationToken}/{accountEmail}][%d] orgAccountOverviewNotFound ", 404)
}
func (o *OrgAccountOverviewNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
return nil
}
// NewOrgAccountOverviewInternalServerError creates a OrgAccountOverviewInternalServerError with default headers values
func NewOrgAccountOverviewInternalServerError() *OrgAccountOverviewInternalServerError {
return &OrgAccountOverviewInternalServerError{}
}
/*
OrgAccountOverviewInternalServerError describes a response with status code 500, with default header values.
internal server error
*/
type OrgAccountOverviewInternalServerError struct {
}
// IsSuccess returns true when this org account overview internal server error response has a 2xx status code
func (o *OrgAccountOverviewInternalServerError) IsSuccess() bool {
return false
}
// IsRedirect returns true when this org account overview internal server error response has a 3xx status code
func (o *OrgAccountOverviewInternalServerError) IsRedirect() bool {
return false
}
// IsClientError returns true when this org account overview internal server error response has a 4xx status code
func (o *OrgAccountOverviewInternalServerError) IsClientError() bool {
return false
}
// IsServerError returns true when this org account overview internal server error response has a 5xx status code
func (o *OrgAccountOverviewInternalServerError) IsServerError() bool {
return true
}
// IsCode returns true when this org account overview internal server error response a status code equal to that given
func (o *OrgAccountOverviewInternalServerError) IsCode(code int) bool {
return code == 500
}
// Code gets the status code for the org account overview internal server error response
func (o *OrgAccountOverviewInternalServerError) Code() int {
return 500
}
func (o *OrgAccountOverviewInternalServerError) Error() string {
return fmt.Sprintf("[GET /overview/{organizationToken}/{accountEmail}][%d] orgAccountOverviewInternalServerError ", 500)
}
func (o *OrgAccountOverviewInternalServerError) String() string {
return fmt.Sprintf("[GET /overview/{organizationToken}/{accountEmail}][%d] orgAccountOverviewInternalServerError ", 500)
}
func (o *OrgAccountOverviewInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
return nil
}

View File

@ -1127,6 +1127,47 @@ func init() {
}
}
},
"/overview/{organizationToken}/{accountEmail}": {
"get": {
"security": [
{
"key": []
}
],
"tags": [
"metadata"
],
"operationId": "orgAccountOverview",
"parameters": [
{
"type": "string",
"name": "organizationToken",
"in": "path",
"required": true
},
{
"type": "string",
"name": "accountEmail",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "ok",
"schema": {
"$ref": "#/definitions/overview"
}
},
"404": {
"description": "not found"
},
"500": {
"description": "internal server error"
}
}
}
},
"/regenerateToken": {
"post": {
"security": [
@ -3232,6 +3273,47 @@ func init() {
}
}
},
"/overview/{organizationToken}/{accountEmail}": {
"get": {
"security": [
{
"key": []
}
],
"tags": [
"metadata"
],
"operationId": "orgAccountOverview",
"parameters": [
{
"type": "string",
"name": "organizationToken",
"in": "path",
"required": true
},
{
"type": "string",
"name": "accountEmail",
"in": "path",
"required": true
}
],
"responses": {
"200": {
"description": "ok",
"schema": {
"$ref": "#/definitions/overview"
}
},
"404": {
"description": "not found"
},
"500": {
"description": "internal server error"
}
}
}
},
"/regenerateToken": {
"post": {
"security": [

View File

@ -0,0 +1,71 @@
// Code generated by go-swagger; DO NOT EDIT.
package metadata
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the generate command
import (
"net/http"
"github.com/go-openapi/runtime/middleware"
"github.com/openziti/zrok/rest_model_zrok"
)
// OrgAccountOverviewHandlerFunc turns a function with the right signature into a org account overview handler
type OrgAccountOverviewHandlerFunc func(OrgAccountOverviewParams, *rest_model_zrok.Principal) middleware.Responder
// Handle executing the request and returning a response
func (fn OrgAccountOverviewHandlerFunc) Handle(params OrgAccountOverviewParams, principal *rest_model_zrok.Principal) middleware.Responder {
return fn(params, principal)
}
// OrgAccountOverviewHandler interface for that can handle valid org account overview params
type OrgAccountOverviewHandler interface {
Handle(OrgAccountOverviewParams, *rest_model_zrok.Principal) middleware.Responder
}
// NewOrgAccountOverview creates a new http.Handler for the org account overview operation
func NewOrgAccountOverview(ctx *middleware.Context, handler OrgAccountOverviewHandler) *OrgAccountOverview {
return &OrgAccountOverview{Context: ctx, Handler: handler}
}
/*
OrgAccountOverview swagger:route GET /overview/{organizationToken}/{accountEmail} metadata orgAccountOverview
OrgAccountOverview org account overview API
*/
type OrgAccountOverview struct {
Context *middleware.Context
Handler OrgAccountOverviewHandler
}
func (o *OrgAccountOverview) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
*r = *rCtx
}
var Params = NewOrgAccountOverviewParams()
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)
}

View File

@ -0,0 +1,95 @@
// Code generated by go-swagger; DO NOT EDIT.
package metadata
// 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/middleware"
"github.com/go-openapi/strfmt"
)
// NewOrgAccountOverviewParams creates a new OrgAccountOverviewParams object
//
// There are no default values defined in the spec.
func NewOrgAccountOverviewParams() OrgAccountOverviewParams {
return OrgAccountOverviewParams{}
}
// OrgAccountOverviewParams contains all the bound params for the org account overview operation
// typically these are obtained from a http.Request
//
// swagger:parameters orgAccountOverview
type OrgAccountOverviewParams struct {
// HTTP Request Object
HTTPRequest *http.Request `json:"-"`
/*
Required: true
In: path
*/
AccountEmail string
/*
Required: true
In: path
*/
OrganizationToken string
}
// 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 NewOrgAccountOverviewParams() beforehand.
func (o *OrgAccountOverviewParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
var res []error
o.HTTPRequest = r
rAccountEmail, rhkAccountEmail, _ := route.Params.GetOK("accountEmail")
if err := o.bindAccountEmail(rAccountEmail, rhkAccountEmail, route.Formats); err != nil {
res = append(res, err)
}
rOrganizationToken, rhkOrganizationToken, _ := route.Params.GetOK("organizationToken")
if err := o.bindOrganizationToken(rOrganizationToken, rhkOrganizationToken, route.Formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// bindAccountEmail binds and validates parameter AccountEmail from path.
func (o *OrgAccountOverviewParams) bindAccountEmail(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: true
// Parameter is provided by construction from the route
o.AccountEmail = raw
return nil
}
// bindOrganizationToken binds and validates parameter OrganizationToken from path.
func (o *OrgAccountOverviewParams) bindOrganizationToken(rawData []string, hasKey bool, formats strfmt.Registry) error {
var raw string
if len(rawData) > 0 {
raw = rawData[len(rawData)-1]
}
// Required: true
// Parameter is provided by construction from the route
o.OrganizationToken = raw
return nil
}

View File

@ -0,0 +1,109 @@
// Code generated by go-swagger; DO NOT EDIT.
package metadata
// 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"
"github.com/openziti/zrok/rest_model_zrok"
)
// OrgAccountOverviewOKCode is the HTTP code returned for type OrgAccountOverviewOK
const OrgAccountOverviewOKCode int = 200
/*
OrgAccountOverviewOK ok
swagger:response orgAccountOverviewOK
*/
type OrgAccountOverviewOK struct {
/*
In: Body
*/
Payload *rest_model_zrok.Overview `json:"body,omitempty"`
}
// NewOrgAccountOverviewOK creates OrgAccountOverviewOK with default headers values
func NewOrgAccountOverviewOK() *OrgAccountOverviewOK {
return &OrgAccountOverviewOK{}
}
// WithPayload adds the payload to the org account overview o k response
func (o *OrgAccountOverviewOK) WithPayload(payload *rest_model_zrok.Overview) *OrgAccountOverviewOK {
o.Payload = payload
return o
}
// SetPayload sets the payload to the org account overview o k response
func (o *OrgAccountOverviewOK) SetPayload(payload *rest_model_zrok.Overview) {
o.Payload = payload
}
// WriteResponse to the client
func (o *OrgAccountOverviewOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.WriteHeader(200)
if o.Payload != nil {
payload := o.Payload
if err := producer.Produce(rw, payload); err != nil {
panic(err) // let the recovery middleware deal with this
}
}
}
// OrgAccountOverviewNotFoundCode is the HTTP code returned for type OrgAccountOverviewNotFound
const OrgAccountOverviewNotFoundCode int = 404
/*
OrgAccountOverviewNotFound not found
swagger:response orgAccountOverviewNotFound
*/
type OrgAccountOverviewNotFound struct {
}
// NewOrgAccountOverviewNotFound creates OrgAccountOverviewNotFound with default headers values
func NewOrgAccountOverviewNotFound() *OrgAccountOverviewNotFound {
return &OrgAccountOverviewNotFound{}
}
// WriteResponse to the client
func (o *OrgAccountOverviewNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses
rw.WriteHeader(404)
}
// OrgAccountOverviewInternalServerErrorCode is the HTTP code returned for type OrgAccountOverviewInternalServerError
const OrgAccountOverviewInternalServerErrorCode int = 500
/*
OrgAccountOverviewInternalServerError internal server error
swagger:response orgAccountOverviewInternalServerError
*/
type OrgAccountOverviewInternalServerError struct {
}
// NewOrgAccountOverviewInternalServerError creates OrgAccountOverviewInternalServerError with default headers values
func NewOrgAccountOverviewInternalServerError() *OrgAccountOverviewInternalServerError {
return &OrgAccountOverviewInternalServerError{}
}
// WriteResponse to the client
func (o *OrgAccountOverviewInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses
rw.WriteHeader(500)
}

View File

@ -0,0 +1,107 @@
// Code generated by go-swagger; DO NOT EDIT.
package metadata
// 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"
"strings"
)
// OrgAccountOverviewURL generates an URL for the org account overview operation
type OrgAccountOverviewURL struct {
AccountEmail string
OrganizationToken string
_basePath string
// avoid unkeyed usage
_ struct{}
}
// 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 *OrgAccountOverviewURL) WithBasePath(bp string) *OrgAccountOverviewURL {
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 *OrgAccountOverviewURL) SetBasePath(bp string) {
o._basePath = bp
}
// Build a url path and query string
func (o *OrgAccountOverviewURL) Build() (*url.URL, error) {
var _result url.URL
var _path = "/overview/{organizationToken}/{accountEmail}"
accountEmail := o.AccountEmail
if accountEmail != "" {
_path = strings.Replace(_path, "{accountEmail}", accountEmail, -1)
} else {
return nil, errors.New("accountEmail is required on OrgAccountOverviewURL")
}
organizationToken := o.OrganizationToken
if organizationToken != "" {
_path = strings.Replace(_path, "{organizationToken}", organizationToken, -1)
} else {
return nil, errors.New("organizationToken is required on OrgAccountOverviewURL")
}
_basePath := o._basePath
if _basePath == "" {
_basePath = "/api/v1"
}
_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 *OrgAccountOverviewURL) 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 *OrgAccountOverviewURL) String() string {
return o.Must(o.Build()).String()
}
// BuildFull builds a full url with scheme, host, path and query string
func (o *OrgAccountOverviewURL) BuildFull(scheme, host string) (*url.URL, error) {
if scheme == "" {
return nil, errors.New("scheme is required for a full url on OrgAccountOverviewURL")
}
if host == "" {
return nil, errors.New("host is required for a full url on OrgAccountOverviewURL")
}
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 *OrgAccountOverviewURL) StringFull(scheme, host string) string {
return o.Must(o.BuildFull(scheme, host)).String()
}

View File

@ -127,6 +127,9 @@ func NewZrokAPI(spec *loads.Document) *ZrokAPI {
AccountLoginHandler: account.LoginHandlerFunc(func(params account.LoginParams) middleware.Responder {
return middleware.NotImplemented("operation account.Login has not yet been implemented")
}),
MetadataOrgAccountOverviewHandler: metadata.OrgAccountOverviewHandlerFunc(func(params metadata.OrgAccountOverviewParams, principal *rest_model_zrok.Principal) middleware.Responder {
return middleware.NotImplemented("operation metadata.OrgAccountOverview has not yet been implemented")
}),
MetadataOverviewHandler: metadata.OverviewHandlerFunc(func(params metadata.OverviewParams, principal *rest_model_zrok.Principal) middleware.Responder {
return middleware.NotImplemented("operation metadata.Overview has not yet been implemented")
}),
@ -268,6 +271,8 @@ type ZrokAPI struct {
AdminListOrganizationsHandler admin.ListOrganizationsHandler
// AccountLoginHandler sets the operation handler for the login operation
AccountLoginHandler account.LoginHandler
// MetadataOrgAccountOverviewHandler sets the operation handler for the org account overview operation
MetadataOrgAccountOverviewHandler metadata.OrgAccountOverviewHandler
// MetadataOverviewHandler sets the operation handler for the overview operation
MetadataOverviewHandler metadata.OverviewHandler
// AccountRegenerateTokenHandler sets the operation handler for the regenerate token operation
@ -453,6 +458,9 @@ func (o *ZrokAPI) Validate() error {
if o.AccountLoginHandler == nil {
unregistered = append(unregistered, "account.LoginHandler")
}
if o.MetadataOrgAccountOverviewHandler == nil {
unregistered = append(unregistered, "metadata.OrgAccountOverviewHandler")
}
if o.MetadataOverviewHandler == nil {
unregistered = append(unregistered, "metadata.OverviewHandler")
}
@ -698,6 +706,10 @@ func (o *ZrokAPI) initHandlerCache() {
if o.handlers["GET"] == nil {
o.handlers["GET"] = make(map[string]http.Handler)
}
o.handlers["GET"]["/overview/{organizationToken}/{accountEmail}"] = metadata.NewOrgAccountOverview(o.context, o.MetadataOrgAccountOverviewHandler)
if o.handlers["GET"] == nil {
o.handlers["GET"] = make(map[string]http.Handler)
}
o.handlers["GET"]["/overview"] = metadata.NewOverview(o.context, o.MetadataOverviewHandler)
if o.handlers["POST"] == nil {
o.handlers["POST"] = make(map[string]http.Handler)

View File

@ -654,6 +654,84 @@ export class MetadataApi {
});
});
}
/**
*
* @param organizationToken
* @param accountEmail
*/
public async orgAccountOverview (organizationToken: string, accountEmail: string, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: Overview; }> {
const localVarPath = this.basePath + '/overview/{organizationToken}/{accountEmail}'
.replace('{' + 'organizationToken' + '}', encodeURIComponent(String(organizationToken)))
.replace('{' + 'accountEmail' + '}', encodeURIComponent(String(accountEmail)));
let localVarQueryParameters: any = {};
let localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders);
const produces = ['application/zrok.v1+json'];
// give precedence to 'application/json'
if (produces.indexOf('application/json') >= 0) {
localVarHeaderParams.Accept = 'application/json';
} else {
localVarHeaderParams.Accept = produces.join(',');
}
let localVarFormParams: any = {};
// verify required parameter 'organizationToken' is not null or undefined
if (organizationToken === null || organizationToken === undefined) {
throw new Error('Required parameter organizationToken was null or undefined when calling orgAccountOverview.');
}
// verify required parameter 'accountEmail' is not null or undefined
if (accountEmail === null || accountEmail === undefined) {
throw new Error('Required parameter accountEmail was null or undefined when calling orgAccountOverview.');
}
(<any>Object).assign(localVarHeaderParams, options.headers);
let localVarUseFormData = false;
let localVarRequestOptions: localVarRequest.Options = {
method: 'GET',
qs: localVarQueryParameters,
headers: localVarHeaderParams,
uri: localVarPath,
useQuerystring: this._useQuerystring,
json: true,
};
let authenticationPromise = Promise.resolve();
if (this.authentications.key.apiKey) {
authenticationPromise = authenticationPromise.then(() => this.authentications.key.applyToRequest(localVarRequestOptions));
}
authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions));
let interceptorPromise = authenticationPromise;
for (const interceptor of this.interceptors) {
interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions));
}
return interceptorPromise.then(() => {
if (Object.keys(localVarFormParams).length) {
if (localVarUseFormData) {
(<any>localVarRequestOptions).formData = localVarFormParams;
} else {
localVarRequestOptions.form = localVarFormParams;
}
}
return new Promise<{ response: http.IncomingMessage; body: Overview; }>((resolve, reject) => {
localVarRequest(localVarRequestOptions, (error, response, body) => {
if (error) {
reject(error);
} else {
if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) {
body = ObjectSerializer.deserialize(body, "Overview");
resolve({ response: response, body: body });
} else {
reject(new HttpError(response, body, response.statusCode));
}
}
});
});
});
}
/**
*
*/

View File

@ -764,6 +764,107 @@ class MetadataApi(object):
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def org_account_overview(self, organization_token, account_email, **kwargs): # noqa: E501
"""org_account_overview # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.org_account_overview(organization_token, account_email, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str organization_token: (required)
:param str account_email: (required)
:return: Overview
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.org_account_overview_with_http_info(organization_token, account_email, **kwargs) # noqa: E501
else:
(data) = self.org_account_overview_with_http_info(organization_token, account_email, **kwargs) # noqa: E501
return data
def org_account_overview_with_http_info(self, organization_token, account_email, **kwargs): # noqa: E501
"""org_account_overview # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.org_account_overview_with_http_info(organization_token, account_email, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str organization_token: (required)
:param str account_email: (required)
:return: Overview
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['organization_token', 'account_email'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method org_account_overview" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'organization_token' is set
if ('organization_token' not in params or
params['organization_token'] is None):
raise ValueError("Missing the required parameter `organization_token` when calling `org_account_overview`") # noqa: E501
# verify the required parameter 'account_email' is set
if ('account_email' not in params or
params['account_email'] is None):
raise ValueError("Missing the required parameter `account_email` when calling `org_account_overview`") # noqa: E501
collection_formats = {}
path_params = {}
if 'organization_token' in params:
path_params['organizationToken'] = params['organization_token'] # noqa: E501
if 'account_email' in params:
path_params['accountEmail'] = params['account_email'] # noqa: E501
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/zrok.v1+json']) # noqa: E501
# Authentication setting
auth_settings = ['key'] # noqa: E501
return self.api_client.call_api(
'/overview/{organizationToken}/{accountEmail}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='Overview', # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def overview(self, **kwargs): # noqa: E501
"""overview # noqa: E501

View File

@ -708,6 +708,32 @@ paths:
schema:
$ref: "#/definitions/errorMessage"
/overview/{organizationToken}/{accountEmail}:
get:
tags:
- metadata
security:
- key: []
operationId: orgAccountOverview
parameters:
- name: organizationToken
in: path
type: string
required: true
- name: accountEmail
in: path
type: string
required: true
responses:
200:
description: ok
schema:
$ref: "#/definitions/overview"
404:
description: not found
500:
description: internal server error
/metrics/account:
get:
tags:

View File

@ -59,6 +59,21 @@ export function overview() {
return gateway.request(overviewOperation)
}
/**
* @param {string} organizationToken
* @param {string} accountEmail
* @return {Promise<module:types.overview>} ok
*/
export function orgAccountOverview(organizationToken, accountEmail) {
const parameters = {
path: {
organizationToken,
accountEmail
}
}
return gateway.request(orgAccountOverviewOperation, parameters)
}
/**
* @param {object} options Optional options
* @param {string} [options.duration]
@ -173,6 +188,16 @@ const overviewOperation = {
]
}
const orgAccountOverviewOperation = {
path: '/overview/{organizationToken}/{accountEmail}',
method: 'get',
security: [
{
id: 'key'
}
]
}
const getAccountMetricsOperation = {
path: '/metrics/account',
method: 'get',