63 lines
1.3 KiB
Go
63 lines
1.3 KiB
Go
package database
|
|
|
|
import (
|
|
"api/libs/logger"
|
|
"api/libs/postgres"
|
|
"api/models/users"
|
|
"context"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/alexedwards/argon2id"
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
func Init() {
|
|
|
|
ensureTableUsers()
|
|
ensureTableProducts()
|
|
|
|
usersRepository := users.New(postgres.Pool)
|
|
|
|
var ctx = context.Background()
|
|
|
|
hash, err := argon2id.CreateHash("admin", argon2id.DefaultParams)
|
|
if err != nil {
|
|
logger.Production.Error("error generate password hash")
|
|
}
|
|
|
|
_, err = usersRepository.GetUser(ctx, "admin")
|
|
if err != nil {
|
|
if err.Error() == pgx.ErrNoRows.Error() {
|
|
usersRepository.CreateUser(ctx, users.CreateUserParams{
|
|
User: uuid.New().String(),
|
|
CreatedAt: uint64(time.Now().Unix()),
|
|
Username: "admin",
|
|
Password: hash,
|
|
})
|
|
logger.Production.Info("Create user admin into database")
|
|
} else {
|
|
logger.Production.Error(err.Error())
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
func ensureTableUsers() {
|
|
if _, err := postgres.Pool.Exec(context.Background(), CreateUsersTableIfNotExists); err != nil {
|
|
logger.Production.Error(err.Error())
|
|
os.Exit(1)
|
|
}
|
|
logger.Production.Info("users exists")
|
|
}
|
|
|
|
func ensureTableProducts() {
|
|
if _, err := postgres.Pool.Exec(context.Background(), CreateProductsTableIfNotExists); err != nil {
|
|
logger.Production.Error(err.Error())
|
|
os.Exit(1)
|
|
}
|
|
logger.Production.Info("products exists")
|
|
}
|