Initial backend import
This commit is contained in:
29
internal/seed/seed.go
Normal file
29
internal/seed/seed.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package seed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func EnsureAdmin(ctx context.Context, pool *pgxpool.Pool, email, password string) error {
|
||||
var n int
|
||||
if err := pool.QueryRow(ctx, `SELECT COUNT(*) FROM admins`).Scan(&n); err != nil {
|
||||
return err
|
||||
}
|
||||
if n > 0 {
|
||||
return nil
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = pool.Exec(ctx, `INSERT INTO admins (email, password_hash) VALUES ($1, $2)`, email, string(hash))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Printf("seeded admin user %s", email)
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user