fix: init sub commands (#3218)

* fix(init): add sub commands

* fix(init): admin user in config,
test(init): verify functions

* refactor: config, remove second commands

* refactor: init steps

* chore: fix link in readme

* chore: numerate sql files

* Update cmd/admin/initialise/sql/README.md

Co-authored-by: Livio Amstutz <[email protected]>

* Update cmd/admin/initialise/sql/README.md

Co-authored-by: Livio Amstutz <[email protected]>

* fix(init): remove unused index

* user

* fix database username in defaults.yaml

Co-authored-by: Livio Amstutz <[email protected]>
This commit is contained in:
Silvan
2022-02-16 12:30:49 +00:00
committed by GitHub
co-authored by Livio Amstutz
parent 389eb4a27a
commit 4272ea6fe1
22 changed files with 639 additions and 185 deletions
+18 -20
View File
@@ -2,6 +2,8 @@ package initialise
import (
"database/sql"
_ "embed"
"fmt"
"github.com/caos/logging"
"github.com/caos/zitadel/internal/database"
@@ -9,6 +11,12 @@ import (
"github.com/spf13/viper"
)
var (
searchGrant = "SELECT * FROM [SHOW GRANTS ON DATABASE %s] where grantee = $1 AND privilege_type = 'ALL'"
//go:embed sql/03_grant_user.sql
grantStmt string
)
func newGrant() *cobra.Command {
return &cobra.Command{
Use: "grant",
@@ -19,31 +27,21 @@ Prereqesits:
- cockroachdb
`,
RunE: func(cmd *cobra.Command, args []string) error {
config := new(Config)
if err := viper.Unmarshal(config); err != nil {
config := Config{}
if err := viper.Unmarshal(&config); err != nil {
return err
}
return initialise(config, verifyGrant)
return initialise(config, verifyGrant(config.Database))
},
}
}
func verifyGrant(db *sql.DB, config database.Config) error {
logging.Info("verify grant")
exists, err := hasGrant(db, config)
if exists || err != nil {
return err
func verifyGrant(config database.Config) func(*sql.DB) error {
return func(db *sql.DB) error {
logging.WithFields("user", config.Username).Info("verify grant")
return verify(db,
exists(fmt.Sprintf(searchGrant, config.Database), config.Username),
exec(fmt.Sprintf(grantStmt, config.Database, config.Username)),
)
}
return grant(db, config)
}
func hasGrant(db *sql.DB, config database.Config) (has bool, err error) {
row := db.QueryRow("SELECT EXISTS(SELECT * FROM [SHOW GRANTS ON DATABASE "+config.Database+"] where grantee = $1 AND privilege_type = 'ALL')", config.User)
err = row.Scan(&has)
return has, err
}
func grant(db *sql.DB, config database.Config) error {
_, err := db.Exec("GRANT ALL ON DATABASE " + config.Database + " TO " + config.User)
return err
}