first
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
// 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"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
log.Fatalf("load config: %v", err)
|
||||
}
|
||||
|
||||
if cfg.Seed.AdminEmail == "" || cfg.Seed.AdminPassword == "" {
|
||||
log.Fatal("SEED_ADMIN_EMAIL 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)
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
if existing, err := repo.FindByEmail(ctx, cfg.Seed.AdminEmail); err == nil && existing != nil {
|
||||
log.Fatalf("an account with email %q already exists (id=%s)", cfg.Seed.AdminEmail, 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.AdminEmail, cfg.Seed.AdminPassword, users.RoleAdmin)
|
||||
if err != nil {
|
||||
log.Fatalf("create admin: %v", err)
|
||||
}
|
||||
|
||||
log.Printf("admin account created: email=%s id=%s", admin.Email, admin.ID)
|
||||
}
|
||||
Reference in New Issue
Block a user