-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsuper_users_init.go
More file actions
82 lines (70 loc) · 2.33 KB
/
super_users_init.go
File metadata and controls
82 lines (70 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import (
"context"
"errors"
"github.com/dtg-lucifer/everato/config"
"github.com/dtg-lucifer/everato/internal/db/repository"
"github.com/dtg-lucifer/everato/internal/utils"
"github.com/dtg-lucifer/everato/pkg"
"github.com/jackc/pgx/v5"
)
func SuperUserInit(cfg *config.Config) error {
// Initialize the super user with the provided configuration
// This function should create a super user if it doesn't exist
// and set up necessary permissions or roles
logger := pkg.NewLogger()
// Establish connection to the PostgreSQL database using connection string from environment
conn, err := pgx.Connect(
context.Background(),
utils.GetEnv("DB_URL", "postgres://piush:root_access@localhost:5432/everato?ssl_mode=disable"),
)
if err != nil {
logger.StdoutLogger.Error("Error connecting to the postgres db", "err", err.Error())
return err
}
// Initialize the repository with the database connection
repo := repository.New(conn)
tx, err := conn.Begin(context.Background())
if err != nil {
logger.StdoutLogger.Error("Error starting transaction", "err", err.Error())
return err
}
for _, su := range cfg.SuperUsers {
// hash the password before saving into db
hashedPassword, err := utils.BcryptHash(su.Password)
if err != nil {
logger.StdoutLogger.Error("Error hashing password", "err", err.Error(), "email", su.Email)
return tx.Rollback(context.Background())
}
u, err := repo.WithTx(tx).CreateSuperUserIfNotExists(
context.Background(),
repository.CreateSuperUserIfNotExistsParams{
Column1: su.UserName,
Column2: su.Name,
Column3: su.Email,
Column4: hashedPassword,
},
)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
logger.StdoutLogger.Info("Super user already exists", "email", su.Email)
continue // Not a fatal error, just skip
}
logger.StdoutLogger.Error("Error creating super user", "err", err.Error(), "email", su.Email)
tx.Rollback(context.Background())
return err
}
logger.StdoutLogger.Info(
"Adding user with following details",
"username", u.Username,
"email", u.Email,
"role", u.Role, // This will be a string
"permissions", u.Permissions, // Show as a raw object
)
}
if err := tx.Commit(context.Background()); err != nil {
logger.StdoutLogger.Error("Error committing transaction", "err", err.Error())
return err
}
return nil
}