60 lines
1.8 KiB
Go
60 lines
1.8 KiB
Go
// cmd/seed creates the initial admin account so the developer can hand the
|
|
// client a username/password without ever touching the database by hand.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log"
|
|
|
|
"backend/internal/modules/users"
|
|
"backend/internal/platform/config"
|
|
"backend/internal/platform/db"
|
|
)
|
|
|
|
// alwaysAvailableGate satisfies users.AccountsGate for the seed CLI, which
|
|
// only ever creates the initial admin account (never a customer), so the
|
|
// gate is never actually consulted.
|
|
type alwaysAvailableGate struct{}
|
|
|
|
func (alwaysAvailableGate) CustomerAccountsAvailable(context.Context) (bool, error) {
|
|
return true, nil
|
|
}
|
|
|
|
func main() {
|
|
cfg, err := config.Load()
|
|
if err != nil {
|
|
log.Fatalf("load config: %v", err)
|
|
}
|
|
|
|
if cfg.Seed.AdminUsername == "" || cfg.Seed.AdminPassword == "" {
|
|
log.Fatal("SEED_ADMIN_USERNAME and SEED_ADMIN_PASSWORD must be set")
|
|
}
|
|
if len(cfg.Seed.AdminPassword) < 12 {
|
|
log.Fatal("SEED_ADMIN_PASSWORD must be at least 12 characters")
|
|
}
|
|
|
|
database, err := db.Connect(cfg.Database.URL, false)
|
|
if err != nil {
|
|
log.Fatalf("connect database: %v", err)
|
|
}
|
|
|
|
repo := users.NewRepository(database)
|
|
service := users.NewService(repo, alwaysAvailableGate{}, cfg.Seed)
|
|
|
|
ctx := context.Background()
|
|
|
|
if existing, err := repo.FindByUsername(ctx, cfg.Seed.AdminUsername); err == nil && existing != nil {
|
|
log.Fatalf("an account with username %q already exists (id=%s)", cfg.Seed.AdminUsername, existing.ID)
|
|
} else if err != nil && !errors.Is(err, users.ErrNotFound) {
|
|
log.Fatalf("check existing admin: %v", err)
|
|
}
|
|
|
|
admin, err := service.Create(ctx, cfg.Seed.AdminUsername, cfg.Seed.AdminPassword, users.RoleAdmin)
|
|
if err != nil {
|
|
log.Fatalf("create admin: %v", err)
|
|
}
|
|
|
|
log.Printf("admin account created: username=%s id=%s", admin.Username, admin.ID)
|
|
}
|