Download this file
| 1 | package store |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "strings" |
| 7 | "time" |
| 8 | |
| 9 | "amadan.net/rastrillo/rastrillo/assertion" |
| 10 | ) |
| 11 | |
| 12 | // Bootstrap makes ownerEmail (BASE_OWNER) an owner: it adds the address as |
| 13 | // an owner when no member has it, and promotes the member who has it. It |
| 14 | // never demotes or removes anyone, so changing BASE_OWNER adds an owner and |
| 15 | // leaves the previous one in place. Both statements are idempotent, so two |
| 16 | // Bases booting together end in the same state. |
| 17 | func Bootstrap(ctx context.Context, db *sql.DB, ownerEmail string) error { |
| 18 | email := strings.ToLower(strings.TrimSpace(ownerEmail)) |
| 19 | id, err := assertion.RandomID() |
| 20 | if err != nil { |
| 21 | return err |
| 22 | } |
| 23 | if _, err := db.ExecContext(ctx, |
| 24 | `INSERT INTO members (id, email, role, invited_at) |
| 25 | SELECT ?, ?, 'owner', ? WHERE NOT EXISTS (SELECT 1 FROM members WHERE email = ?)`, |
| 26 | id, email, time.Now().UTC(), email); err != nil { |
| 27 | return err |
| 28 | } |
| 29 | _, err = db.ExecContext(ctx, `UPDATE members SET role = 'owner' WHERE email = ? AND role <> 'owner'`, email) |
| 30 | return err |
| 31 | } |
| 32 | |