-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
276 lines (227 loc) · 7.79 KB
/
main.go
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
package main
import (
"fmt"
"github.com/google/uuid"
consulServiceManager "github.com/kontesthq/go-consul-service-manager/consulservicemanager"
"kontest-authentication/database"
"kontest-authentication/model"
"kontest-authentication/routes"
"kontest-authentication/service"
"kontest-authentication/utils/kafka_utils"
"kontest-authentication/utils/spicedb_utils"
"log"
"log/slog"
"net/http"
"os"
"strconv"
"time"
)
var (
applicationHost = "localhost" // Default value for local development
applicationPort = 5155 // Default value for local development
serviceName = "KONTEST-AUTHENTICATION-SERVICE" // Service name for Service Registry
consulHost = "localhost" // Default value for local development
consulPort = 5150
// DB properties
dbHost = "localhost"
dbPort = "5432"
dbName = "kontest"
dbUser = "ayushsinghal"
dbPassword = ""
isSSLModeEnabled = false
)
func initializeVariables() {
// Get the hostname of the machine
hostname, err := os.Hostname()
if err != nil {
log.Fatalf("Error fetching hostname: %v", err)
}
// Attempt to read the KONTEST_API_SERVER_HOST environment variable
if host := os.Getenv("KONTEST_AUTHENTICATION_SERVICE_HOST"); host != "" {
applicationHost = host // Override with the environment variable if set
} else {
applicationHost = hostname // Use the machine's hostname if the env var is not set
}
// Attempt to read the KONTEST_API_SERVER_PORT environment variable
if port := os.Getenv("KONTEST_AUTHENTICATION_SERVICE_PORT"); port != "" {
parsedPort, err := strconv.Atoi(port)
if err != nil {
log.Fatalf("Invalid port value: %v", err)
}
applicationPort = parsedPort // Override with the environment variable if set
}
// Attempt to read the CONSUL_ADDRESS environment variable
if host := os.Getenv("CONSUL_HOST"); host != "" {
consulHost = host // Override with the environment variable if set
}
// Attempt to read the CONSUL_PORT environment variable
if port := os.Getenv("CONSUL_PORT"); port != "" {
if portInt, err := strconv.Atoi(port); err == nil {
consulPort = portInt // Override with the environment variable if set and valid
}
}
// Attempt to read the DB_HOST environment variable
if host := os.Getenv("DB_HOST"); host != "" {
dbHost = host // Override with the environment variable if set
}
// Attempt to read the DB_PORT environment variable
if port := os.Getenv("DB_PORT"); port != "" {
dbPort = port // Override with the environment variable if set
}
// Attempt to read the DB_NAME environment variable
if name := os.Getenv("DB_NAME"); name != "" {
dbName = name // Override with the environment variable if set
}
// Attempt to read the DB_USER environment variable
if user := os.Getenv("DB_USER"); user != "" {
dbUser = user // Override with the environment variable if set
}
// Attempt to read the DB_PASSWORD environment variable
if password := os.Getenv("DB_PASSWORD"); password != "" {
dbPassword = password // Override with the environment variable if set
}
// Attempt to read the DB_SSL_MODE environment variable
if sslMode := os.Getenv("DB_SSL_MODE"); sslMode != "" {
isSSLModeEnabled = sslMode == "enable"
}
}
func main() {
initializeVariables()
kafkaConfig := kafka_utils.GetKafkaConfig()
kafkaBroker := kafkaConfig.KafkaHost + ":" + kafkaConfig.KafkaPort
service.InitKafka(kafkaBroker)
consulService := consulServiceManager.NewConsulService(consulHost, consulPort)
consulService.Start(applicationHost, applicationPort, serviceName, []string{})
// Initialize the database connection
database.InitializeDatabase(dbName, dbPort, dbHost, dbUser, dbPassword, map[bool]string{true: "enable", false: "disable"}[isSSLModeEnabled])
database.SetupDatabase()
defer database.CloseDB()
DoStartupTasks()
router := http.NewServeMux()
routes.RegisterRoutes(router)
server := http.Server{
Addr: ":" + strconv.Itoa(applicationPort),
Handler: router,
}
fmt.Println("Server listening at applicationPort: " + strconv.Itoa(applicationPort))
err := server.ListenAndServe()
if err != nil {
fmt.Println(err)
return
}
}
func DoStartupTasks() {
// Make users admin
MakeUsersAdmin()
}
func MakeUsersAdmin() {
tx, err := database.GetDB().Beginx()
if err != nil {
slog.Error(fmt.Sprintf("Failed to begin transaction: %v", err))
os.Exit(1)
}
defer func() {
if err != nil {
err := tx.Rollback()
if err != nil {
slog.Warn("Cannot rollback transaction")
return
} // Rollback if there was an error
} else {
if commitErr := tx.Commit(); commitErr != nil {
slog.Error(fmt.Sprintf("Failed to commit transaction: %v", commitErr))
os.Exit(1)
}
}
}()
emailsOfUsersToMakeAdmin := []string{"[email protected]"}
for _, email := range emailsOfUsersToMakeAdmin {
user, err := database.FindUserByEmail(email)
if err != nil {
slog.Error(fmt.Sprintf("Error finding user with email %s: %v\n", email, err))
continue
}
// Assign the admin role to the user in DB
_, err = database.AssignRoleToUser(user.ID, model.GetRoleAdmin().ID, tx)
if err != nil {
slog.Error(fmt.Sprintf("Error assigning admin role to user with email %s: %v\n", email, err))
}
// Assign the admin role to the user in spiceDB
spicedb_utils.MakeUserAdmin(user.ID.String())
}
}
func doDatabaseTest() {
tx, err := database.GetDB().Beginx()
if err != nil {
log.Fatalf("Failed to begin transaction: %v", err)
}
defer func() {
if err != nil {
err := tx.Rollback()
if err != nil {
log.Println("Cannot rollback transaction")
return
} // Rollback if there was an error
} else {
if commitErr := tx.Commit(); commitErr != nil {
log.Fatalf("Failed to commit transaction: %v", commitErr)
}
}
}()
// Inserting sample users into the database
users := []model.User{
{ID: uuid.New(), Email: "[email protected]", Password: "hashed_password"},
{ID: uuid.New(), Email: "[email protected]", Password: "hashed_password"},
}
// Use the db variable to create multiple users
for _, user := range users {
refreshToken := model.RefreshToken{
TokenID: uuid.New(),
RefreshToken: "sample_refresh_token", // generate or pass a token here
Expiry: time.Now().Add(24 * time.Hour), // set your expiration time
UserID: user.ID,
}
// Insert users
_, err := database.InsertUserIntoDB(user, tx)
if err != nil {
log.Printf("Error adding user %s: %v\n", user.Email, err)
continue
}
// Insert refresh token
_, err = database.InsertRefreshTokenIntoDB(refreshToken, tx)
// Add a device for the refresh token
device := model.Device{
RefreshTokenID: refreshToken.TokenID,
}
_, err = database.InsertDeviceIntoDB(device, tx)
}
log.Println("Users added successfully")
// Inserting sample roles into the database
roles := []model.Role{
{ID: 1, Name: "user"},
{ID: 2, Name: "admin"},
}
// Use the db variable to create multiple roles
for _, role := range roles {
if _, err := database.InsertRoleIntoDB(role, tx); err != nil {
log.Printf("Error adding role %s: %v\n", role.Name, err)
}
}
log.Println("Roles added successfully")
// Inserting role assignments (assign roles to users) into the user_roles table
userRoles := []struct {
UserID uuid.UUID `db:"user_id"`
RoleID int `db:"role_id"`
}{
{UserID: users[0].ID, RoleID: 1}, // Assign "user" role to first user
{UserID: users[0].ID, RoleID: 2}, // Assign "admin" role to first user
{UserID: users[1].ID, RoleID: 1}, // Assign "user" role to second user
}
// Insert user roles
for _, userRole := range userRoles {
if _, err := database.AssignRoleToUser(userRole.UserID, userRole.RoleID, tx); err != nil {
log.Printf("Error assigning role ID %d to user ID %s: %v\n", userRole.RoleID, userRole.UserID, err)
}
}
log.Println("User roles added successfully")
}