Skip to content

Commit 8bf83ce

Browse files
committed
Add superuser by default
1 parent f46f58b commit 8bf83ce

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

compose.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ services:
1010
POSTGRES_AUTH_USER: user
1111
POSTGRES_AUTH_PASSWORD: password
1212
POSTGRES_AUTH_DB: db
13+
SUPERUSER_USERNAME: superuser
14+
SUPERUSER_PASSWORD: password
1315
volumes:
1416
- .:/src/
1517
ports:

src/db/db.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@ var POSTGRES_AUTH_USER = os.Getenv("POSTGRES_AUTH_USER")
2929
var POSTGRES_AUTH_PASSWORD = os.Getenv("POSTGRES_AUTH_PASSWORD")
3030
var POSTGRES_AUTH_DB = os.Getenv("POSTGRES_AUTH_DB")
3131

32+
var SUPERUSER_USERNAME = os.Getenv("SUPERUSER_USERNAME")
33+
var SUPERUSER_PASSWORD = os.Getenv("SUPERUSER_PASSWORD")
34+
3235
func Init() error {
3336
once.Do(func() {
3437
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
@@ -65,6 +68,15 @@ func Init() error {
6568
initErr = fmt.Errorf("failed to apply database schema: %w", err)
6669
return
6770
}
71+
// Create Superuser if it doesn't exist
72+
superuser_query := `INSERT INTO users (username, name, surname, email, password, role)
73+
VALUES ($1, $2, $3, $4, $5, 'superuser') ON CONFLICT DO NOTHING`
74+
_, err = pool.Exec(ctx, superuser_query, SUPERUSER_USERNAME, "OpenPark", "Superuser", "superuser@openpark.com", SUPERUSER_PASSWORD)
75+
if err != nil {
76+
pool.Close()
77+
initErr = fmt.Errorf("failed to create superuser: %w", err)
78+
return
79+
}
6880

6981
instance = &DB{pool: pool}
7082
fmt.Println("Database connection pool created successfully")

src/db/postgres_schema_v1.sql

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
-- Users table
22
CREATE TABLE IF NOT EXISTS users (
33
user_id SERIAL PRIMARY KEY,
4-
username TEXT NOT NULL,
4+
username TEXT NOT NULL UNIQUE,
55
name TEXT NOT NULL,
66
surname TEXT NOT NULL,
77
email TEXT NOT NULL UNIQUE,

0 commit comments

Comments
 (0)