/
user_sql.go
380 lines (331 loc) · 9.94 KB
/
user_sql.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
package persistence
import (
"context"
"fmt"
"time"
"github.com/alwitt/goutils"
"github.com/apex/log"
"github.com/google/uuid"
"gorm.io/gorm"
)
// sqlUserEntry SQL table representing a user
type sqlUserEntry struct {
ID string `gorm:"primaryKey"`
Name string `gorm:"not null;uniqueIndex:username_index"`
APIToken string `gorm:"not null"`
ActiveSessionID *string `gorm:"default:null"`
ActiveSession *sqlChatSessionEntry `gorm:"constraint:OnDelete:SET NULL;foreignKey:ActiveSessionID"`
ChatSessions []sqlChatSessionEntry `gorm:"foreignKey:UserID"`
CreatedAt time.Time
UpdatedAt time.Time
}
// TableName hard code table name
func (sqlUserEntry) TableName() string {
return "users"
}
// String override String
func (t sqlUserEntry) String() string {
return fmt.Sprintf("(%s [%s])", t.Name, t.ID)
}
// sqlUserHandle wrapper object for working with the "users" table
type sqlUserHandle struct {
goutils.Component
driver *sqlUserPersistence
sqlUserEntry
}
/*
GetID query for user GetID
@param ctxt context.Context - query context
@return the user ID
*/
func (h *sqlUserHandle) GetID(ctxt context.Context) (string, error) {
return h.ID, nil
}
/*
GetName query for user name
@param ctxt context.Context - query context
@return the user name
*/
func (h *sqlUserHandle) GetName(ctxt context.Context) (string, error) {
return h.Name, nil
}
/*
SetName set user name
@param ctxt context.Context - query context
@param newName string - new user name
*/
func (h *sqlUserHandle) SetName(ctxt context.Context, newName string) error {
logtags := h.GetLogTagsForContext(ctxt)
return h.driver.db.Transaction(func(tx *gorm.DB) error {
tmp := tx.Model(&h.sqlUserEntry).Updates(&sqlUserEntry{Name: newName}).First(&h.sqlUserEntry)
if tmp.Error != nil {
log.
WithError(tmp.Error).
WithFields(logtags).
Errorf("Failed to update user '%s' name to '%s'", h.ID, newName)
return tmp.Error
}
return nil
})
}
/*
GetActiveSessionID fetch user's active session ID
@param ctxt context.Context - query context
@return active session ID
*/
func (h *sqlUserHandle) GetActiveSessionID(ctxt context.Context) (*string, error) {
return h.ActiveSessionID, nil
}
/*
SetActiveSessionID change user's active session ID
@param ctxt context.Context - query context
@param sessionID string - new session ID
*/
func (h *sqlUserHandle) SetActiveSessionID(ctxt context.Context, sessionID string) error {
logtags := h.GetLogTagsForContext(ctxt)
return h.driver.db.Transaction(func(tx *gorm.DB) error {
if tmp := tx.
Model(&h.sqlUserEntry).
Updates(&sqlUserEntry{ActiveSessionID: &sessionID}).
First(&h.sqlUserEntry); tmp.Error != nil {
log.
WithError(tmp.Error).
WithFields(logtags).
Errorf("Failed to update user '%s' active session to '%s'", h.ID, sessionID)
return tmp.Error
}
return nil
})
}
/*
ClearActiveSessionID clear user's active session ID
@param ctxt context.Context - query context
*/
func (h *sqlUserHandle) ClearActiveSessionID(ctxt context.Context) error {
logtags := h.GetLogTagsForContext(ctxt)
return h.driver.db.Transaction(func(tx *gorm.DB) error {
if tmp := tx.
Model(&h.sqlUserEntry).
Update("active_session_id", nil).
First(&h.sqlUserEntry); tmp.Error != nil {
log.
WithError(tmp.Error).
WithFields(logtags).
Errorf("Failed to clear user '%s' active session", h.ID)
return tmp.Error
}
return nil
})
}
/*
GetAPIToken get user API token
@param ctxt context.Context - query context
@return the user API token
*/
func (h *sqlUserHandle) GetAPIToken(ctxt context.Context) (string, error) {
return h.APIToken, nil
}
/*
Refresh helper function to sync the handler with what is stored in persistence
@param ctxt context.Context - query context
*/
func (h *sqlUserHandle) Refresh(ctxt context.Context) error {
logtags := h.GetLogTagsForContext(ctxt)
return h.driver.db.Transaction(func(tx *gorm.DB) error {
if tmp := tx.
Where(&sqlUserEntry{ID: h.ID}).
First(&h.sqlUserEntry); tmp.Error != nil {
log.
WithError(tmp.Error).
WithFields(logtags).
Errorf("Failed to refresh user '%s' info", h.ID)
return tmp.Error
}
return nil
})
}
/*
SetAPIToken set user API token
@param ctxt context.Context - query context
@param newToken string - new API token
*/
func (h *sqlUserHandle) SetAPIToken(ctxt context.Context, newToken string) error {
logtags := h.GetLogTagsForContext(ctxt)
return h.driver.db.Transaction(func(tx *gorm.DB) error {
tmp := tx.Model(&h.sqlUserEntry).Updates(&sqlUserEntry{APIToken: newToken}).First(&h.sqlUserEntry)
if tmp.Error != nil {
log.
WithError(tmp.Error).
WithFields(logtags).
Errorf("Failed to update user '%s' API token", h.ID)
return tmp.Error
}
return nil
})
}
/*
ChatSessionManager fetch chat session manager for a user
@param ctxt context.Context - query context
@return associated chat session manager
*/
func (h *sqlUserHandle) ChatSessionManager(ctxt context.Context) (ChatSessionManager, error) {
logtags := h.GetLogTagsForContext(ctxt)
logtags["table"] = "chat_sessions"
return &sqlChatPersistence{
Component: goutils.Component{
LogTags: logtags,
LogTagModifiers: []goutils.LogMetadataModifier{},
},
db: h.driver.db,
user: h,
}, nil
}
// ============================================================================================
// SQL User Manager implementation
// defineUserHandle helper function for defining new user handle object
func (c *sqlUserPersistence) defineUserHandle(ctxt context.Context, userEntry sqlUserEntry) sqlUserHandle {
logtags := c.GetLogTagsForContext(ctxt)
logtags["table"] = "users"
logtags["user"] = userEntry.String()
return sqlUserHandle{
Component: goutils.Component{
LogTags: logtags,
LogTagModifiers: []goutils.LogMetadataModifier{},
},
driver: c,
sqlUserEntry: userEntry,
}
}
/*
RecordNewUser record a new system user
@param ctxt context.Context - query context
@param userName string - user name
@return new user entry
*/
func (c *sqlUserPersistence) RecordNewUser(ctxt context.Context, userName string) (User, error) {
logtags := c.GetLogTagsForContext(ctxt)
var result sqlUserHandle
return &result, c.db.Transaction(func(tx *gorm.DB) error {
log.WithFields(logtags).Debugf("Defining new user entry for '%s'", userName)
// Define a new user entry
newEntry := sqlUserEntry{ID: uuid.New().String(), Name: userName, APIToken: ""}
if tmp := tx.Create(&newEntry); tmp.Error != nil {
log.
WithError(tmp.Error).
WithFields(logtags).
Errorf("Failed to define new entry for '%s'", userName)
return tmp.Error
}
log.WithFields(logtags).Debugf("Defined new user entry for '%s'", userName)
// Prepare wrapper object
result = c.defineUserHandle(ctxt, newEntry)
return nil
})
}
/*
ListUsers list all known users
@param ctxt context.Context - query context
@return list of known users
*/
func (c *sqlUserPersistence) ListUsers(ctxt context.Context) ([]User, error) {
logtags := c.GetLogTagsForContext(ctxt)
result := []User{}
return result, c.db.Transaction(func(tx *gorm.DB) error {
var dbEntries []sqlUserEntry
if tmp := tx.Find(&dbEntries); tmp.Error != nil {
log.
WithError(tmp.Error).
WithFields(logtags).
Error("Failed to list all users")
return tmp.Error
}
// Create the wrapper objects
for _, userEntry := range dbEntries {
handleObject := c.defineUserHandle(ctxt, userEntry)
result = append(result, &handleObject)
}
return nil
})
}
/*
GetUser fetch a user
@param ctxt context.Context - query context
@param userID string - user ID
@return user entry
*/
func (c *sqlUserPersistence) GetUser(ctxt context.Context, userID string) (User, error) {
logtags := c.GetLogTagsForContext(ctxt)
var result sqlUserHandle
return &result, c.db.Transaction(func(tx *gorm.DB) error {
var dbEntry sqlUserEntry
if tmp := tx.Where(&sqlUserEntry{ID: userID}).First(&dbEntry); tmp.Error != nil {
log.
WithError(tmp.Error).
WithFields(logtags).
Errorf("Unable to locate user '%s'", userID)
return tmp.Error
}
// Prepare wrapper object
result = c.defineUserHandle(ctxt, dbEntry)
return nil
})
}
/*
GetUser fetch a user by name
@param ctxt context.Context - query context
@param userName string - user name
@return user entry
*/
func (c *sqlUserPersistence) GetUserByName(ctxt context.Context, userName string) (User, error) {
logtags := c.GetLogTagsForContext(ctxt)
var result sqlUserHandle
return &result, c.db.Transaction(func(tx *gorm.DB) error {
var dbEntry sqlUserEntry
if tmp := tx.Where(&sqlUserEntry{Name: userName}).First(&dbEntry); tmp.Error != nil {
log.
WithError(tmp.Error).
WithFields(logtags).
Errorf("Unable to locate user named '%s'", userName)
return tmp.Error
}
// Prepare wrapper object
result = c.defineUserHandle(ctxt, dbEntry)
return nil
})
}
/*
DeleteUser delete a user
@param ctxt context.Context - query context
@param userID string - user ID
*/
func (c *sqlUserPersistence) DeleteUser(ctxt context.Context, userID string) error {
logtags := c.GetLogTagsForContext(ctxt)
// Get user
userEntry, err := c.GetUser(ctxt, userID)
if err != nil {
log.WithError(err).WithFields(logtags).Errorf("Unable to find user '%s'", userID)
return err
}
// Get chat manager
chatManager, err := userEntry.ChatSessionManager(ctxt)
if err != nil {
log.WithError(err).WithFields(logtags).Errorf("Unable to get user '%s' chat manager", userID)
return err
}
// Delete all associated chat sessions
if err := chatManager.DeleteAllSessions(ctxt); err != nil {
log.WithError(err).WithFields(logtags).Errorf("Unable to delete user '%s' chats", userID)
return err
}
// Delete user
return c.db.Transaction(func(tx *gorm.DB) error {
if tmp := tx.Where(&sqlUserEntry{ID: userID}).Delete(&sqlUserEntry{}); tmp.Error != nil {
log.
WithError(tmp.Error).
WithFields(logtags).
Errorf("Unable to delete user '%s'", userID)
return tmp.Error
}
return nil
})
}