authorizer/server/resolvers/admin_signup.go

83 lines
2.0 KiB
Go
Raw Normal View History

2022-01-09 12:05:37 +00:00
package resolvers
import (
"context"
"encoding/json"
"fmt"
2022-01-19 17:49:20 +00:00
"log"
2022-01-09 12:05:37 +00:00
"strings"
"github.com/authorizerdev/authorizer/server/constants"
"github.com/authorizerdev/authorizer/server/db"
2022-01-17 06:02:13 +00:00
"github.com/authorizerdev/authorizer/server/envstore"
2022-01-09 12:05:37 +00:00
"github.com/authorizerdev/authorizer/server/graph/model"
"github.com/authorizerdev/authorizer/server/utils"
)
2022-01-17 06:02:13 +00:00
// AdminSignupResolver is a resolver for admin signup mutation
func AdminSignupResolver(ctx context.Context, params model.AdminSignupInput) (*model.Response, error) {
2022-01-09 12:05:37 +00:00
gc, err := utils.GinContextFromContext(ctx)
var res *model.Response
2022-01-09 12:05:37 +00:00
if err != nil {
return res, err
}
if strings.TrimSpace(params.AdminSecret) == "" {
err = fmt.Errorf("please select secure admin secret")
return res, err
}
if len(params.AdminSecret) < 6 {
err = fmt.Errorf("admin secret must be at least 6 characters")
return res, err
}
2022-01-17 06:02:13 +00:00
adminSecret := envstore.EnvInMemoryStoreObj.GetEnvVariable(constants.EnvKeyAdminSecret).(string)
if adminSecret != "" {
2022-01-09 12:05:37 +00:00
err = fmt.Errorf("admin sign up already completed")
return res, err
}
2022-01-17 06:02:13 +00:00
envstore.EnvInMemoryStoreObj.UpdateEnvVariable(constants.EnvKeyAdminSecret, params.AdminSecret)
2022-01-09 12:05:37 +00:00
// consvert EnvData to JSON
var jsonData map[string]interface{}
2022-01-17 06:02:13 +00:00
jsonBytes, err := json.Marshal(envstore.EnvInMemoryStoreObj.GetEnvStoreClone())
2022-01-09 12:05:37 +00:00
if err != nil {
return res, err
}
if err := json.Unmarshal(jsonBytes, &jsonData); err != nil {
return res, err
}
config, err := db.Mgr.GetConfig()
if err != nil {
return res, err
}
2022-01-17 06:02:13 +00:00
configData, err := utils.EncryptEnvData(jsonData)
2022-01-19 17:49:20 +00:00
log.Println("=> config data from signup:", configData)
2022-01-09 12:05:37 +00:00
if err != nil {
return res, err
}
config.Config = configData
if _, err := db.Mgr.UpdateConfig(config); err != nil {
return res, err
}
2022-01-17 06:02:13 +00:00
hashedKey, err := utils.EncryptPassword(params.AdminSecret)
2022-01-09 12:05:37 +00:00
if err != nil {
return res, err
}
utils.SetAdminCookie(gc, hashedKey)
res = &model.Response{
2022-01-09 12:32:16 +00:00
Message: "admin signed up successfully",
2022-01-09 12:05:37 +00:00
}
return res, nil
}