@@ -0,0 +1,73 @@
|
||||
// Command user provisions development identities without exposing a registration API.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"veyra/services/api/internal/identity/repository"
|
||||
"veyra/services/api/internal/identity/service"
|
||||
"veyra/services/api/internal/platform/config"
|
||||
"veyra/services/api/internal/platform/database"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
slog.Error("provision identity failed", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
func run() error {
|
||||
envFile := flag.String("env-file", "", "environment file")
|
||||
role := flag.String("role", "ADMIN", "ADMIN or USER")
|
||||
flag.Parse()
|
||||
if *envFile != "" {
|
||||
if err := config.LoadEnvFile(*envFile); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
c, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if c.Environment != "local" && c.Environment != "test" {
|
||||
return fmt.Errorf("development provisioning is disabled outside local/test environments")
|
||||
}
|
||||
var login, password, name string
|
||||
switch *role {
|
||||
case "ADMIN":
|
||||
login = os.Getenv("ADMIN_LOGIN")
|
||||
password = os.Getenv("ADMIN_PASSWORD")
|
||||
name = "管理员"
|
||||
case "USER":
|
||||
login = os.Getenv("DEV_USER_LOGIN")
|
||||
password = os.Getenv("DEV_USER_PASSWORD")
|
||||
name = "开发测试用户"
|
||||
default:
|
||||
return fmt.Errorf("role must be ADMIN or USER")
|
||||
}
|
||||
if login == "" || password == "" {
|
||||
return fmt.Errorf("configure the selected identity login and password in the local environment file")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
pool, err := database.Open(ctx, c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
auth, err := service.NewAuthService(repository.NewPostgres(pool))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
user, err := auth.ProvisionUser(ctx, login, password, name, *role)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
slog.Info("identity provisioned", "user_id", user.ID, "role", *role)
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user