add admin support to rest_model_zrok.Principal; authenticator (#116)

This commit is contained in:
Michael Quigley 2022-12-01 14:48:23 -05:00
parent b4f85e711f
commit 8610cf944a
No known key found for this signature in database
GPG Key ID: 9B60314A9DD20A62
7 changed files with 44 additions and 4 deletions

View File

@ -10,6 +10,7 @@ const ConfigVersion = 1
type Config struct {
V int
Admin *AdminConfig
Endpoint *EndpointConfig
Proxy *ProxyConfig
Email *EmailConfig
@ -20,6 +21,10 @@ type Config struct {
Influx *InfluxConfig
}
type AdminConfig struct {
Secrets []string `cf:"+secret"`
}
type EndpointConfig struct {
Host string
Port int

View File

@ -26,7 +26,7 @@ func Run(inCfg *Config) error {
}
api := operations.NewZrokAPI(swaggerSpec)
api.KeyAuth = ZrokAuthenticate
api.KeyAuth = newZrokAuthenticator(cfg).authenticate
api.AccountInviteHandler = newInviteHandler()
api.AccountLoginHandler = account.LoginHandlerFunc(loginHandler)
api.AccountRegisterHandler = newRegisterHandler()

View File

@ -13,20 +13,43 @@ import (
"strings"
)
func ZrokAuthenticate(token string) (*rest_model_zrok.Principal, error) {
type zrokAuthenticator struct {
cfg *Config
}
func newZrokAuthenticator(cfg *Config) *zrokAuthenticator {
return &zrokAuthenticator{cfg}
}
func (za *zrokAuthenticator) authenticate(token string) (*rest_model_zrok.Principal, error) {
tx, err := str.Begin()
if err != nil {
return nil, err
}
defer func() { _ = tx.Rollback() }()
if a, err := str.FindAccountWithToken(token, tx); err == nil {
principal := rest_model_zrok.Principal{
principal := &rest_model_zrok.Principal{
ID: int64(a.Id),
Token: a.Token,
Email: a.Email,
}
return &principal, nil
return principal, nil
} else {
// check for admin secret
if cfg.Admin != nil {
for _, secret := range cfg.Admin.Secrets {
if token == secret {
principal := &rest_model_zrok.Principal{
ID: int64(-1),
Admin: true,
}
return principal, nil
}
}
}
// no match
return nil, errors2.New(401, "invalid api key")
}
}

View File

@ -17,6 +17,9 @@ import (
// swagger:model principal
type Principal struct {
// admin
Admin bool `json:"admin,omitempty"`
// email
Email string `json:"email,omitempty"`

View File

@ -599,6 +599,9 @@ func init() {
"principal": {
"type": "object",
"properties": {
"admin": {
"type": "boolean"
},
"email": {
"type": "string"
},
@ -1383,6 +1386,9 @@ func init() {
"principal": {
"type": "object",
"properties": {
"admin": {
"type": "boolean"
},
"email": {
"type": "string"
},

View File

@ -399,6 +399,8 @@ definitions:
type: string
token:
type: string
admin:
type: boolean
registerRequest:
type: object

View File

@ -90,6 +90,7 @@
* @property {number} id
* @property {string} email
* @property {string} token
* @property {boolean} admin
*/
/**