forked from heroiclabs/nakama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore_account.go
534 lines (476 loc) · 19.8 KB
/
core_account.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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
// Copyright 2018 The Nakama Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package server
import (
"context"
"database/sql"
"encoding/json"
"errors"
"strconv"
"strings"
"time"
"github.com/gofrs/uuid"
"github.com/heroiclabs/nakama-common/api"
"github.com/heroiclabs/nakama/v3/console"
"github.com/jackc/pgconn"
"github.com/jackc/pgtype"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
"google.golang.org/protobuf/types/known/wrapperspb"
)
var ErrAccountNotFound = errors.New("account not found")
// Not an API entity, only used to receive data from runtime environment.
type accountUpdate struct {
userID uuid.UUID
username string
displayName *wrapperspb.StringValue
timezone *wrapperspb.StringValue
location *wrapperspb.StringValue
langTag *wrapperspb.StringValue
avatarURL *wrapperspb.StringValue
metadata *wrapperspb.StringValue
}
func GetAccount(ctx context.Context, logger *zap.Logger, db *sql.DB, statusRegistry *StatusRegistry, userID uuid.UUID) (*api.Account, error) {
var displayName sql.NullString
var username sql.NullString
var avatarURL sql.NullString
var langTag sql.NullString
var location sql.NullString
var timezone sql.NullString
var metadata sql.NullString
var wallet sql.NullString
var email sql.NullString
var apple sql.NullString
var facebook sql.NullString
var facebookInstantGame sql.NullString
var google sql.NullString
var gamecenter sql.NullString
var steam sql.NullString
var customID sql.NullString
var edgeCount int
var createTime pgtype.Timestamptz
var updateTime pgtype.Timestamptz
var verifyTime pgtype.Timestamptz
var disableTime pgtype.Timestamptz
var deviceIDs pgtype.VarcharArray
query := `
SELECT u.username, u.display_name, u.avatar_url, u.lang_tag, u.location, u.timezone, u.metadata, u.wallet,
u.email, u.apple_id, u.facebook_id, u.facebook_instant_game_id, u.google_id, u.gamecenter_id, u.steam_id, u.custom_id, u.edge_count,
u.create_time, u.update_time, u.verify_time, u.disable_time, array(select ud.id from user_device ud where u.id = ud.user_id)
FROM users u
WHERE u.id = $1`
if err := db.QueryRowContext(ctx, query, userID).Scan(&username, &displayName, &avatarURL, &langTag, &location, &timezone, &metadata, &wallet, &email, &apple, &facebook, &facebookInstantGame, &google, &gamecenter, &steam, &customID, &edgeCount, &createTime, &updateTime, &verifyTime, &disableTime, &deviceIDs); err != nil {
if err == sql.ErrNoRows {
return nil, ErrAccountNotFound
}
logger.Error("Error retrieving user account.", zap.Error(err))
return nil, err
}
devices := make([]*api.AccountDevice, 0, len(deviceIDs.Elements))
for _, deviceID := range deviceIDs.Elements {
devices = append(devices, &api.AccountDevice{Id: deviceID.String})
}
var verifyTimestamp *timestamppb.Timestamp
if verifyTime.Status == pgtype.Present && verifyTime.Time.Unix() != 0 {
verifyTimestamp = ×tamppb.Timestamp{Seconds: verifyTime.Time.Unix()}
}
var disableTimestamp *timestamppb.Timestamp
if disableTime.Status == pgtype.Present && disableTime.Time.Unix() != 0 {
disableTimestamp = ×tamppb.Timestamp{Seconds: disableTime.Time.Unix()}
}
online := false
if statusRegistry != nil {
online = statusRegistry.IsOnline(userID)
}
return &api.Account{
User: &api.User{
Id: userID.String(),
Username: username.String,
DisplayName: displayName.String,
AvatarUrl: avatarURL.String,
LangTag: langTag.String,
Location: location.String,
Timezone: timezone.String,
Metadata: metadata.String,
AppleId: apple.String,
FacebookId: facebook.String,
FacebookInstantGameId: facebookInstantGame.String,
GoogleId: google.String,
GamecenterId: gamecenter.String,
SteamId: steam.String,
EdgeCount: int32(edgeCount),
CreateTime: ×tamppb.Timestamp{Seconds: createTime.Time.Unix()},
UpdateTime: ×tamppb.Timestamp{Seconds: updateTime.Time.Unix()},
Online: online,
},
Wallet: wallet.String,
Email: email.String,
Devices: devices,
CustomId: customID.String,
VerifyTime: verifyTimestamp,
DisableTime: disableTimestamp,
}, nil
}
func GetAccounts(ctx context.Context, logger *zap.Logger, db *sql.DB, statusRegistry *StatusRegistry, userIDs []string) ([]*api.Account, error) {
statements := make([]string, 0, len(userIDs))
parameters := make([]interface{}, 0, len(userIDs))
for _, userID := range userIDs {
parameters = append(parameters, userID)
statements = append(statements, "$"+strconv.Itoa(len(parameters)))
}
query := `
SELECT u.id, u.username, u.display_name, u.avatar_url, u.lang_tag, u.location, u.timezone, u.metadata, u.wallet,
u.email, u.apple_id, u.facebook_id, u.facebook_instant_game_id, u.google_id, u.gamecenter_id, u.steam_id, u.custom_id, u.edge_count,
u.create_time, u.update_time, u.verify_time, u.disable_time, array(select ud.id from user_device ud where u.id = ud.user_id)
FROM users u
WHERE u.id IN (` + strings.Join(statements, ",") + `)`
rows, err := db.QueryContext(ctx, query, parameters...)
if err != nil {
logger.Error("Error retrieving user accounts.", zap.Error(err))
return nil, err
}
accounts := make([]*api.Account, 0, len(userIDs))
for rows.Next() {
var userID string
var username sql.NullString
var displayName sql.NullString
var avatarURL sql.NullString
var langTag sql.NullString
var location sql.NullString
var timezone sql.NullString
var metadata sql.NullString
var wallet sql.NullString
var email sql.NullString
var apple sql.NullString
var facebook sql.NullString
var facebookInstantGame sql.NullString
var google sql.NullString
var gamecenter sql.NullString
var steam sql.NullString
var customID sql.NullString
var edgeCount int
var createTime pgtype.Timestamptz
var updateTime pgtype.Timestamptz
var verifyTime pgtype.Timestamptz
var disableTime pgtype.Timestamptz
var deviceIDs pgtype.VarcharArray
err = rows.Scan(&userID, &username, &displayName, &avatarURL, &langTag, &location, &timezone, &metadata, &wallet, &email, &apple, &facebook, &facebookInstantGame, &google, &gamecenter, &steam, &customID, &edgeCount, &createTime, &updateTime, &verifyTime, &disableTime, &deviceIDs)
if err != nil {
_ = rows.Close()
logger.Error("Error retrieving user accounts.", zap.Error(err))
return nil, err
}
devices := make([]*api.AccountDevice, 0, len(deviceIDs.Elements))
for _, deviceID := range deviceIDs.Elements {
devices = append(devices, &api.AccountDevice{Id: deviceID.String})
}
var verifyTimestamp *timestamppb.Timestamp
if verifyTime.Status == pgtype.Present && verifyTime.Time.Unix() != 0 {
verifyTimestamp = ×tamppb.Timestamp{Seconds: verifyTime.Time.Unix()}
}
var disableTimestamp *timestamppb.Timestamp
if disableTime.Status == pgtype.Present && disableTime.Time.Unix() != 0 {
disableTimestamp = ×tamppb.Timestamp{Seconds: disableTime.Time.Unix()}
}
accounts = append(accounts, &api.Account{
User: &api.User{
Id: userID,
Username: username.String,
DisplayName: displayName.String,
AvatarUrl: avatarURL.String,
LangTag: langTag.String,
Location: location.String,
Timezone: timezone.String,
Metadata: metadata.String,
AppleId: apple.String,
FacebookId: facebook.String,
FacebookInstantGameId: facebookInstantGame.String,
GoogleId: google.String,
GamecenterId: gamecenter.String,
SteamId: steam.String,
EdgeCount: int32(edgeCount),
CreateTime: ×tamppb.Timestamp{Seconds: createTime.Time.Unix()},
UpdateTime: ×tamppb.Timestamp{Seconds: updateTime.Time.Unix()},
// Online filled below.
},
Wallet: wallet.String,
Email: email.String,
Devices: devices,
CustomId: customID.String,
VerifyTime: verifyTimestamp,
DisableTime: disableTimestamp,
})
}
_ = rows.Close()
if statusRegistry != nil {
statusRegistry.FillOnlineAccounts(accounts)
}
return accounts, nil
}
func UpdateAccounts(ctx context.Context, logger *zap.Logger, db *sql.DB, updates []*accountUpdate) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
logger.Error("Could not begin database transaction.", zap.Error(err))
return err
}
if err = ExecuteInTx(ctx, tx, func() error {
updateErr := updateAccounts(ctx, logger, tx, updates)
if updateErr != nil {
return updateErr
}
return nil
}); err != nil {
if e, ok := err.(*statusError); ok {
return e.Cause()
}
logger.Error("Error updating user accounts.", zap.Error(err))
return err
}
return nil
}
func updateAccounts(ctx context.Context, logger *zap.Logger, tx *sql.Tx, updates []*accountUpdate) error {
for _, update := range updates {
updateStatements := make([]string, 0, 7)
distinctStatements := make([]string, 0, 7)
params := make([]interface{}, 0, 8)
// Ensure user ID is always present.
params = append(params, update.userID)
if update.username != "" {
if invalidUsernameRegex.MatchString(update.username) {
return errors.New("Username invalid, no spaces or control characters allowed.")
}
params = append(params, update.username)
updateStatements = append(updateStatements, "username = $"+strconv.Itoa(len(params)))
distinctStatements = append(distinctStatements, "username IS DISTINCT FROM $"+strconv.Itoa(len(params)))
}
if update.displayName != nil {
if d := update.displayName.GetValue(); d == "" {
updateStatements = append(updateStatements, "display_name = NULL")
distinctStatements = append(distinctStatements, "display_name IS NOT NULL")
} else {
params = append(params, d)
updateStatements = append(updateStatements, "display_name = $"+strconv.Itoa(len(params)))
distinctStatements = append(distinctStatements, "display_name IS DISTINCT FROM $"+strconv.Itoa(len(params)))
}
}
if update.timezone != nil {
if t := update.timezone.GetValue(); t == "" {
updateStatements = append(updateStatements, "timezone = NULL")
distinctStatements = append(distinctStatements, "timezone IS NOT NULL")
} else {
params = append(params, t)
updateStatements = append(updateStatements, "timezone = $"+strconv.Itoa(len(params)))
distinctStatements = append(distinctStatements, "timezone IS DISTINCT FROM $"+strconv.Itoa(len(params)))
}
}
if update.location != nil {
if l := update.location.GetValue(); l == "" {
updateStatements = append(updateStatements, "location = NULL")
distinctStatements = append(distinctStatements, "location IS NOT NULL")
} else {
params = append(params, l)
updateStatements = append(updateStatements, "location = $"+strconv.Itoa(len(params)))
distinctStatements = append(distinctStatements, "location IS DISTINCT FROM $"+strconv.Itoa(len(params)))
}
}
if update.langTag != nil {
if l := update.langTag.GetValue(); l == "" {
updateStatements = append(updateStatements, "lang_tag = NULL")
distinctStatements = append(distinctStatements, "lang_tag IS NOT NULL")
} else {
params = append(params, l)
updateStatements = append(updateStatements, "lang_tag = $"+strconv.Itoa(len(params)))
distinctStatements = append(distinctStatements, "lang_tag IS DISTINCT FROM $"+strconv.Itoa(len(params)))
}
}
if update.avatarURL != nil {
if a := update.avatarURL.GetValue(); a == "" {
updateStatements = append(updateStatements, "avatar_url = NULL")
distinctStatements = append(distinctStatements, "avatar_url IS NOT NULL")
} else {
params = append(params, a)
updateStatements = append(updateStatements, "avatar_url = $"+strconv.Itoa(len(params)))
distinctStatements = append(distinctStatements, "avatar_url IS DISTINCT FROM $"+strconv.Itoa(len(params)))
}
}
if update.metadata != nil {
params = append(params, update.metadata.GetValue())
updateStatements = append(updateStatements, "metadata = $"+strconv.Itoa(len(params)))
distinctStatements = append(distinctStatements, "metadata IS DISTINCT FROM $"+strconv.Itoa(len(params)))
}
if len(updateStatements) == 0 {
return errors.New("No fields to update.")
}
query := "UPDATE users SET update_time = now(), " + strings.Join(updateStatements, ", ") +
" WHERE id = $1 AND (" + strings.Join(distinctStatements, " OR ") + ")"
if _, err := tx.ExecContext(ctx, query, params...); err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == dbErrorUniqueViolation && strings.Contains(pgErr.Message, "users_username_key") {
return errors.New("Username is already in use.")
}
logger.Error("Could not update user account.", zap.Error(err),
zap.String("username", update.username),
zap.Any("display_name", update.displayName),
zap.Any("timezone", update.timezone),
zap.Any("location", update.location),
zap.Any("lang_tag", update.langTag),
zap.Any("avatar_url", update.avatarURL))
return err
}
}
return nil
}
func ExportAccount(ctx context.Context, logger *zap.Logger, db *sql.DB, userID uuid.UUID) (*console.AccountExport, error) {
// Core user account.
account, err := GetAccount(ctx, logger, db, nil, userID)
if err != nil {
if err == ErrAccountNotFound {
return nil, status.Error(codes.NotFound, "Account not found.")
}
logger.Error("Could not export account data", zap.Error(err), zap.String("user_id", userID.String()))
return nil, status.Error(codes.Internal, "An error occurred while trying to export user data.")
}
// Friends.
friends, err := GetFriendIDs(ctx, logger, db, userID)
if err != nil {
logger.Error("Could not fetch friend IDs", zap.Error(err), zap.String("user_id", userID.String()))
return nil, status.Error(codes.Internal, "An error occurred while trying to export user data.")
}
// Messages.
messages, err := GetChannelMessages(ctx, logger, db, userID)
if err != nil {
logger.Error("Could not fetch messages", zap.Error(err), zap.String("user_id", userID.String()))
return nil, status.Error(codes.Internal, "An error occurred while trying to export user data.")
}
// Leaderboard records.
leaderboardRecords, err := LeaderboardRecordReadAll(ctx, logger, db, userID)
if err != nil {
logger.Error("Could not fetch leaderboard records", zap.Error(err), zap.String("user_id", userID.String()))
return nil, status.Error(codes.Internal, "An error occurred while trying to export user data.")
}
groups := make([]*api.Group, 0, 1)
groupUsers, err := ListUserGroups(ctx, logger, db, userID, 0, nil, "")
if err != nil {
logger.Error("Could not fetch groups that belong to the user", zap.Error(err), zap.String("user_id", userID.String()))
return nil, status.Error(codes.Internal, "An error occurred while trying to export user data.")
}
for _, g := range groupUsers.UserGroups {
groups = append(groups, g.Group)
}
// Notifications.
notifications, err := NotificationList(ctx, logger, db, userID, 0, "", nil)
if err != nil {
logger.Error("Could not fetch notifications", zap.Error(err), zap.String("user_id", userID.String()))
return nil, status.Error(codes.Internal, "An error occurred while trying to export user data.")
}
// Storage objects where user is the owner.
storageObjects, err := StorageReadAllUserObjects(ctx, logger, db, userID)
if err != nil {
logger.Error("Could not fetch notifications", zap.Error(err), zap.String("user_id", userID.String()))
return nil, status.Error(codes.Internal, "An error occurred while trying to export user data.")
}
// History of user's wallet.
walletLedgers, _, _, err := ListWalletLedger(ctx, logger, db, userID, nil, "")
if err != nil {
logger.Error("Could not fetch wallet ledger items", zap.Error(err), zap.String("user_id", userID.String()))
return nil, status.Error(codes.Internal, "An error occurred while trying to export user data.")
}
wl := make([]*console.WalletLedger, len(walletLedgers))
for i, w := range walletLedgers {
changeset, err := json.Marshal(w.Changeset)
if err != nil {
logger.Error("Could not fetch wallet ledger items, error encoding changeset", zap.Error(err), zap.String("user_id", userID.String()))
return nil, status.Error(codes.Internal, "An error occurred while trying to export user data.")
}
metadata, err := json.Marshal(w.Metadata)
if err != nil {
logger.Error("Could not fetch wallet ledger items, error encoding metadata", zap.Error(err), zap.String("user_id", userID.String()))
return nil, status.Error(codes.Internal, "An error occurred while trying to export user data.")
}
wl[i] = &console.WalletLedger{
Id: w.ID,
UserId: w.UserID,
Changeset: string(changeset),
Metadata: string(metadata),
CreateTime: ×tamppb.Timestamp{Seconds: w.CreateTime},
UpdateTime: ×tamppb.Timestamp{Seconds: w.UpdateTime},
}
}
export := &console.AccountExport{
Account: account,
Objects: storageObjects,
Friends: friends.GetFriends(),
Messages: messages,
Groups: groups,
LeaderboardRecords: leaderboardRecords,
Notifications: notifications.GetNotifications(),
WalletLedgers: wl,
}
return export, nil
}
func DeleteAccount(ctx context.Context, logger *zap.Logger, db *sql.DB, config Config, leaderboardRankCache LeaderboardRankCache, sessionRegistry SessionRegistry, sessionCache SessionCache, tracker Tracker, userID uuid.UUID, recorded bool) error {
ts := time.Now().UTC().Unix()
tx, err := db.BeginTx(ctx, nil)
if err != nil {
logger.Error("Could not begin database transaction.", zap.Error(err))
return err
}
var deleted bool
if err := ExecuteInTx(ctx, tx, func() error {
count, err := DeleteUser(ctx, tx, userID)
if err != nil {
logger.Debug("Could not delete user", zap.Error(err), zap.String("user_id", userID.String()))
return err
} else if count == 0 {
logger.Info("No user was found to delete. Skipping blacklist.", zap.String("user_id", userID.String()))
return nil
}
err = LeaderboardRecordsDeleteAll(ctx, logger, leaderboardRankCache, tx, userID, ts)
if err != nil {
logger.Debug("Could not delete leaderboard records.", zap.Error(err), zap.String("user_id", userID.String()))
return err
}
err = GroupDeleteAll(ctx, logger, tx, userID)
if err != nil {
logger.Debug("Could not delete groups and relationships.", zap.Error(err), zap.String("user_id", userID.String()))
return err
}
if recorded {
_, err = tx.ExecContext(ctx, `INSERT INTO user_tombstone (user_id) VALUES ($1) ON CONFLICT(user_id) DO NOTHING`, userID)
if err != nil {
logger.Debug("Could not insert user ID into tombstone", zap.Error(err), zap.String("user_id", userID.String()))
return err
}
}
deleted = true
return nil
}); err != nil {
logger.Error("Error occurred while trying to delete the user.", zap.Error(err), zap.String("user_id", userID.String()))
return err
}
if deleted {
// Logout and disconnect.
if err = SessionLogout(config, sessionCache, userID, "", ""); err != nil {
return err
}
for _, presence := range tracker.ListPresenceIDByStream(PresenceStream{Mode: StreamModeNotifications, Subject: userID}) {
if err = sessionRegistry.Disconnect(ctx, presence.SessionID, false); err != nil {
return err
}
}
}
return nil
}