Merge pull request #150 from openziti-test-kitchen/alternate-token-method

Token-based invitations.
This commit is contained in:
Michael Quigley 2023-01-12 11:54:08 -05:00 committed by GitHub
commit 71c0503bf4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 1276 additions and 16 deletions

View File

@ -27,4 +27,4 @@ swagger generate client -P rest_model_zrok.Principal -f "$zrokSpec" -c rest_clie
echo "...generating js client" echo "...generating js client"
openapi -s specs/zrok.yml -o ui/src/api -l js openapi -s specs/zrok.yml -o ui/src/api -l js
git co rest_server_zrok/configure_zrok.go git checkout rest_server_zrok/configure_zrok.go

79
cmd/zrok/adminGenerate.go Normal file
View File

@ -0,0 +1,79 @@
package main
import (
"fmt"
"github.com/jaevor/go-nanoid"
"github.com/openziti-test-kitchen/zrok/rest_client_zrok/admin"
"github.com/openziti-test-kitchen/zrok/rest_model_zrok"
"github.com/openziti-test-kitchen/zrok/zrokdir"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
func init() {
adminCmd.AddCommand(newAdminGenerateCommand().cmd)
}
type adminGenerateCommand struct {
cmd *cobra.Command
amount int
}
func newAdminGenerateCommand() *adminGenerateCommand {
cmd := &cobra.Command{
Use: "generate",
Short: "Generate invite tokens (default: 5)",
Args: cobra.ExactArgs(0),
}
command := &adminGenerateCommand{cmd: cmd}
cmd.Run = command.run
cmd.Flags().IntVar(&command.amount, "amount", 5, "Amount of tokens to generate")
return command
}
func (cmd *adminGenerateCommand) run(_ *cobra.Command, args []string) {
var err error
tokens := make([]string, cmd.amount)
for i := 0; i < int(cmd.amount); i++ {
tokens[i], err = createToken()
if err != nil {
logrus.Error("error creating token", err)
}
}
zrd, err := zrokdir.Load()
if err != nil {
logrus.Error("error loading zrokdir", err)
}
zrok, err := zrd.Client()
if err != nil {
if !panicInstead {
logrus.Error("error creating zrok api client", err)
}
panic(err)
}
req := admin.NewInviteTokenGenerateParams()
req.Body = &rest_model_zrok.InviteTokenGenerateRequest{
Tokens: tokens,
}
_, err = zrok.Admin.InviteTokenGenerate(req, mustGetAdminAuth())
if err != nil {
if !panicInstead {
logrus.Error("error creating invite tokens", err)
}
panic(err)
}
fmt.Printf("generated %d tokens\n", len(tokens))
}
func createToken() (string, error) {
gen, err := nanoid.CustomASCII("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", 12)
if err != nil {
return "", err
}
return gen(), nil
}

View File

@ -2,6 +2,9 @@ package main
import ( import (
"fmt" "fmt"
"os"
"strings"
"github.com/charmbracelet/bubbles/textinput" "github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea" tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss" "github.com/charmbracelet/lipgloss"
@ -11,8 +14,6 @@ import (
"github.com/openziti-test-kitchen/zrok/util" "github.com/openziti-test-kitchen/zrok/util"
"github.com/openziti-test-kitchen/zrok/zrokdir" "github.com/openziti-test-kitchen/zrok/zrokdir"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"os"
"strings"
) )
func init() { func init() {
@ -20,8 +21,9 @@ func init() {
} }
type inviteCommand struct { type inviteCommand struct {
cmd *cobra.Command cmd *cobra.Command
tui inviteTui token string
tui inviteTui
} }
func newInviteCommand() *inviteCommand { func newInviteCommand() *inviteCommand {
@ -35,6 +37,9 @@ func newInviteCommand() *inviteCommand {
tui: newInviteTui(), tui: newInviteTui(),
} }
cmd.Run = command.run cmd.Run = command.run
cmd.Flags().StringVar(&command.token, "token", "", "Invite token required when zrok running in token store mode")
return command return command
} }
@ -61,6 +66,7 @@ func (cmd *inviteCommand) run(_ *cobra.Command, _ []string) {
req := account.NewInviteParams() req := account.NewInviteParams()
req.Body = &rest_model_zrok.InviteRequest{ req.Body = &rest_model_zrok.InviteRequest{
Email: email, Email: email,
Token: cmd.token,
} }
_, err = zrok.Account.Invite(req) _, err = zrok.Account.Invite(req)
if err != nil { if err != nil {

View File

@ -39,6 +39,7 @@ type EmailConfig struct {
type RegistrationConfig struct { type RegistrationConfig struct {
EmailFrom string EmailFrom string
RegistrationUrlTemplate string RegistrationUrlTemplate string
TokenStrategy string
} }
type ZitiConfig struct { type ZitiConfig struct {

View File

@ -26,13 +26,14 @@ func Run(inCfg *Config) error {
api := operations.NewZrokAPI(swaggerSpec) api := operations.NewZrokAPI(swaggerSpec)
api.KeyAuth = newZrokAuthenticator(cfg).authenticate api.KeyAuth = newZrokAuthenticator(cfg).authenticate
api.AccountInviteHandler = newInviteHandler() api.AccountInviteHandler = newInviteHandler(cfg)
api.AccountLoginHandler = account.LoginHandlerFunc(loginHandler) api.AccountLoginHandler = account.LoginHandlerFunc(loginHandler)
api.AccountRegisterHandler = newRegisterHandler() api.AccountRegisterHandler = newRegisterHandler()
api.AccountVerifyHandler = newVerifyHandler() api.AccountVerifyHandler = newVerifyHandler()
api.AdminCreateFrontendHandler = newCreateFrontendHandler() api.AdminCreateFrontendHandler = newCreateFrontendHandler()
api.AdminCreateIdentityHandler = newCreateIdentityHandler() api.AdminCreateIdentityHandler = newCreateIdentityHandler()
api.AdminDeleteFrontendHandler = newDeleteFrontendHandler() api.AdminDeleteFrontendHandler = newDeleteFrontendHandler()
api.AdminInviteTokenGenerateHandler = newInviteTokenGenerateHandler()
api.AdminListFrontendsHandler = newListFrontendsHandler() api.AdminListFrontendsHandler = newListFrontendsHandler()
api.AdminUpdateFrontendHandler = newUpdateFrontendHandler() api.AdminUpdateFrontendHandler = newUpdateFrontendHandler()
api.EnvironmentEnableHandler = newEnableHandler() api.EnvironmentEnableHandler = newEnableHandler()

View File

@ -9,10 +9,13 @@ import (
) )
type inviteHandler struct { type inviteHandler struct {
cfg *Config
} }
func newInviteHandler() *inviteHandler { func newInviteHandler(cfg *Config) *inviteHandler {
return &inviteHandler{} return &inviteHandler{
cfg: cfg,
}
} }
func (self *inviteHandler) Handle(params account.InviteParams) middleware.Responder { func (self *inviteHandler) Handle(params account.InviteParams) middleware.Responder {
@ -25,8 +28,28 @@ func (self *inviteHandler) Handle(params account.InviteParams) middleware.Respon
return account.NewInviteBadRequest() return account.NewInviteBadRequest()
} }
logrus.Infof("received account request for email '%v'", params.Body.Email) logrus.Infof("received account request for email '%v'", params.Body.Email)
var token string
token, err := createToken() tx, err := str.Begin()
if err != nil {
logrus.Error(err)
return account.NewInviteInternalServerError()
}
defer func() { _ = tx.Rollback() }()
if self.cfg.Registration.TokenStrategy == "store" {
invite, err := str.GetInviteTokenByToken(params.Body.Token, tx)
if err != nil {
logrus.Error(err)
return account.NewInviteBadRequest()
}
if err := str.DeleteInviteToken(invite.Id, tx); err != nil {
logrus.Error(err)
return account.NewInviteInternalServerError()
}
}
token, err = createToken()
if err != nil { if err != nil {
logrus.Error(err) logrus.Error(err)
return account.NewInviteInternalServerError() return account.NewInviteInternalServerError()
@ -37,13 +60,6 @@ func (self *inviteHandler) Handle(params account.InviteParams) middleware.Respon
SourceAddress: params.HTTPRequest.RemoteAddr, SourceAddress: params.HTTPRequest.RemoteAddr,
} }
tx, err := str.Begin()
if err != nil {
logrus.Error(err)
return account.NewInviteInternalServerError()
}
defer func() { _ = tx.Rollback() }()
if _, err := str.FindAccountWithEmail(params.Body.Email, tx); err == nil { if _, err := str.FindAccountWithEmail(params.Body.Email, tx); err == nil {
logrus.Errorf("found account for '%v', cannot process account request", params.Body.Email) logrus.Errorf("found account for '%v', cannot process account request", params.Body.Email)
return account.NewInviteBadRequest() return account.NewInviteBadRequest()

View File

@ -0,0 +1,55 @@
package controller
import (
"github.com/go-openapi/runtime/middleware"
"github.com/openziti-test-kitchen/zrok/controller/store"
"github.com/openziti-test-kitchen/zrok/rest_model_zrok"
"github.com/openziti-test-kitchen/zrok/rest_server_zrok/operations/account"
"github.com/openziti-test-kitchen/zrok/rest_server_zrok/operations/admin"
"github.com/sirupsen/logrus"
)
type inviteTokenGenerateHandler struct {
}
func newInviteTokenGenerateHandler() *inviteTokenGenerateHandler {
return &inviteTokenGenerateHandler{}
}
func (handler *inviteTokenGenerateHandler) Handle(params admin.InviteTokenGenerateParams, principal *rest_model_zrok.Principal) middleware.Responder {
if !principal.Admin {
logrus.Errorf("invalid admin principal")
return admin.NewInviteTokenGenerateUnauthorized()
}
if params.Body == nil || len(params.Body.Tokens) == 0 {
logrus.Error("missing tokens")
return admin.NewInviteTokenGenerateBadRequest()
}
logrus.Infof("received invite generate request with %d tokens", len(params.Body.Tokens))
invites := make([]*store.InviteToken, len(params.Body.Tokens))
for i, token := range params.Body.Tokens {
invites[i] = &store.InviteToken{
Token: token,
}
}
tx, err := str.Begin()
if err != nil {
logrus.Error(err)
return admin.NewInviteTokenGenerateInternalServerError()
}
defer func() { _ = tx.Rollback() }()
if err := str.CreateInviteTokens(invites, tx); err != nil {
logrus.Error(err)
return admin.NewInviteTokenGenerateInternalServerError()
}
if err := tx.Commit(); err != nil {
logrus.Errorf("error committing inviteGenerate request: %v", err)
return account.NewInviteInternalServerError()
}
return admin.NewInviteTokenGenerateCreated()
}

View File

@ -0,0 +1,52 @@
package store
import (
"fmt"
"strings"
"github.com/jmoiron/sqlx"
"github.com/pkg/errors"
)
type InviteToken struct {
Model
Token string
}
func (str *Store) CreateInviteTokens(inviteTokens []*InviteToken, tx *sqlx.Tx) error {
sql := "insert into invite_tokens (token) values %s"
invs := make([]any, len(inviteTokens))
queries := make([]string, len(inviteTokens))
for i, inv := range inviteTokens {
invs[i] = inv.Token
queries[i] = fmt.Sprintf("($%d)", i+1)
}
stmt, err := tx.Prepare(fmt.Sprintf(sql, strings.Join(queries, ",")))
if err != nil {
return errors.Wrap(err, "error preparing invite_tokenss insert statement")
}
if _, err := stmt.Exec(invs...); err != nil {
return errors.Wrap(err, "error executing invites_tokens insert statement")
}
return nil
}
func (str *Store) GetInviteTokenByToken(token string, tx *sqlx.Tx) (*InviteToken, error) {
inviteToken := &InviteToken{}
if err := tx.QueryRowx("select * from invite_tokens where token = $1", token).StructScan(inviteToken); err != nil {
return nil, errors.Wrap(err, "error getting unused invite_token")
}
return inviteToken, nil
}
func (str *Store) DeleteInviteToken(id int, tx *sqlx.Tx) error {
stmt, err := tx.Prepare("delete from invite_tokens where id = $1")
if err != nil {
return errors.Wrap(err, "error preparing invite_tokens delete statement")
}
_, err = stmt.Exec(id)
if err != nil {
return errors.Wrap(err, "error executing invite_tokens delete statement")
}
return nil
}

View File

@ -0,0 +1,14 @@
-- +migrate Up
--
-- invite_tokens
---
create table invite_tokens (
id serial primary key,
token varchar(32) not null unique,
created_at timestamptz not null default(current_timestamp),
updated_at timestamptz not null default(current_timestamp),
constraint chk_token check(token <> '')
);

View File

@ -0,0 +1,14 @@
-- +migrate Up
--
-- invite_tokens
---
create table invite_tokens (
id integer primary key,
token string not null unique,
created_at datetime not null default(strftime('%Y-%m-%d %H:%M:%f', 'now')),
updated_at datetime not null default(strftime('%Y-%m-%d %H:%M:%f', 'now')),
constraint chk_token check(token <> '')
);

View File

@ -36,6 +36,8 @@ type ClientService interface {
DeleteFrontend(params *DeleteFrontendParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteFrontendOK, error) DeleteFrontend(params *DeleteFrontendParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*DeleteFrontendOK, error)
InviteTokenGenerate(params *InviteTokenGenerateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*InviteTokenGenerateCreated, error)
ListFrontends(params *ListFrontendsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListFrontendsOK, error) ListFrontends(params *ListFrontendsParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*ListFrontendsOK, error)
UpdateFrontend(params *UpdateFrontendParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateFrontendOK, error) UpdateFrontend(params *UpdateFrontendParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*UpdateFrontendOK, error)
@ -160,6 +162,45 @@ func (a *Client) DeleteFrontend(params *DeleteFrontendParams, authInfo runtime.C
panic(msg) panic(msg)
} }
/*
InviteTokenGenerate invite token generate API
*/
func (a *Client) InviteTokenGenerate(params *InviteTokenGenerateParams, authInfo runtime.ClientAuthInfoWriter, opts ...ClientOption) (*InviteTokenGenerateCreated, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewInviteTokenGenerateParams()
}
op := &runtime.ClientOperation{
ID: "inviteTokenGenerate",
Method: "POST",
PathPattern: "/invite/token/generate",
ProducesMediaTypes: []string{"application/zrok.v1+json"},
ConsumesMediaTypes: []string{"application/zrok.v1+json"},
Schemes: []string{"http"},
Params: params,
Reader: &InviteTokenGenerateReader{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.(*InviteTokenGenerateCreated)
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 inviteTokenGenerate: API contract not enforced by server. Client expected to get an error, but got: %T", result)
panic(msg)
}
/* /*
ListFrontends list frontends API ListFrontends list frontends API
*/ */

View File

@ -0,0 +1,150 @@
// 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"
"github.com/openziti-test-kitchen/zrok/rest_model_zrok"
)
// NewInviteTokenGenerateParams creates a new InviteTokenGenerateParams 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 NewInviteTokenGenerateParams() *InviteTokenGenerateParams {
return &InviteTokenGenerateParams{
timeout: cr.DefaultTimeout,
}
}
// NewInviteTokenGenerateParamsWithTimeout creates a new InviteTokenGenerateParams object
// with the ability to set a timeout on a request.
func NewInviteTokenGenerateParamsWithTimeout(timeout time.Duration) *InviteTokenGenerateParams {
return &InviteTokenGenerateParams{
timeout: timeout,
}
}
// NewInviteTokenGenerateParamsWithContext creates a new InviteTokenGenerateParams object
// with the ability to set a context for a request.
func NewInviteTokenGenerateParamsWithContext(ctx context.Context) *InviteTokenGenerateParams {
return &InviteTokenGenerateParams{
Context: ctx,
}
}
// NewInviteTokenGenerateParamsWithHTTPClient creates a new InviteTokenGenerateParams object
// with the ability to set a custom HTTPClient for a request.
func NewInviteTokenGenerateParamsWithHTTPClient(client *http.Client) *InviteTokenGenerateParams {
return &InviteTokenGenerateParams{
HTTPClient: client,
}
}
/*
InviteTokenGenerateParams contains all the parameters to send to the API endpoint
for the invite token generate operation.
Typically these are written to a http.Request.
*/
type InviteTokenGenerateParams struct {
// Body.
Body *rest_model_zrok.InviteTokenGenerateRequest
timeout time.Duration
Context context.Context
HTTPClient *http.Client
}
// WithDefaults hydrates default values in the invite token generate params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *InviteTokenGenerateParams) WithDefaults() *InviteTokenGenerateParams {
o.SetDefaults()
return o
}
// SetDefaults hydrates default values in the invite token generate params (not the query body).
//
// All values with no default are reset to their zero value.
func (o *InviteTokenGenerateParams) SetDefaults() {
// no default values defined for this parameter
}
// WithTimeout adds the timeout to the invite token generate params
func (o *InviteTokenGenerateParams) WithTimeout(timeout time.Duration) *InviteTokenGenerateParams {
o.SetTimeout(timeout)
return o
}
// SetTimeout adds the timeout to the invite token generate params
func (o *InviteTokenGenerateParams) SetTimeout(timeout time.Duration) {
o.timeout = timeout
}
// WithContext adds the context to the invite token generate params
func (o *InviteTokenGenerateParams) WithContext(ctx context.Context) *InviteTokenGenerateParams {
o.SetContext(ctx)
return o
}
// SetContext adds the context to the invite token generate params
func (o *InviteTokenGenerateParams) SetContext(ctx context.Context) {
o.Context = ctx
}
// WithHTTPClient adds the HTTPClient to the invite token generate params
func (o *InviteTokenGenerateParams) WithHTTPClient(client *http.Client) *InviteTokenGenerateParams {
o.SetHTTPClient(client)
return o
}
// SetHTTPClient adds the HTTPClient to the invite token generate params
func (o *InviteTokenGenerateParams) SetHTTPClient(client *http.Client) {
o.HTTPClient = client
}
// WithBody adds the body to the invite token generate params
func (o *InviteTokenGenerateParams) WithBody(body *rest_model_zrok.InviteTokenGenerateRequest) *InviteTokenGenerateParams {
o.SetBody(body)
return o
}
// SetBody adds the body to the invite token generate params
func (o *InviteTokenGenerateParams) SetBody(body *rest_model_zrok.InviteTokenGenerateRequest) {
o.Body = body
}
// WriteToRequest writes these params to a swagger request
func (o *InviteTokenGenerateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {
if err := r.SetTimeout(o.timeout); err != nil {
return err
}
var res []error
if o.Body != nil {
if err := r.SetBodyParam(o.Body); err != nil {
return err
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

View File

@ -0,0 +1,254 @@
// 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 (
"fmt"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
)
// InviteTokenGenerateReader is a Reader for the InviteTokenGenerate structure.
type InviteTokenGenerateReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *InviteTokenGenerateReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 201:
result := NewInviteTokenGenerateCreated()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
case 400:
result := NewInviteTokenGenerateBadRequest()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
case 401:
result := NewInviteTokenGenerateUnauthorized()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
case 500:
result := NewInviteTokenGenerateInternalServerError()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
default:
return nil, runtime.NewAPIError("response status code does not match any response statuses defined for this endpoint in the swagger spec", response, response.Code())
}
}
// NewInviteTokenGenerateCreated creates a InviteTokenGenerateCreated with default headers values
func NewInviteTokenGenerateCreated() *InviteTokenGenerateCreated {
return &InviteTokenGenerateCreated{}
}
/*
InviteTokenGenerateCreated describes a response with status code 201, with default header values.
invitation tokens created
*/
type InviteTokenGenerateCreated struct {
}
// IsSuccess returns true when this invite token generate created response has a 2xx status code
func (o *InviteTokenGenerateCreated) IsSuccess() bool {
return true
}
// IsRedirect returns true when this invite token generate created response has a 3xx status code
func (o *InviteTokenGenerateCreated) IsRedirect() bool {
return false
}
// IsClientError returns true when this invite token generate created response has a 4xx status code
func (o *InviteTokenGenerateCreated) IsClientError() bool {
return false
}
// IsServerError returns true when this invite token generate created response has a 5xx status code
func (o *InviteTokenGenerateCreated) IsServerError() bool {
return false
}
// IsCode returns true when this invite token generate created response a status code equal to that given
func (o *InviteTokenGenerateCreated) IsCode(code int) bool {
return code == 201
}
func (o *InviteTokenGenerateCreated) Error() string {
return fmt.Sprintf("[POST /invite/token/generate][%d] inviteTokenGenerateCreated ", 201)
}
func (o *InviteTokenGenerateCreated) String() string {
return fmt.Sprintf("[POST /invite/token/generate][%d] inviteTokenGenerateCreated ", 201)
}
func (o *InviteTokenGenerateCreated) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
return nil
}
// NewInviteTokenGenerateBadRequest creates a InviteTokenGenerateBadRequest with default headers values
func NewInviteTokenGenerateBadRequest() *InviteTokenGenerateBadRequest {
return &InviteTokenGenerateBadRequest{}
}
/*
InviteTokenGenerateBadRequest describes a response with status code 400, with default header values.
invitation tokens not created
*/
type InviteTokenGenerateBadRequest struct {
}
// IsSuccess returns true when this invite token generate bad request response has a 2xx status code
func (o *InviteTokenGenerateBadRequest) IsSuccess() bool {
return false
}
// IsRedirect returns true when this invite token generate bad request response has a 3xx status code
func (o *InviteTokenGenerateBadRequest) IsRedirect() bool {
return false
}
// IsClientError returns true when this invite token generate bad request response has a 4xx status code
func (o *InviteTokenGenerateBadRequest) IsClientError() bool {
return true
}
// IsServerError returns true when this invite token generate bad request response has a 5xx status code
func (o *InviteTokenGenerateBadRequest) IsServerError() bool {
return false
}
// IsCode returns true when this invite token generate bad request response a status code equal to that given
func (o *InviteTokenGenerateBadRequest) IsCode(code int) bool {
return code == 400
}
func (o *InviteTokenGenerateBadRequest) Error() string {
return fmt.Sprintf("[POST /invite/token/generate][%d] inviteTokenGenerateBadRequest ", 400)
}
func (o *InviteTokenGenerateBadRequest) String() string {
return fmt.Sprintf("[POST /invite/token/generate][%d] inviteTokenGenerateBadRequest ", 400)
}
func (o *InviteTokenGenerateBadRequest) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
return nil
}
// NewInviteTokenGenerateUnauthorized creates a InviteTokenGenerateUnauthorized with default headers values
func NewInviteTokenGenerateUnauthorized() *InviteTokenGenerateUnauthorized {
return &InviteTokenGenerateUnauthorized{}
}
/*
InviteTokenGenerateUnauthorized describes a response with status code 401, with default header values.
unauthorized
*/
type InviteTokenGenerateUnauthorized struct {
}
// IsSuccess returns true when this invite token generate unauthorized response has a 2xx status code
func (o *InviteTokenGenerateUnauthorized) IsSuccess() bool {
return false
}
// IsRedirect returns true when this invite token generate unauthorized response has a 3xx status code
func (o *InviteTokenGenerateUnauthorized) IsRedirect() bool {
return false
}
// IsClientError returns true when this invite token generate unauthorized response has a 4xx status code
func (o *InviteTokenGenerateUnauthorized) IsClientError() bool {
return true
}
// IsServerError returns true when this invite token generate unauthorized response has a 5xx status code
func (o *InviteTokenGenerateUnauthorized) IsServerError() bool {
return false
}
// IsCode returns true when this invite token generate unauthorized response a status code equal to that given
func (o *InviteTokenGenerateUnauthorized) IsCode(code int) bool {
return code == 401
}
func (o *InviteTokenGenerateUnauthorized) Error() string {
return fmt.Sprintf("[POST /invite/token/generate][%d] inviteTokenGenerateUnauthorized ", 401)
}
func (o *InviteTokenGenerateUnauthorized) String() string {
return fmt.Sprintf("[POST /invite/token/generate][%d] inviteTokenGenerateUnauthorized ", 401)
}
func (o *InviteTokenGenerateUnauthorized) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
return nil
}
// NewInviteTokenGenerateInternalServerError creates a InviteTokenGenerateInternalServerError with default headers values
func NewInviteTokenGenerateInternalServerError() *InviteTokenGenerateInternalServerError {
return &InviteTokenGenerateInternalServerError{}
}
/*
InviteTokenGenerateInternalServerError describes a response with status code 500, with default header values.
internal server error
*/
type InviteTokenGenerateInternalServerError struct {
}
// IsSuccess returns true when this invite token generate internal server error response has a 2xx status code
func (o *InviteTokenGenerateInternalServerError) IsSuccess() bool {
return false
}
// IsRedirect returns true when this invite token generate internal server error response has a 3xx status code
func (o *InviteTokenGenerateInternalServerError) IsRedirect() bool {
return false
}
// IsClientError returns true when this invite token generate internal server error response has a 4xx status code
func (o *InviteTokenGenerateInternalServerError) IsClientError() bool {
return false
}
// IsServerError returns true when this invite token generate internal server error response has a 5xx status code
func (o *InviteTokenGenerateInternalServerError) IsServerError() bool {
return true
}
// IsCode returns true when this invite token generate internal server error response a status code equal to that given
func (o *InviteTokenGenerateInternalServerError) IsCode(code int) bool {
return code == 500
}
func (o *InviteTokenGenerateInternalServerError) Error() string {
return fmt.Sprintf("[POST /invite/token/generate][%d] inviteTokenGenerateInternalServerError ", 500)
}
func (o *InviteTokenGenerateInternalServerError) String() string {
return fmt.Sprintf("[POST /invite/token/generate][%d] inviteTokenGenerateInternalServerError ", 500)
}
func (o *InviteTokenGenerateInternalServerError) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
return nil
}

View File

@ -19,6 +19,9 @@ type InviteRequest struct {
// email // email
Email string `json:"email,omitempty"` Email string `json:"email,omitempty"`
// token
Token string `json:"token,omitempty"`
} }
// Validate validates this invite request // Validate validates this invite request

View File

@ -0,0 +1,50 @@
// Code generated by go-swagger; DO NOT EDIT.
package rest_model_zrok
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// InviteTokenGenerateRequest invite token generate request
//
// swagger:model inviteTokenGenerateRequest
type InviteTokenGenerateRequest struct {
// tokens
Tokens []string `json:"tokens"`
}
// Validate validates this invite token generate request
func (m *InviteTokenGenerateRequest) Validate(formats strfmt.Registry) error {
return nil
}
// ContextValidate validates this invite token generate request based on context it is used
func (m *InviteTokenGenerateRequest) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *InviteTokenGenerateRequest) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *InviteTokenGenerateRequest) UnmarshalBinary(b []byte) error {
var res InviteTokenGenerateRequest
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View File

@ -431,6 +431,42 @@ func init() {
} }
} }
}, },
"/invite/token/generate": {
"post": {
"security": [
{
"key": []
}
],
"tags": [
"admin"
],
"operationId": "inviteTokenGenerate",
"parameters": [
{
"name": "body",
"in": "body",
"schema": {
"$ref": "#/definitions/inviteTokenGenerateRequest"
}
}
],
"responses": {
"201": {
"description": "invitation tokens created"
},
"400": {
"description": "invitation tokens not created"
},
"401": {
"description": "unauthorized"
},
"500": {
"description": "internal server error"
}
}
}
},
"/login": { "/login": {
"post": { "post": {
"tags": [ "tags": [
@ -864,6 +900,20 @@ func init() {
"properties": { "properties": {
"email": { "email": {
"type": "string" "type": "string"
},
"token": {
"type": "string"
}
}
},
"inviteTokenGenerateRequest": {
"type": "object",
"properties": {
"tokens": {
"type": "array",
"items": {
"type": "string"
}
} }
} }
}, },
@ -1549,6 +1599,42 @@ func init() {
} }
} }
}, },
"/invite/token/generate": {
"post": {
"security": [
{
"key": []
}
],
"tags": [
"admin"
],
"operationId": "inviteTokenGenerate",
"parameters": [
{
"name": "body",
"in": "body",
"schema": {
"$ref": "#/definitions/inviteTokenGenerateRequest"
}
}
],
"responses": {
"201": {
"description": "invitation tokens created"
},
"400": {
"description": "invitation tokens not created"
},
"401": {
"description": "unauthorized"
},
"500": {
"description": "internal server error"
}
}
}
},
"/login": { "/login": {
"post": { "post": {
"tags": [ "tags": [
@ -1982,6 +2068,20 @@ func init() {
"properties": { "properties": {
"email": { "email": {
"type": "string" "type": "string"
},
"token": {
"type": "string"
}
}
},
"inviteTokenGenerateRequest": {
"type": "object",
"properties": {
"tokens": {
"type": "array",
"items": {
"type": "string"
}
} }
} }
}, },

View File

@ -0,0 +1,71 @@
// 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 (
"net/http"
"github.com/go-openapi/runtime/middleware"
"github.com/openziti-test-kitchen/zrok/rest_model_zrok"
)
// InviteTokenGenerateHandlerFunc turns a function with the right signature into a invite token generate handler
type InviteTokenGenerateHandlerFunc func(InviteTokenGenerateParams, *rest_model_zrok.Principal) middleware.Responder
// Handle executing the request and returning a response
func (fn InviteTokenGenerateHandlerFunc) Handle(params InviteTokenGenerateParams, principal *rest_model_zrok.Principal) middleware.Responder {
return fn(params, principal)
}
// InviteTokenGenerateHandler interface for that can handle valid invite token generate params
type InviteTokenGenerateHandler interface {
Handle(InviteTokenGenerateParams, *rest_model_zrok.Principal) middleware.Responder
}
// NewInviteTokenGenerate creates a new http.Handler for the invite token generate operation
func NewInviteTokenGenerate(ctx *middleware.Context, handler InviteTokenGenerateHandler) *InviteTokenGenerate {
return &InviteTokenGenerate{Context: ctx, Handler: handler}
}
/*
InviteTokenGenerate swagger:route POST /invite/token/generate admin inviteTokenGenerate
InviteTokenGenerate invite token generate API
*/
type InviteTokenGenerate struct {
Context *middleware.Context
Handler InviteTokenGenerateHandler
}
func (o *InviteTokenGenerate) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
route, rCtx, _ := o.Context.RouteInfo(r)
if rCtx != nil {
*r = *rCtx
}
var Params = NewInviteTokenGenerateParams()
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,76 @@
// 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"
"github.com/openziti-test-kitchen/zrok/rest_model_zrok"
)
// NewInviteTokenGenerateParams creates a new InviteTokenGenerateParams object
//
// There are no default values defined in the spec.
func NewInviteTokenGenerateParams() InviteTokenGenerateParams {
return InviteTokenGenerateParams{}
}
// InviteTokenGenerateParams contains all the bound params for the invite token generate operation
// typically these are obtained from a http.Request
//
// swagger:parameters inviteTokenGenerate
type InviteTokenGenerateParams struct {
// HTTP Request Object
HTTPRequest *http.Request `json:"-"`
/*
In: body
*/
Body *rest_model_zrok.InviteTokenGenerateRequest
}
// 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 NewInviteTokenGenerateParams() beforehand.
func (o *InviteTokenGenerateParams) BindRequest(r *http.Request, route *middleware.MatchedRoute) error {
var res []error
o.HTTPRequest = r
if runtime.HasBody(r) {
defer r.Body.Close()
var body rest_model_zrok.InviteTokenGenerateRequest
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
}

View File

@ -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"
)
// InviteTokenGenerateCreatedCode is the HTTP code returned for type InviteTokenGenerateCreated
const InviteTokenGenerateCreatedCode int = 201
/*
InviteTokenGenerateCreated invitation tokens created
swagger:response inviteTokenGenerateCreated
*/
type InviteTokenGenerateCreated struct {
}
// NewInviteTokenGenerateCreated creates InviteTokenGenerateCreated with default headers values
func NewInviteTokenGenerateCreated() *InviteTokenGenerateCreated {
return &InviteTokenGenerateCreated{}
}
// WriteResponse to the client
func (o *InviteTokenGenerateCreated) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses
rw.WriteHeader(201)
}
// InviteTokenGenerateBadRequestCode is the HTTP code returned for type InviteTokenGenerateBadRequest
const InviteTokenGenerateBadRequestCode int = 400
/*
InviteTokenGenerateBadRequest invitation tokens not created
swagger:response inviteTokenGenerateBadRequest
*/
type InviteTokenGenerateBadRequest struct {
}
// NewInviteTokenGenerateBadRequest creates InviteTokenGenerateBadRequest with default headers values
func NewInviteTokenGenerateBadRequest() *InviteTokenGenerateBadRequest {
return &InviteTokenGenerateBadRequest{}
}
// WriteResponse to the client
func (o *InviteTokenGenerateBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses
rw.WriteHeader(400)
}
// InviteTokenGenerateUnauthorizedCode is the HTTP code returned for type InviteTokenGenerateUnauthorized
const InviteTokenGenerateUnauthorizedCode int = 401
/*
InviteTokenGenerateUnauthorized unauthorized
swagger:response inviteTokenGenerateUnauthorized
*/
type InviteTokenGenerateUnauthorized struct {
}
// NewInviteTokenGenerateUnauthorized creates InviteTokenGenerateUnauthorized with default headers values
func NewInviteTokenGenerateUnauthorized() *InviteTokenGenerateUnauthorized {
return &InviteTokenGenerateUnauthorized{}
}
// WriteResponse to the client
func (o *InviteTokenGenerateUnauthorized) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) {
rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses
rw.WriteHeader(401)
}
// InviteTokenGenerateInternalServerErrorCode is the HTTP code returned for type InviteTokenGenerateInternalServerError
const InviteTokenGenerateInternalServerErrorCode int = 500
/*
InviteTokenGenerateInternalServerError internal server error
swagger:response inviteTokenGenerateInternalServerError
*/
type InviteTokenGenerateInternalServerError struct {
}
// NewInviteTokenGenerateInternalServerError creates InviteTokenGenerateInternalServerError with default headers values
func NewInviteTokenGenerateInternalServerError() *InviteTokenGenerateInternalServerError {
return &InviteTokenGenerateInternalServerError{}
}
// WriteResponse to the client
func (o *InviteTokenGenerateInternalServerError) 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,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"
)
// InviteTokenGenerateURL generates an URL for the invite token generate operation
type InviteTokenGenerateURL 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 *InviteTokenGenerateURL) WithBasePath(bp string) *InviteTokenGenerateURL {
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 *InviteTokenGenerateURL) SetBasePath(bp string) {
o._basePath = bp
}
// Build a url path and query string
func (o *InviteTokenGenerateURL) Build() (*url.URL, error) {
var _result url.URL
var _path = "/invite/token/generate"
_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 *InviteTokenGenerateURL) 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 *InviteTokenGenerateURL) String() string {
return o.Must(o.Build()).String()
}
// BuildFull builds a full url with scheme, host, path and query string
func (o *InviteTokenGenerateURL) BuildFull(scheme, host string) (*url.URL, error) {
if scheme == "" {
return nil, errors.New("scheme is required for a full url on InviteTokenGenerateURL")
}
if host == "" {
return nil, errors.New("host is required for a full url on InviteTokenGenerateURL")
}
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 *InviteTokenGenerateURL) StringFull(scheme, host string) string {
return o.Must(o.BuildFull(scheme, host)).String()
}

View File

@ -76,6 +76,9 @@ func NewZrokAPI(spec *loads.Document) *ZrokAPI {
AccountInviteHandler: account.InviteHandlerFunc(func(params account.InviteParams) middleware.Responder { AccountInviteHandler: account.InviteHandlerFunc(func(params account.InviteParams) middleware.Responder {
return middleware.NotImplemented("operation account.Invite has not yet been implemented") return middleware.NotImplemented("operation account.Invite has not yet been implemented")
}), }),
AdminInviteTokenGenerateHandler: admin.InviteTokenGenerateHandlerFunc(func(params admin.InviteTokenGenerateParams, principal *rest_model_zrok.Principal) middleware.Responder {
return middleware.NotImplemented("operation admin.InviteTokenGenerate has not yet been implemented")
}),
AdminListFrontendsHandler: admin.ListFrontendsHandlerFunc(func(params admin.ListFrontendsParams, principal *rest_model_zrok.Principal) middleware.Responder { AdminListFrontendsHandler: admin.ListFrontendsHandlerFunc(func(params admin.ListFrontendsParams, principal *rest_model_zrok.Principal) middleware.Responder {
return middleware.NotImplemented("operation admin.ListFrontends has not yet been implemented") return middleware.NotImplemented("operation admin.ListFrontends has not yet been implemented")
}), }),
@ -177,6 +180,8 @@ type ZrokAPI struct {
MetadataGetShareDetailHandler metadata.GetShareDetailHandler MetadataGetShareDetailHandler metadata.GetShareDetailHandler
// AccountInviteHandler sets the operation handler for the invite operation // AccountInviteHandler sets the operation handler for the invite operation
AccountInviteHandler account.InviteHandler AccountInviteHandler account.InviteHandler
// AdminInviteTokenGenerateHandler sets the operation handler for the invite token generate operation
AdminInviteTokenGenerateHandler admin.InviteTokenGenerateHandler
// AdminListFrontendsHandler sets the operation handler for the list frontends operation // AdminListFrontendsHandler sets the operation handler for the list frontends operation
AdminListFrontendsHandler admin.ListFrontendsHandler AdminListFrontendsHandler admin.ListFrontendsHandler
// AccountLoginHandler sets the operation handler for the login operation // AccountLoginHandler sets the operation handler for the login operation
@ -307,6 +312,9 @@ func (o *ZrokAPI) Validate() error {
if o.AccountInviteHandler == nil { if o.AccountInviteHandler == nil {
unregistered = append(unregistered, "account.InviteHandler") unregistered = append(unregistered, "account.InviteHandler")
} }
if o.AdminInviteTokenGenerateHandler == nil {
unregistered = append(unregistered, "admin.InviteTokenGenerateHandler")
}
if o.AdminListFrontendsHandler == nil { if o.AdminListFrontendsHandler == nil {
unregistered = append(unregistered, "admin.ListFrontendsHandler") unregistered = append(unregistered, "admin.ListFrontendsHandler")
} }
@ -475,6 +483,10 @@ func (o *ZrokAPI) initHandlerCache() {
o.handlers["POST"] = make(map[string]http.Handler) o.handlers["POST"] = make(map[string]http.Handler)
} }
o.handlers["POST"]["/invite"] = account.NewInvite(o.context, o.AccountInviteHandler) o.handlers["POST"]["/invite"] = account.NewInvite(o.context, o.AccountInviteHandler)
if o.handlers["POST"] == nil {
o.handlers["POST"] = make(map[string]http.Handler)
}
o.handlers["POST"]["/invite/token/generate"] = admin.NewInviteTokenGenerate(o.context, o.AdminInviteTokenGenerateHandler)
if o.handlers["GET"] == nil { if o.handlers["GET"] == nil {
o.handlers["GET"] = make(map[string]http.Handler) o.handlers["GET"] = make(map[string]http.Handler)
} }

View File

@ -202,6 +202,28 @@ paths:
description: unauthorized description: unauthorized
500: 500:
description: internal server error description: internal server error
/invite/token/generate:
post:
tags:
- admin
security:
- key: []
operationId: inviteTokenGenerate
parameters:
- name: body
in: body
schema:
$ref: "#/definitions/inviteTokenGenerateRequest"
responses:
201:
description: invitation tokens created
400:
description: invitation tokens not created
401:
description: unauthorized
500:
description: internal server error
# #
# environment # environment
# #
@ -552,11 +574,21 @@ definitions:
errorMessage: errorMessage:
type: string type: string
inviteTokenGenerateRequest:
type: object
properties:
tokens:
type: array
items:
type: string
inviteRequest: inviteRequest:
type: object type: object
properties: properties:
email: email:
type: string type: string
token:
type: string
loginRequest: loginRequest:
type: object type: object

View File

@ -68,6 +68,21 @@ export function createIdentity(options) {
return gateway.request(createIdentityOperation, parameters) return gateway.request(createIdentityOperation, parameters)
} }
/**
* @param {object} options Optional options
* @param {module:types.inviteTokenGenerateRequest} [options.body]
* @return {Promise<object>} invitation tokens created
*/
export function inviteTokenGenerate(options) {
if (!options) options = {}
const parameters = {
body: {
body: options.body
}
}
return gateway.request(inviteTokenGenerateOperation, parameters)
}
const createFrontendOperation = { const createFrontendOperation = {
path: '/frontend', path: '/frontend',
contentTypes: ['application/zrok.v1+json'], contentTypes: ['application/zrok.v1+json'],
@ -121,3 +136,14 @@ const createIdentityOperation = {
} }
] ]
} }
const inviteTokenGenerateOperation = {
path: '/invite/token/generate',
contentTypes: ['application/zrok.v1+json'],
method: 'post',
security: [
{
id: 'key'
}
]
}

View File

@ -91,11 +91,19 @@
* @property {module:types.shares} shares * @property {module:types.shares} shares
*/ */
/**
* @typedef inviteTokenGenerateRequest
* @memberof module:types
*
* @property {string[]} tokens
*/
/** /**
* @typedef inviteRequest * @typedef inviteRequest
* @memberof module:types * @memberof module:types
* *
* @property {string} email * @property {string} email
* @property {string} token
*/ */
/** /**