UPDATE: Add super admin

This commit is contained in:
2026-03-30 23:48:37 +07:00
parent 44d0d0c973
commit 62d4b889d1
18 changed files with 1061 additions and 16 deletions

View File

@@ -3,12 +3,14 @@ package database
import (
"context"
"history-api/pkg/config"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
func NewPostgresqlDB() (*pgxpool.Pool, error) {
ctx := context.Background()
connectionURI, err := config.GetConfig("PGX_CONNECTION_URI")
if err != nil {
return nil, err
@@ -19,14 +21,21 @@ func NewPostgresqlDB() (*pgxpool.Pool, error) {
return nil, err
}
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
if err != nil {
return nil, err
var pool *pgxpool.Pool
for i := 0; i < 5; i++ {
pool, err = pgxpool.NewWithConfig(ctx, poolConfig)
if err != nil {
time.Sleep(2 * time.Second)
continue
}
if err = pool.Ping(ctx); err == nil {
return pool, nil
}
time.Sleep(2 * time.Second)
}
if err := pool.Ping(ctx); err != nil {
return nil, err
}
return pool, nil
}
return nil, err
}

75
pkg/database/seed.go Normal file
View File

@@ -0,0 +1,75 @@
package database
import (
"context"
"database/sql"
"errors"
"history-api/internal/gen/sqlc"
"history-api/pkg/config"
"history-api/pkg/constants"
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
"golang.org/x/crypto/bcrypt"
)
func SeedSuperAdmin(pool *pgxpool.Pool) error {
ctx := context.Background()
displayName, err := config.GetConfig("ADMIN_DISPLAY_NAME")
if err != nil {
return err
}
email, err := config.GetConfig("ADMIN_EMAIL")
if err != nil {
return err
}
password, err := config.GetConfig("ADMIN_PASSWORD")
if err != nil {
return err
}
q := sqlc.New(pool)
_, err = q.GetUserByEmail(ctx, email)
if err == nil {
return nil
}
if !errors.Is(err, sql.ErrNoRows) {
return err
}
hashed, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return err
}
user, err := q.UpsertUser(ctx, sqlc.UpsertUserParams{
Email: email,
PasswordHash: pgtype.Text{
String: string(hashed),
Valid: len(hashed) != 0,
},
AuthProvider: constants.LocalProvider.String(),
})
if err != nil {
return err
}
_, err = q.CreateUserProfile(ctx, sqlc.CreateUserProfileParams{
UserID: user.ID,
DisplayName: pgtype.Text{
String: displayName,
Valid: displayName != "",
},
})
if err != nil {
return err
}
return nil
}