-
Notifications
You must be signed in to change notification settings - Fork 18
/
user.go
783 lines (691 loc) · 21 KB
/
user.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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
package main
import (
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/google/uuid"
"gorm.io/gorm"
"image"
"image/color"
"image/png"
"io"
"log"
"lukechampine.com/blake3"
"net/http"
"net/url"
"time"
)
// Must be in a region of the skin that supports translucency
const SKIN_WINDOW_X_MIN = 40
const SKIN_WINDOW_X_MAX = 48
const SKIN_WINDOW_Y_MIN = 9
const SKIN_WINDOW_Y_MAX = 11
var InviteNotFoundError error = NewBadRequestUserError("Invite not found.")
var InviteMissingError error = NewBadRequestUserError("Registration requires an invite.")
func (app *App) CreateUser(
caller *User,
username string,
password string,
isAdmin bool,
isLocked bool,
chosenUUID *string,
existingPlayer bool,
challengeToken *string,
inviteCode *string,
playerName *string,
fallbackPlayer *string,
preferredLanguage *string,
skinModel *string,
skinReader *io.Reader,
skinURL *string,
capeReader *io.Reader,
capeURL *string,
) (User, error) {
callerIsAdmin := caller != nil && caller.IsAdmin
if err := app.ValidateUsername(username); err != nil {
return User{}, NewBadRequestUserError("Invalid username: %s", err)
}
if err := app.ValidatePassword(password); err != nil {
return User{}, NewBadRequestUserError("Invalid password: %s", err)
}
if playerName == nil {
playerName = &username
} else {
if *playerName != username && !app.Config.AllowChangingPlayerName && !callerIsAdmin {
return User{}, NewBadRequestUserError("Choosing a player name different from your username is not allowed.")
}
if err := app.ValidatePlayerName(*playerName); err != nil {
return User{}, NewBadRequestUserError("Invalid player name: %s", err)
}
}
if preferredLanguage == nil {
preferredLanguage = &app.Config.DefaultPreferredLanguage
}
if !IsValidPreferredLanguage(*preferredLanguage) {
return User{}, NewBadRequestUserError("Invalid preferred language.")
}
getInvite := func(requireInvite bool) (*Invite, error) {
var invite Invite
if inviteCode == nil {
if requireInvite && !callerIsAdmin {
return nil, InviteMissingError
}
return nil, nil
} else {
result := app.DB.First(&invite, "code = ?", *inviteCode)
if result.Error != nil {
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return nil, InviteNotFoundError
}
return nil, result.Error
}
return &invite, nil
}
}
var accountUUID string
var invite *Invite
if existingPlayer {
// Existing player registration
if !app.Config.RegistrationExistingPlayer.Allow && !callerIsAdmin {
return User{}, NewBadRequestUserError("Registration from an existing account is not allowed.")
}
var err error
invite, err = getInvite(app.Config.RegistrationExistingPlayer.RequireInvite)
if err != nil {
return User{}, err
}
if chosenUUID != nil {
return User{}, NewBadRequestUserError("Can't register from an existing account AND choose a UUID.")
}
details, err := app.ValidateChallenge(*playerName, challengeToken)
if err != nil {
if app.Config.RegistrationExistingPlayer.RequireSkinVerification {
return User{}, NewBadRequestUserError("Couldn't verify your skin, maybe try again: %s", err)
} else {
return User{}, NewBadRequestUserError("Couldn't find your account, maybe try again: %s", err)
}
}
playerName = &details.Username
if err := app.ValidatePlayerName(*playerName); err != nil {
return User{}, NewBadRequestUserError("Invalid player name: %s", err)
}
accountUUID = details.UUID
} else {
// New player registration
if !app.Config.RegistrationNewPlayer.Allow && !callerIsAdmin {
return User{}, NewBadRequestUserError("Registration without some existing account is not allowed.")
}
var err error
invite, err = getInvite(app.Config.RegistrationNewPlayer.RequireInvite)
if err != nil {
return User{}, err
}
if chosenUUID == nil {
accountUUID = uuid.New().String()
} else {
if !app.Config.RegistrationNewPlayer.AllowChoosingUUID && !callerIsAdmin {
return User{}, NewBadRequestUserError("Choosing a UUID is not allowed.")
}
chosenUUIDStruct, err := uuid.Parse(*chosenUUID)
if err != nil {
return User{}, NewBadRequestUserError("Invalid UUID: %s", err)
}
accountUUID = chosenUUIDStruct.String()
}
}
passwordSalt := make([]byte, 16)
_, err := rand.Read(passwordSalt)
if err != nil {
return User{}, err
}
passwordHash, err := HashPassword(password, passwordSalt)
if err != nil {
return User{}, err
}
if isAdmin && !callerIsAdmin {
return User{}, NewBadRequestUserError("Cannot make a new admin user without having admin privileges yourself.")
}
if isLocked && !callerIsAdmin {
return User{}, NewBadRequestUserError("Cannot make a new locked user without admin privileges.")
}
offlineUUID, err := OfflineUUID(username)
if err != nil {
return User{}, err
}
if fallbackPlayer == nil {
fallbackPlayer = &accountUUID
}
if err := app.ValidatePlayerNameOrUUID(*fallbackPlayer); err != nil {
return User{}, NewBadRequestUserError("Invalid fallback player: %s", err)
}
apiToken, err := MakeAPIToken()
if err != nil {
return User{}, err
}
if skinModel == nil {
skinModel = Ptr(SkinModelClassic)
}
if !IsValidSkinModel(*skinModel) {
return User{}, NewBadRequestUserError("Invalid skin model.")
}
var skinHash *string
var skinBuf *bytes.Buffer
if skinReader != nil || skinURL != nil {
if !app.Config.AllowSkins && !callerIsAdmin {
return User{}, NewBadRequestUserError("Setting a skin is not allowed.")
}
if skinReader != nil && skinURL != nil {
return User{}, NewBadRequestUserError("Can't specify both a skin file and a skin URL.")
}
if skinURL != nil {
res, err := MakeHTTPClient().Get(*skinURL)
if err != nil {
return User{}, NewBadRequestUserError("Couldn't download skin from that URL: %s", err)
}
defer res.Body.Close()
bodyReader := res.Body.(io.Reader)
skinReader = &bodyReader
}
validSkinHandle, err := app.ValidateSkin(*skinReader)
if err != nil {
return User{}, NewBadRequestUserError("Error using that skin: %s", err)
}
var hash string
skinBuf, hash, err = app.ReadTexture(validSkinHandle)
if err != nil {
return User{}, err
}
skinHash = &hash
}
var capeHash *string
var capeBuf *bytes.Buffer
if capeReader != nil || capeURL != nil {
if !app.Config.AllowCapes && !callerIsAdmin {
return User{}, NewBadRequestUserError("Setting a cape is not allowed.")
}
if capeReader != nil && capeURL != nil {
return User{}, NewBadRequestUserError("Can't specify both a cape file and a cape URL.")
}
if capeURL != nil {
res, err := MakeHTTPClient().Get(*capeURL)
if err != nil {
return User{}, NewBadRequestUserError("Couldn't download cape from that URL: %s", err)
}
defer res.Body.Close()
bodyReader := res.Body.(io.Reader)
capeReader = &bodyReader
}
validCapeHandle, err := app.ValidateCape(*capeReader)
if err != nil {
return User{}, NewBadRequestUserError("Error using that cape: %s", err)
}
var hash string
capeBuf, hash, err = app.ReadTexture(validCapeHandle)
if err != nil {
return User{}, err
}
capeHash = &hash
}
user := User{
IsAdmin: Contains(app.Config.DefaultAdmins, username) || isAdmin,
IsLocked: isLocked,
UUID: accountUUID,
Username: username,
PasswordSalt: passwordSalt,
PasswordHash: passwordHash,
Clients: []Client{},
PlayerName: *playerName,
OfflineUUID: offlineUUID,
FallbackPlayer: *fallbackPlayer,
PreferredLanguage: app.Config.DefaultPreferredLanguage,
SkinModel: *skinModel,
SkinHash: MakeNullString(skinHash),
CapeHash: MakeNullString(capeHash),
APIToken: apiToken,
CreatedAt: time.Now(),
NameLastChangedAt: time.Now(),
}
tx := app.DB.Begin()
defer tx.Rollback()
result := tx.Create(&user)
if result.Error != nil {
if IsErrorUniqueFailedField(result.Error, "users.username") ||
IsErrorUniqueFailedField(result.Error, "users.player_name") {
return User{}, NewBadRequestUserError("That username is taken.")
} else if IsErrorUniqueFailedField(result.Error, "users.uuid") {
return User{}, NewBadRequestUserError("That UUID is taken.")
}
return User{}, result.Error
}
if invite != nil {
result = tx.Delete(invite)
if result.Error != nil {
return User{}, result.Error
}
}
result = tx.Commit()
if result.Error != nil {
return User{}, result.Error
}
if skinHash != nil {
err = app.WriteSkin(*skinHash, skinBuf)
if err != nil {
return user, NewBadRequestUserError("Error saving the skin.")
}
}
if capeHash != nil {
err = app.WriteCape(*capeHash, capeBuf)
if err != nil {
return user, NewBadRequestUserError("Error saving the cape.")
}
}
return user, nil
}
func (app *App) UpdateUser(
caller *User,
user User,
password *string,
isAdmin *bool,
isLocked *bool,
playerName *string,
fallbackPlayer *string,
resetAPIToken bool,
preferredLanguage *string,
skinModel *string,
skinReader *io.Reader,
skinURL *string,
deleteSkin bool,
capeReader *io.Reader,
capeURL *string,
deleteCape bool,
) (User, error) {
if caller == nil {
return User{}, NewBadRequestUserError("Caller cannot be null.")
}
callerIsAdmin := caller.IsAdmin
if user.UUID != caller.UUID && !callerIsAdmin {
return User{}, NewBadRequestUserError("You are not an admin.")
}
if password != nil {
if err := app.ValidatePassword(*password); err != nil {
return User{}, NewBadRequestUserError("Invalid password: %s", err)
}
passwordSalt := make([]byte, 16)
_, err := rand.Read(passwordSalt)
if err != nil {
return User{}, err
}
user.PasswordSalt = passwordSalt
passwordHash, err := HashPassword(*password, passwordSalt)
if err != nil {
return User{}, err
}
user.PasswordHash = passwordHash
}
if isAdmin != nil {
if !callerIsAdmin {
return User{}, NewBadRequestUserError("Cannot change admin status of user without having admin privileges yourself.")
}
user.IsAdmin = *isAdmin
}
if isLocked != nil {
if !callerIsAdmin {
return User{}, NewBadRequestUserError("Cannot change locked status of user without having admin privileges yourself.")
}
user.IsLocked = *isLocked
}
if playerName != nil && *playerName != user.PlayerName {
if !app.Config.AllowChangingPlayerName && !user.IsAdmin {
return User{}, NewBadRequestUserError("Changing your player name is not allowed.")
}
if err := app.ValidatePlayerName(*playerName); err != nil {
return User{}, NewBadRequestUserError("Invalid player name: %s", err)
}
offlineUUID, err := OfflineUUID(*playerName)
if err != nil {
return User{}, err
}
user.PlayerName = *playerName
user.OfflineUUID = offlineUUID
user.NameLastChangedAt = time.Now()
}
if fallbackPlayer != nil && *fallbackPlayer != user.FallbackPlayer {
if err := app.ValidatePlayerNameOrUUID(*fallbackPlayer); err != nil {
return User{}, NewBadRequestUserError("Invalid fallback player: %s", err)
}
user.FallbackPlayer = *fallbackPlayer
}
if preferredLanguage != nil {
if !IsValidPreferredLanguage(*preferredLanguage) {
return User{}, NewBadRequestUserError("Invalid preferred language.")
}
user.PreferredLanguage = *preferredLanguage
}
if resetAPIToken {
apiToken, err := MakeAPIToken()
if err != nil {
return User{}, err
}
user.APIToken = apiToken
}
if skinModel != nil {
if !IsValidSkinModel(*skinModel) {
return User{}, NewBadRequestUserError("Invalid skin model.")
}
user.SkinModel = *skinModel
}
// Skin and cape updates are done as follows:
// 1. Validate with ValidateSkin/ValidateCape
// 2. Read the texture into memory and hash it with ReadTexture
// 3. Update the database
// 4. If the database updated successfully:
// - Acquire a lock to the texture file
// - If the texture file doesn't exist, write it to disk
// - Delete the old texture if it's unused
//
// Any update should happen first to the DB, then to the filesystem. We
// don't attempt to roll back changes to the DB if we fail to write to
// the filesystem.
var skinBuf *bytes.Buffer
oldSkinHash := UnmakeNullString(&user.SkinHash)
if skinReader != nil || skinURL != nil {
// The user is setting a new skin
if !app.Config.AllowSkins && !callerIsAdmin {
return User{}, NewBadRequestUserError("Setting a skin is not allowed.")
}
if skinReader != nil && skinURL != nil {
return User{}, NewBadRequestUserError("Can't specify both a skin file and a skin URL.")
}
if skinURL != nil {
res, err := MakeHTTPClient().Get(*skinURL)
if err != nil {
return User{}, NewBadRequestUserError("Couldn't download skin from that URL: %s", err)
}
defer res.Body.Close()
bodyReader := res.Body.(io.Reader)
skinReader = &bodyReader
}
validSkinHandle, err := app.ValidateSkin(*skinReader)
if err != nil {
return User{}, NewBadRequestUserError("Error using that skin: %s", err)
}
var hash string
skinBuf, hash, err = app.ReadTexture(validSkinHandle)
if err != nil {
return User{}, err
}
user.SkinHash = MakeNullString(&hash)
} else if deleteSkin {
user.SkinHash = MakeNullString(nil)
}
var capeBuf *bytes.Buffer
oldCapeHash := UnmakeNullString(&user.CapeHash)
if capeReader != nil || capeURL != nil {
if !app.Config.AllowCapes && !callerIsAdmin {
return User{}, NewBadRequestUserError("Setting a cape is not allowed.")
}
if capeReader != nil && capeURL != nil {
return User{}, NewBadRequestUserError("Can't specify both a cape file and a cape URL.")
}
if capeURL != nil {
res, err := MakeHTTPClient().Get(*capeURL)
if err != nil {
return User{}, NewBadRequestUserError("Couldn't download cape from that URL: %s", err)
}
defer res.Body.Close()
bodyReader := res.Body.(io.Reader)
capeReader = &bodyReader
}
validCapeHandle, err := app.ValidateCape(*capeReader)
if err != nil {
return User{}, NewBadRequestUserError("Error using that cape: %s", err)
}
var hash string
capeBuf, hash, err = app.ReadTexture(validCapeHandle)
if err != nil {
return User{}, err
}
user.CapeHash = MakeNullString(&hash)
} else if deleteCape {
user.CapeHash = MakeNullString(nil)
}
newSkinHash := UnmakeNullString(&user.SkinHash)
newCapeHash := UnmakeNullString(&user.CapeHash)
err := app.DB.Save(&user).Error
if err != nil {
if IsErrorUniqueFailed(err) {
return User{}, NewBadRequestUserError("That player name is taken.")
}
return User{}, err
}
if !PtrEquals(oldSkinHash, newSkinHash) {
if newSkinHash != nil {
err = app.WriteSkin(*newSkinHash, skinBuf)
if err != nil {
return User{}, NewBadRequestUserError("Error saving the skin.")
}
}
err = app.DeleteSkinIfUnused(oldSkinHash)
if err != nil {
return User{}, err
}
}
if !PtrEquals(oldCapeHash, newCapeHash) {
if newCapeHash != nil {
err = app.WriteCape(*newCapeHash, capeBuf)
if err != nil {
return User{}, NewBadRequestUserError("Error saving the cape.")
}
}
err = app.DeleteCapeIfUnused(oldCapeHash)
if err != nil {
return User{}, err
}
}
return user, nil
}
type proxiedAccountDetails struct {
Username string
UUID string
}
func (app *App) GetChallenge(username string, token string) []byte {
// This challenge is nice because:
// - it doesn't depend on any serverside state
// - an attacker can't use it to verify a different username, since hash
// incorporates the username - an attacker can't generate their own
// challenges, since the hash includes a hash of the instance's private key
// - an attacker can't steal the skin mid-verification and register the
// account themselves, since the hash incorporates a token known only to
// the verifying browser
challengeBytes := bytes.Join([][]byte{
[]byte(username),
app.KeyB3Sum512,
[]byte(token),
}, []byte{})
sum := blake3.Sum512(challengeBytes)
return sum[:]
}
func (app *App) ValidateChallenge(username string, challengeToken *string) (*proxiedAccountDetails, error) {
base, err := url.Parse(app.Config.RegistrationExistingPlayer.AccountURL)
if err != nil {
return nil, err
}
base.Path, err = url.JoinPath(base.Path, "users/profiles/minecraft/"+username)
if err != nil {
return nil, err
}
res, err := MakeHTTPClient().Get(base.String())
if err != nil {
log.Printf("Couldn't access registration server at %s: %s\n", base.String(), err)
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
log.Printf("Request to registration server at %s resulted in status code %d\n", base.String(), res.StatusCode)
return nil, errors.New("registration server returned error")
}
var idRes playerNameToUUIDResponse
err = json.NewDecoder(res.Body).Decode(&idRes)
if err != nil {
return nil, err
}
base, err = url.Parse(app.Config.RegistrationExistingPlayer.SessionURL)
if err != nil {
return nil, fmt.Errorf("Invalid SessionURL %s: %s", app.Config.RegistrationExistingPlayer.SessionURL, err)
}
base.Path, err = url.JoinPath(base.Path, "session/minecraft/profile/"+idRes.ID)
if err != nil {
return nil, err
}
res, err = MakeHTTPClient().Get(base.String())
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
log.Printf("Request to registration server at %s resulted in status code %d\n", base.String(), res.StatusCode)
return nil, errors.New("registration server returned error")
}
var profileRes SessionProfileResponse
err = json.NewDecoder(res.Body).Decode(&profileRes)
if err != nil {
return nil, err
}
id := profileRes.ID
accountUUID, err := IDToUUID(id)
if err != nil {
return nil, err
}
details := proxiedAccountDetails{
Username: profileRes.Name,
UUID: accountUUID,
}
if !app.Config.RegistrationExistingPlayer.RequireSkinVerification {
return &details, nil
}
for _, property := range profileRes.Properties {
if property.Name == "textures" {
textureJSON, err := base64.StdEncoding.DecodeString(property.Value)
if err != nil {
return nil, err
}
var texture texturesValue
err = json.Unmarshal(textureJSON, &texture)
if err != nil {
return nil, err
}
if texture.Textures.Skin == nil {
return nil, errors.New("player does not have a skin")
}
res, err = MakeHTTPClient().Get(texture.Textures.Skin.URL)
if err != nil {
return nil, err
}
defer res.Body.Close()
rgba_img, err := png.Decode(res.Body)
if err != nil {
return nil, err
}
img, ok := rgba_img.(*image.NRGBA)
if !ok {
return nil, errors.New("invalid image")
}
challenge := make([]byte, 64)
challengeByte := 0
for y := SKIN_WINDOW_Y_MIN; y < SKIN_WINDOW_Y_MAX; y += 1 {
for x := SKIN_WINDOW_X_MIN; x < SKIN_WINDOW_X_MAX; x += 1 {
c := img.NRGBAAt(x, y)
challenge[challengeByte] = c.R
challenge[challengeByte+1] = c.G
challenge[challengeByte+2] = c.B
challenge[challengeByte+3] = c.A
challengeByte += 4
}
}
if challengeToken == nil {
return nil, errors.New("missing challenge token")
}
correctChallenge := app.GetChallenge(username, *challengeToken)
if !bytes.Equal(challenge, correctChallenge) {
return nil, errors.New("skin does not match")
}
if err != nil {
return nil, err
}
return &details, nil
}
}
return nil, errors.New("registration server didn't return textures")
}
func MakeChallengeToken() (string, error) {
return RandomHex(16)
}
func (app *App) GetChallengeSkin(username string, challengeToken string) ([]byte, error) {
if err := app.ValidateUsername(username); err != nil {
return nil, NewBadRequestUserError("Invalid username: %s", err)
}
// challenge is a 512-bit, 64 byte checksum
challenge := app.GetChallenge(username, challengeToken)
// Embed the challenge into a skin
skinSize := 64
img := image.NewNRGBA(image.Rectangle{image.Point{0, 0}, image.Point{skinSize, skinSize}})
challengeByte := 0
for y := 0; y < skinSize; y += 1 {
for x := 0; x < skinSize; x += 1 {
var col color.NRGBA
if SKIN_WINDOW_Y_MIN <= y && y < SKIN_WINDOW_Y_MAX && SKIN_WINDOW_X_MIN <= x && x < SKIN_WINDOW_X_MAX {
col = color.NRGBA{
challenge[challengeByte],
challenge[challengeByte+1],
challenge[challengeByte+2],
challenge[challengeByte+3],
}
challengeByte += 4
} else {
col = app.VerificationSkinTemplate.At(x, y).(color.NRGBA)
}
img.SetNRGBA(x, y, col)
}
}
var imgBuffer bytes.Buffer
err := png.Encode(&imgBuffer, img)
if err != nil {
return nil, err
}
return imgBuffer.Bytes(), nil
}
func (app *App) InvalidateUser(db *gorm.DB, user *User) error {
result := db.Model(Client{}).Where("user_uuid = ?", user.UUID).Update("version", gorm.Expr("version + ?", 1))
return result.Error
}
func (app *App) SetIsLocked(db *gorm.DB, user *User, isLocked bool) error {
user.IsLocked = isLocked
if isLocked {
user.BrowserToken = MakeNullString(nil)
err := app.InvalidateUser(db, user)
if err != nil {
return err
}
}
return nil
}
func (app *App) DeleteUser(user *User) error {
oldSkinHash := UnmakeNullString(&user.SkinHash)
oldCapeHash := UnmakeNullString(&user.CapeHash)
err := app.DB.Select("Clients").Delete(&user).Error
if err != nil {
return err
}
err = app.DeleteSkinIfUnused(oldSkinHash)
if err != nil {
return err
}
err = app.DeleteCapeIfUnused(oldCapeHash)
if err != nil {
return err
}
return nil
}