-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathAuth.php
1084 lines (882 loc) · 36.6 KB
/
Auth.php
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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
/**
* Auth
*
* Secure auth built on delight-im/auth.
* Replaces various homebrew components.
*
* Functions like an oracle service:
* takes queries and returns messages.
*
* @see https://github.com/delight-im/PHP-Auth
*/
class Auth # extends Delight\Auth\Auth
{
# library instance
public \Delight\Auth\Auth $library;
# 2fa libraries
private \RobThree\Auth\TwoFactorAuth $twoFactor;
# seconds * minutes * hours * days
private int $shortRemember = 60 * 60 * 24 * 1;
private int $longRemember = 60 * 60 * 24 * 7;
# hash algo for passwords
# legacy: remove after 2024-04-01
private static string $algorithm = "sha512";
# https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html#authentication-and-error-messages
private string $message = "Invalid username, passphrase, or 2FA";
/**
* __construct
*
* @see https://github.com/delight-im/PHP-Auth#creating-a-new-instance
*/
public function __construct()
{
$app = \Gazelle\App::go();
if ($app->env->dev) {
$throttling = false;
} else {
$throttling = true;
}
try {
$this->library = new Delight\Auth\Auth(
databaseConnection: $app->dbNew->source,
throttling: $throttling
);
$this->twoFactor = new RobThree\Auth\TwoFactorAuth($app->env->siteName);
} catch (Throwable $e) {
return $e->getMessage();
}
}
/**
* register
*
* Returns a variety of different responses, unlike most.
* We want them to register *before* they get vague messages.
*
* @param array $post Gazelle\Http::request("post")
* @return string|int error or userId
*
* @see https://github.com/delight-im/PHP-Auth#registration-sign-up
*/
public function register(array $data): string|int
{
$app = \Gazelle\App::go();
# escape the inputs
$username = \Gazelle\Escape::username($data["username"] ?? null);
$email = \Gazelle\Escape::email($data["email"] ?? null);
$passphrase = \Gazelle\Escape::passphrase($data["passphrase"] ?? null);
$confirmPassphrase = \Gazelle\Escape::passphrase($data["confirmPassphrase"] ?? null);
$invite = \Gazelle\Escape::string($data["invite"] ?? null);
try {
# throttle registration attempts: 1 request per IP address per 60 minutes
$this->library->throttle(["createNewAccount", $this->library->getIpAddress()], 1, 3600);
# disallow registration if the database is encrypted
if (!apcu_exists("DBKEY")) {
throw new Exception("Registration temporarily disabled due to degraded database access");
}
# make sure the essential info isn't empty
if (empty($email) || empty($passphrase) || empty($confirmPassphrase) || empty($username)) {
throw new Exception("Please fill out all the fields");
}
# extra form fields (privacy consent, age check, etc.)
if (empty($data["isAdult"]) || empty($data["privacyConsent"]) || empty($data["ruleWikiPledge"])) {
throw new Exception("You need to check the legal age, privacy consent, and rules/wiki boxes");
}
# passphrase mismatch
if ($passphrase !== $confirmPassphrase) {
throw new Exception("The entered passphrases don't match");
}
# passphrase = username
if ($passphrase === $username) {
throw new Exception("Your passphrase can't be the same as your username");
}
# passphrase = email
if ($passphrase === $email) {
throw new Exception("Your passphrase can't be the same as your email");
}
/*
# you may want to exclude non-printing control characters and certain printable special characters
if (preg_match("/[\x00-\x1f\x7f\/:\\\\]/", $username)) {
throw new Exception("Registering usernames with control characters isn't allowed");
}
*/
# don't allow a username of "0" or "1" due to PHP's type juggling
if (trim($username) === "0" || trim($username) === "1") {
throw new Exception("You can't have a username of 0 or 1");
}
# disallow registration without invite if site is closed
if (!$app->env->openRegistration && empty($invite)) {
throw new Exception("Open registration is disabled, no invite code provided");
}
# is the email blacklisted?
$domain = explode("@", $email)[1] ?? null;
$query = "select 1 from email_blacklist where email like '%{$domain}%' limit 1";
$bad = $app->dbNew->single($query, []);
if ($bad) {
throw new Exception("This email address can't be used to register an account");
}
# check the validity of the invite code
if (!empty($invite)) {
$query = "select 1 from invites where inviteKey = ?";
$good = $app->dbNew->single($query, [$invite]);
if (!$good) {
throw new Exception("Invalid invite code");
}
}
# if you want to enforce unique usernames,
# simply call registerWithUniqueUsername instead of register,
# and be prepared to catch the DuplicateUsernameException
$response = $this->library->registerWithUniqueUsername($email, $passphrase, $username, function ($selector, $token) use ($email) {
$app = \Gazelle\App::go();
# build the verification uri
$uri = "https://{$app->env->siteDomain}/confirm/{$selector}/{$token}";
# email it to the prospective user
$subject = "Confirm your new {$app->env->siteName} account";
$body = $app->twig->render("email/verifyRegistration.twig", ["env" => $app->env, "uri" => $uri]);
# send the email
$app->email($email, $subject, $body);
});
if (!is_int($response)) {
throw new Exception("Registration failed");
}
# this will be a userId
$this->hydrateUserInfo($response, $data);
return $response;
} catch (Delight\Auth\InvalidEmailException $e) {
return "Please use a different email";
} catch (Delight\Auth\InvalidPasswordException $e) {
return "Please use a different passphrase";
} catch (Delight\Auth\UserAlreadyExistsException $e) {
return "Please use a different username";
} catch (Delight\Auth\TooManyRequestsException $e) {
return "Please try again later";
} catch (Delight\Auth\DuplicateUsernameException $e) {
return "Please use a different username";
} catch (Throwable $e) {
return $e->getMessage();
}
} # register
/**
* hydrateUserInfo
*
* Populates some defaults in the Gazelle user tables.
*/
public function hydrateUserInfo(int $userId, array $data = [])
{
$app = \Gazelle\App::go();
# http query vars
$server = \Gazelle\Http::request("server");
# escape the inputs
$email = \Gazelle\Escape::email($data["email"] ?? null);
$encryptedEmail = \Gazelle\Crypto::encrypt($email);
$passphrase = \Gazelle\Escape::passphrase($data["passphrase"] ?? null);
$confirmPassphrase = \Gazelle\Escape::passphrase($data["confirmPassphrase"] ?? null);
$username = \Gazelle\Escape::username($data["username"] ?? null);
$invite = \Gazelle\Escape::string($data["invite"] ?? null);
# generate keys
$torrent_pass = \Gazelle\Text::random(32);
$authKey = \Gazelle\Text::random(32);
$resetKey = \Gazelle\Text::random(32);
# delight-im/auth: encrypt the email
# purposefully enforced outside the transaction
$query = "update users set email = ? where id = ?";
$app->dbNew->do($query, [$encryptedEmail, $userId]);
try {
# start a transaction
$app->dbNew->beginTransaction();
# users_main
$query = "
insert into users_main (
userId, username, email, passHash,
ip, uploaded, enabled, invites, permissionId, torrent_pass, flTokens)
values (
:userId, :username, :email, :passHash,
:ip, :uploaded, :enabled, :invites, :permissionId, :torrent_pass, :flTokens)
";
/*
# todo: this will have to wait until foreign key constraints are resolved
$query = "
insert into users_main (
id, userId, username, email, passHash,
ip, uploaded, enabled, invites, permissionId, torrent_pass, flTokens)
values (
:id, :userId, :username, :email, :passHash,
:ip, :uploaded, :enabled, :invites, :permissionId, :torrent_pass, :flTokens)
";
*/
$app->dbNew->do($query, [
#"id" => $userId, # required for legacy gazelle queries
"userId" => $userId, # this will become the primary key
# legacy not null fields
"username" => $username,
"email" => $encryptedEmail,
"passHash" => password_hash($passphrase, PASSWORD_DEFAULT),
# everything else
"ip" => \Gazelle\Crypto::encrypt($server["REMOTE_ADDR"]),
"uploaded" => $app->env->newUserUpload,
"enabled" => 1,
"invites" => $app->env->newUserInvites,
"permissionId" => USER, # todo: constant
"torrent_pass" => $torrent_pass,
"flTokens" => $app->env->newUserTokens,
]);
/*
# todo: we're just updating users_main.id, it's technically wrong
$query = "update users_main set id = userId where userId = ?";
$app->dbNew->do($query, [$userId]);
*/
/** */
# invite tree stuff
if (!empty($invite)) {
$query = "select inviterId, email, reason from invites where inviteKey = ?";
$row = $app->dbNew->row($query, [$invite]) ?? [];
# user created, delete invite
$query = "delete from invites where inviteKey = ?";
$app->dbNew->do($query, [$invite]);
# manage invite trees
$inviterId = $row["inviterId"] ?? null;
if ($inviterId) {
$query = "select treePosition, treeId, treeLevel from invite_tree where userId = ?";
$row = $app->dbNew->row($query, [$inviterId]) ?? [];
$treePosition = $row["treePosition"] ?? null;
$treeId = $row["treeId"] ?? null;
$treeLevel = $row["treeLevel"] ?? null;
# if the inviter doesn't have an invite tree
# note: this should never happen unless you've transferred from another database like what.cd did
if (empty($row)) {
$query = "select max(treeId) + 1 from invite_tree";
$treeId = $app->dbNew->single($query);
$query = "
insert into invite_tree (userId, inviterId, treePosition, treeId, treeLevel)
values (?, ?, ?, ?, ?)
";
$app->dbNew->do($query, [$inviterId, 0, 1, $treeId, 1]);
$treePosition = 2;
$treeLevel = 2;
}
# normal tree position calculation
$query = "select treePosition from invite_tree where treePosition = ? and treeLevel = ? and treeId = ?";
$treePosition = $app->dbNew->single($query, [$treePosition, $treeLevel, $treeId]) ?? null;
if ($treePosition) {
$query = "update invite_tree set treePosition = treePosition + 1 where treeId = ? and treePosition >= ?";
$app->dbNew->do($query, [$treeId, $treePosition]);
} else {
$query = "select treePosition + 1 from invite_tree where treeId = ? order by treePosition desc";
$treePosition = $app->dbNew->single($query, [$treeId]);
$treeLevel++;
# create invite tree record
$query = "
insert into invite_tree (userId, inviterId, treePosition, treeId, treeLevel)
values (?, ?, ?, ?, ?)
";
$app->dbNew->do($query, [$userId, $inviterId, $treePosition, $treeId, $treeLevel]);
}
} # if inviterId
} # if invite
/** */
# default stylesheet
$query = "select id from stylesheets where `default` = 1";
$styleId = $app->dbNew->single($query, []) ?? 1;
# users_info
$query = "
insert into users_info (userId, styleId, siteOptions, authKey, resetKey, inviter, isPassphraseMigrated)
values (:userId, :styleId, :siteOptions, :authKey, :resetKey, :inviter, :isPassphraseMigrated)
";
$app->dbNew->do($query, [
"userId" => $userId,
"styleId" => $styleId,
"siteOptions" => $app->env->defaultSiteOptions,
"authKey" => $authKey,
"resetKey" => $resetKey,
"inviter" => $inviterId ?? null,
"isPassphraseMigrated" => 1,
]);
# users_notifications_settings
$query = "insert into users_notifications_settings (userId) values (?)";
$app->dbNew->do($query, [$userId]);
# update ocelot and commit
\TrackerOld::update_tracker("add_user", ["id" => $userId, "passkey" => $torrent_pass]);
$app->dbNew->commit();
} catch (Throwable $e) {
$app->dbNew->rollBack();
return $e->getMessage();
}
} # hydrateUserInfo
/**
* login
*
* @see https://github.com/delight-im/PHP-Auth#login-sign-in
*/
public function login(array $data)
{
$app = \Gazelle\App::go();
# https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html#login
$message = $this->message;
$username = \Gazelle\Escape::username($data["username"] ?? null);
$passphrase = \Gazelle\Escape::passphrase($data["passphrase"] ?? null);
$twoFactor = \Gazelle\Escape::string($data["twoFactor"] ?? null);
$rememberMe = \Gazelle\Escape::bool($data["rememberMe"] ?? null);
try {
# start a transaction
$app->dbNew->beginTransaction();
# validate userId and 2fa
$query = "
select users.id, users_main.twoFactor from users
join users_main on users_main.userId = users.id
where users.username = ?
";
$row = $app->dbNew->row($query, [$username]);
$userId = $row["id"] ?? null;
if (!$userId) {
throw new Exception("username doesn't exist");
}
$row["twoFactor"] ??= null;
if ($row["twoFactor"] && empty($twoFactor)) {
throw new Exception("2fa code required");
}
if (!empty($twoFactor)) {
$this->verify2FA($userId, $twoFactor);
}
# are there any unencrypted emails left?
$query = "select email from users where id = ?";
$email = $app->dbNew->single($query, [$userId]);
$decryptedEmail = \Gazelle\Crypto::decrypt($email);
if (!$decryptedEmail && \Gazelle\Crypto::apcuExists()) {
$query = "update users set email = ? where id = ?";
$app->dbNew->do($query, [ \Gazelle\Crypto::encrypt($email), $userId ]);
}
# legacy isPassphraseMigrated: remove after 2025-04-01
$query = "select isPassphraseMigrated from users_info where userId = ?";
$isPassphraseMigrated = $app->dbNew->single($query, [$userId]);
if (boolval($isPassphraseMigrated) === false) {
$query = "select password from users where id = ?";
$hash = $app->dbNew->single($query, [$userId]);
$good = self::checkHash($passphrase, $hash);
if (!$good) {
throw new Exception("current passphrase doesn't match");
}
# the current passphrase is good, just update it to a real hash
$this->library->admin()->changePasswordForUserById($userId, $passphrase);
# update isPassphraseMigrated to not deal with this again
$query = "update users_info set isPassphraseMigrated = ? where userId = ?";
$app->dbNew->do($query, [1, $userId]);
}
# resume normal, relatively sane code below
# simply call the method loginWithUsername instead of method login
# make sure to catch both UnknownUsernameException and AmbiguousUsernameException
$this->library->loginWithUsername($username, $passphrase, $this->remember($rememberMe));
/*
# try email validation
$usingEmail = \Gazelle\Escape::email($username);
if (!empty($usingEmail)) {
$response = $this->library->login($username, $passphrase, $this->remember($rememberMe));
} else {
# simply call the method loginWithUsername instead of method login
# make sure to catch both UnknownUsernameException and AmbiguousUsernameException
$username = \Gazelle\Escape::username($username);
$response = $this->library->loginWithUsername($username, $passphrase, $this->remember($rememberMe));
}
*/
/*
} catch (\Delight\Auth\InvalidEmailException $e) {
return $e->getMessage();
return $message;
} catch (\Delight\Auth\InvalidPasswordException $e) {
return $e->getMessage();
return $message;
*/
} catch (\Delight\Auth\EmailNotVerifiedException $e) {
# this throws to provide a "resend confirmation email" link
throw new \Delight\Auth\EmailNotVerifiedException($e->getMessage());
/*
} catch (\Delight\Auth\TooManyRequestsException $e) {
return $e->getMessage();
return $message;
} catch (\Delight\Auth\UnknownUsernameException $e) {
return $e->getMessage();
return $message;
} catch (\Delight\Auth\AmbiguousUsernameException $e) {
return $e->getMessage();
return $message;
*/
} catch (Throwable $e) {
return $e->getMessage();
return $message;
}
} # login
/**
* verify2FA
*/
public function verify2FA(int $userId, string $twoFactorCode): void
{
$app = \Gazelle\App::go();
# get the secret
$query = "select twoFactor from users_main where userId = ? and twoFactor is not null";
$twoFactorSecret = $app->dbNew->single($query, [$userId]);
# no secret
if (!$twoFactorSecret) {
throw new Exception("unable to find the 2FA seed");
}
# failed to verify
if (!$this->twoFactor->verifyCode($twoFactorSecret, $twoFactorCode)) {
throw new Exception("unable to verify the 2FA token");
}
}
/**
* confirmEmail
*
* @return string|array error or [0 => oldEmail, 1 => newEmail]
*/
public function confirmEmail(string $selector, string $token)
{
$app = \Gazelle\App::go();
$message = "Invalid selector or token";
$selector = \Gazelle\Escape::string($selector);
$token = \Gazelle\Escape::string($token);
try {
# if you want the user to be automatically signed in after successful confirmation,
# just call confirmEmailAndSignIn instead of confirmEmail
$this->library->confirmEmail($selector, $token, $this->remember());
} catch (\Delight\Auth\InvalidSelectorTokenPairException $e) {
return $message;
} catch (\Delight\Auth\TokenExpiredException $e) {
# this throws to provide a "resend confirmation email" link
throw new \Delight\Auth\TokenExpiredException($e->getMessage());
} catch (\Delight\Auth\UserAlreadyExistsException $e) {
return $message;
} catch (\Delight\Auth\TooManyRequestsException $e) {
return $message;
} catch (Throwable $e) {
return $message;
}
} # confirmEmail
/**
* remember
*
* @see https://github.com/delight-im/PHP-Auth#keeping-the-user-logged-in
*/
private function remember(bool $enabled = false): int
{
$app = \Gazelle\App::go();
$enabled = \Gazelle\Escape::bool($enabled);
if ($enabled === true) {
return $this->longRemember;
}
if ($enabled === false) {
return $this->shortRemember;
}
}
/**
* recoverStart
*
* Account recovery step one.
*
* @see https://github.com/delight-im/PHP-Auth#step-1-of-3-initiating-the-request
*/
public function recoverStart(string $email, string $ip)
{
$app = \Gazelle\App::go();
$message = "Unable to start account recovery";
$email = \Gazelle\Escape::email($email);
$ip = \Gazelle\Escape::ip($ip);
try {
$this->library->forgotPassword($email, function ($selector, $token) use ($email, $ip) {
$app = \Gazelle\App::go();
# build the verification uri
$uri = "https://{$app->env->siteDomain}/recover/{$selector}/{$token}";
# email it to the prospective user
$subject = "Your {$app->env->siteName} passphrase recovery";
$body = $app->twig->render("email/passphraseReset.twig", ["uri" => $uri, "ip" => $ip]);
$app->email($email, $subject, $body);
Announce::slack("{$email}\n{$subject}\n{$body}", ["debug"]);
});
} catch (Throwable $e) {
# reveals invalid email
#return $message;
}
} # recoverStart
/**
* recoverMiddle
*
* Account recovery step two.
*
* @see https://github.com/delight-im/PHP-Auth#step-2-of-3-verifying-an-attempt
*/
public function recoverMiddle(string $selector, string $token)
{
$app = \Gazelle\App::go();
$message = "Unable to continue account recovery";
$selector = \Gazelle\Escape::string($selector);
$token = \Gazelle\Escape::string($token);
try {
# put the selector and token in hidden fields
# ask the user for their new passphrase
$this->library->canResetPasswordOrThrow($selector, $token);
} catch (Throwable $e) {
return $message;
}
} # recoverMiddle
/**
* recoverEnd
*
* Account recovery step three.
*
* @see https://github.com/delight-im/PHP-Auth#step-3-of-3-updating-the-password
*/
public function recoverEnd(string $selector, string $token, string $passphrase, string $confirmPassphrase)
{
$app = \Gazelle\App::go();
$message = "Unable to finish account recovery";
$selector = \Gazelle\Escape::string($selector);
$token = \Gazelle\Escape::string($token);
$passphrase = \Gazelle\Escape::passphrase($passphrase);
$confirmPassphrase = \Gazelle\Escape::passphrase($confirmPassphrase);
try {
if ($passphrase !== $confirmPassphrase) {
throw new Exception("The entered passphrases don't match");
}
# resolve the username and email
$query = "
select username, email from users
left join users_resets on users_resets.user = users.id
where selector = ?
";
$row = $app->dbNew->row($query, [$selector]);
if (!$row["username"]) {
throw new Exception("Unable to find the username");
}
# passphrase = username
if ($passphrase === $row["username"]) {
throw new Exception("Your passphrase can't be the same as your username");
}
# passphrase = email
$row["email"] = \Gazelle\Crypto::decrypt($row["email"]);
if ($passphrase === $row["email"]) {
throw new Exception("Your passphrase can't be the same as your email");
}
# reset the passphrase
$this->library->resetPassword($selector, $token, $passphrase);
} catch (Throwable $e) {
return $e->getMessage();
}
} # recoverEnd
/**
* changePassphrase
*
* @see https://github.com/delight-im/PHP-Auth#changing-the-current-users-password
*/
public function changePassphrase(string $oldPassphrase, string $newPassphrase)
{
throw new \Exception("not implemented");
/*
$app = \Gazelle\App::go();
$message = "Unable to update passphrase";
$oldPassphrase = \Gazelle\Escape::passphrase($oldPassphrase);
$newPassphrase = \Gazelle\Escape::passphrase($newPassphrase);
try {
$this->library->changePassword($oldPassphrase, $newPassphrase);
} catch (Throwable $e) {
return $message;
}
*/
} # changePassphrase
/**
* changeEmail
*
* Actually, I'm gonna bypass the library for this.
* It doesn't make sense to require extra steps here,
* and I need to support encrypted email addresses.
*
* @see https://github.com/delight-im/PHP-Auth#changing-the-current-users-email-address
*/
public function changeEmail(int $userId, string $newEmail)
{
$app = \Gazelle\App::go();
$message = "Unable to update email";
$newEmail = \Gazelle\Escape::email($newEmail);
$newEmail = \Gazelle\Crypto::encrypt($newEmail);
try {
$query = "update users set email = ? where id = ?";
$app->dbNew->do($query, [$newEmail, $userId]);
} catch (Throwable $e) {
return $message;
}
/*
$app = \Gazelle\App::go();
$message = "Unable to update email";
# sanitize the input
$newEmail = \Gazelle\Escape::email($newEmail);
try {
$this->library->changeEmail($newEmail, function ($selector, $token) use ($newEmail) {
$app = \Gazelle\App::go();
# build the uri
$uri = "https://{$app->env->siteDomain}/confirm/{$selector}/{$token}";
# email content
$subject = "Confirm your new email address";
$body = $app->twig->render("email/changeEmail.twig", ["uri" => $uri]);
# send the email
$app->email($newEmail, $subject, $body);
});
} catch (Throwable $e) {
return $message;
}
*/
} # changeEmail
/**
* resendConfirmation
*
* @see https://github.com/delight-im/PHP-Auth#re-sending-confirmation-requests
*/
public function resendConfirmation(int|string $identifier)
{
$app = \Gazelle\App::go();
$message = "Unable to resend confirmation email";
# try to resolve the email address
$identifier = \Gazelle\Escape::string($identifier);
$column = $app->dbNew->determineId($identifier);
# todo: maybe change unresolved id or uuid to null
# and let the backend decide which column to use?
if ($column === "slug") {
$column = "username";
}
$query = "select email from users where {$column} = ?";
$email = $app->dbNew->single($query, [$identifier]);
$email = \Gazelle\Crypto::decrypt($email);
if (!$email) {
return $message;
}
try {
$this->library->resendConfirmationForEmail($email, function ($selector, $token) use ($email) {
$app = \Gazelle\App::go();
# build the verification uri
$uri = "https://{$app->env->siteDomain}/confirm/{$selector}/{$token}";
# email it to the prospective user
$subject = "Confirm your new {$app->env->siteName} account";
$body = $app->twig->render("email/verifyRegistration.twig", ["env" => $app->env, "uri" => $uri]);
# send the email
$app->email($email, $subject, $body);
});
} catch (\Delight\Auth\ConfirmationRequestNotFound $e) {
return $message;
} catch (\Delight\Auth\TooManyRequestsException $e) {
return $message;
} catch (Throwable $e) {
return $message;
}
} # resendConfirmation
/**
* logout
*
* @see https://github.com/delight-im/PHP-Auth#logout
*/
public function logout()
{
$message = "Unable to log out: please manually clear cookies";
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data
if (!headers_sent()) {
header("Clear-Site-Data: '*'");
}
try {
# you can destroy the entire session by calling a second method
$this->library->logOutEverywhere();
$this->library->destroySession();
# flush all the cookies
\Gazelle\Http::flushCookies();
# cache: should be a hash map
$app->cache->delete("user_info_heavy_{$app->user->core["id"]}");
$app->cache->delete("user_info_{$app->user->core["id"]}");
$app->cache->delete("user_stats_{$app->user->core["id"]}");
$app->cache->delete("users_sessions_{$app->user->core["id"]}");
} catch (Throwable $e) {
return $message;
}
} # logout
/**
* Additional user information
*
* In order to preserve this library’s suitability for all purposes as well as its full re-usability,
* it doesn’t come with additional bundled columns for user information.
* But you don’t have to do without additional user information, of course:
*
* Here’s how to use this library with your own tables for custom user information in a maintainable and re-usable way:
*
* 1. Add any number of custom database tables where you store custom user information, e.g. a table named profiles.
*
* 2. Whenever you call the register method (which returns the new user’s ID), add your own logic afterwards that fills your custom database tables.
*
* 3. If you need the custom user information only rarely, you may just retrieve it as needed.
* If you need it more frequently, however, you’d probably want to have it in your session data.
* The following method is how you can load and access your data in a reliable way:
*
* function getUserInfo(\Delight\Auth\Auth $auth) {
* if (!$auth->isLoggedIn()) {
* return null;
* }
*
* if (!isset($_SESSION['_internal_user_info'])) {
* // TODO: load your custom user information and assign it to the session variable below
* // $_SESSION['_internal_user_info'] = ...
* }
*
* return $_SESSION['_internal_user_info'];
* }
*
* @see https://github.com/delight-im/PHP-Auth#additional-user-information
*/
/**
* enforceLogin
*
* @see https://github.com/delight-im/PHP-Auth#reconfirming-the-users-password
*/
public function enforceLogin(string $passphrase)
{
$app = \Gazelle\App::go();
$message = $this->message;
$passphrase = \Gazelle\Escape::passphrase($passphrase);
try {
$this->library->reconfirmPassword($passphrase);
} catch (Throwable $e) {
return $message;
}
} # enforceLogin
/**
* toggleReset
*
* @see https://github.com/delight-im/PHP-Auth#enabling-or-disabling-password-resets
*/
public function toggleReset(bool $enabled, string $passphrase)
{
$app = \Gazelle\App::go();
$message = "Unable to update reset preference";
$enabled = \Gazelle\Escape::bool($enabled);
$passphrase = \Gazelle\Escape::passphrase($passphrase);
try {
$reconfirmed = $this->library->reconfirmPassword($passphrase);
if ($reconfirmed) {
$this->library->setPasswordResetEnabled(boolval($enabled));
} else {
throw new Exception("We can't say if the user is who they claim to be");
}
} catch (Throwable $e) {
return $message;
}
} # toggleReset
/**
* isPassphraseAllowed
*
* @see https://github.com/delight-im/PHP-Auth#how-can-i-implement-custom-password-requirements
*/
public function isPassphraseAllowed(string $passphrase): bool
{
$passphrase = \Gazelle\Escape::passphrase($passphrase);
if (empty($passphrase) || strlen($passphrase) < 15) {
return false;
}
return true;
}
/** gazelle hash checking */
/**
* makeHash
*
* Create a salted hash for a string.
* TODO: DELETE THIS AFTER 2024-04-01.
*
* @param string $string plaintext
* @return string salted hash
*/
public static function makeHash(string $string): string
{
return password_hash(
str_replace(
"\0",
"",
hash(self::$algorithm, $string, true)
),
PASSWORD_DEFAULT
);
}
/**
* checkHash
*
* Verify a passphrase against a passphrase hash.
* TODO: DELETE THIS AFTER 2024-04-01.
*
* @param string $string plaintext
* @param string $hash passphrase hash
* @return bool on verification
*/
public static function checkHash(string $string, ?string $hash = null): bool
{
if (!$hash) {
return false;
}
return password_verify(
str_replace(