/
ProcessLogin.module
1266 lines (1108 loc) · 38.7 KB
/
ProcessLogin.module
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 namespace ProcessWire;
/**
* ProcessWire Login Process
*
* Provides Login capability for ProcessWire Admin
*
* For more details about how Process modules work, please see:
* /wire/core/Process.php
*
* ProcessWire 3.x, Copyright 2023 by Ryan Cramer
* https://processwire.com
*
* @property bool $allowForgot Whether the ProcessForgotPassword module is installed.
* @property bool|int $allowEmail Whether or not email login is allowed (0|false=off, 1|true=Yes, 2=Yes or name also allowed)
* @property string $emailField Field name used for email login (when enabled).
* @property array $tfaRecRoleIDs Role IDs where admin prompts/recommends them to enable TFA.
* @property int $tfaRememberDays Allow user to remember their browser and bypass TFA for this many days (-1=no limit, 0=disabled)
* @property array $tfaRememberFingerprints Means by which to fingerprint user’s browser
* @property string $tfaAutoType Auto-enable type, aka module name (default='')
* @property array $tfaAutoRoleIDs Auto-enable for these role IDs, or blank for all roles. Applies only if $tfaAutoType selected (default=[])
*
* @method void beforeLogin() #pw-hooker
* @method void afterLogin() #pw-hooker
* @method string executeLogout() #pw-hooker
* @method string executeLoggedOut() #pw-hooker
* @method string afterLoginOutput() #pw-hooker
* @method void afterLoginRedirect($url = '') #pw-hooker
* @method string afterLoginURL($url = '') #pw-hooker
* @method string renderLoginForm() #pw-hooker
* @method InputfieldForm buildLoginForm() #pw-hooker
* @method void login($name, $pass) #pw-hooker
* @method void loginFailed($name, $message = '') #pw-hooker
* @method void loginSuccess(User $user) #pw-hooker
* @method void loginAttemptReady($name) #pw-hooker 3.0.223+
* @method void loginAttempted($user, $name) #pw-hooker 3.0.223+
* @method void loginFormProcessReady($form) #pw-hooker 3.0.223+
* @method void loginFormProcessed($form, $name) #pw-hooker 3.0.223+
* @method array getBeforeLoginVars() #pw-hooker
* @method array getLoginLinks() #pw-hooker
* @method string renderLoginLinks() #pw-hooker
*
*
*/
class ProcessLogin extends Process implements ConfigurableModule {
public static function getModuleInfo() {
return array(
'title' => 'Login',
'summary' => 'Login to ProcessWire',
'version' => 109,
'permanent' => true,
'permission' => 'page-view',
);
}
/**
* @var InputfieldText|InputfieldEmail
*
*/
protected $nameField;
/**
* @var InputfieldText
*
*/
protected $passField;
/**
* @var InputfieldSubmit
*
*/
protected $submitField;
/**
* @var InputfieldForm
*
*/
protected $form;
/**
* Requested page edit ID (no longer used, but kept in case anything else monitoring it)
*
* @var int
*
*/
protected $id;
/**
* Is this login form being used for admin login?
*
* @var bool
*
*/
protected $isAdmin = false;
/**
* URL to redirect to after login
*
* @var string
*
*/
protected $loginURL = '';
/**
* URL to redirect to after logout
*
* @var string
*
*/
protected $logoutURL = '';
/**
* Did user login with two factor authentication?
*
* @var bool
*
*/
protected $tfaLoginSuccess = false;
/**
* Cached value from useEmailLogin method
*
* @var bool|null
*
*/
protected $useEmailLogin = null;
/**
* Custom labels that override defaults, indexed by label name
*
* @var array
*
*/
protected $customLabels = array();
/**
* Login name as submitted (after sanitize)
*
* @var string
*
*/
protected $submitLoginName = '';
/**
* Configurable markup for this module
*
* @var array
*
*/
protected $customMarkup = array(
'error' => '<p class="ui-state-error-text">{out}</p>',
'login-link' => '<a href="{url}">{out}</a>',
'login-links' => '<p class="pw-login-links">{out}</p>',
'login-links-split' => ' <br />',
'forgot-icon' => '', // in constructor
'home-icon' => '', // in constructor
);
/**
* Construct
*
*/
public function __construct() {
$this->set('tfaRecRoleIDs', array());
$this->set('tfaRememberDays', 90);
$this->set('tfaRememberFingerprints', array('agentVL', 'accept', 'scheme', 'host'));
$this->set('tfaAutoType', '');
$this->set('tfaAutoRoleIDs', array());
$this->set('allowEmail', false);
$this->set('emailField', 'email');
$this->customMarkup['forgot-icon'] = wireIconMarkup('question-circle', 'fw');
$this->customMarkup['home-icon'] = wireIconMarkup('home', 'fw');
parent::__construct();
}
/**
* Build the login form
*
*/
public function init() {
$this->id = isset($_GET['id']) ? (int) $_GET['id'] : ''; // id no longer used as anything but a toggle (on/off)
$this->set('allowForgot', $this->modules->isInstalled('ProcessForgotPassword'));
$this->isAdmin = $this->wire()->page->template == 'admin';
$this->useEmailLogin = $this->useEmailLogin();
parent::init();
}
/**
* Get or set named label text
*
* @param string $name Label name
* @param null|string $value Specify value to replace label with custom value at runtime, otherwise omit
* @return string
* @since 3.0.154
*
*/
public function labels($name, $value = null) {
if($value !== null) $this->customLabels[$name] = $value;
if(isset($this->customLabels[$name])) return $this->customLabels[$name];
switch($name) { // alpha order
case 'continue': $label = $this->_('Continue'); break;
case 'edit-profile': $label = $this->_('Edit Profile'); break;
case 'email': $label = $this->_('Email'); break; // Email input label
case 'email-not-supported': $label = $this->_('Login is not supported for that email address.'); break;
case 'fail-cookie': $label = $this->_('Cookie check failed: please enable cookies to login.'); break;
case 'fail-javascript': $label = $this->_('Javascript check failed: please enable Javascript to login.'); break;
case 'forgot-password': $label = $this->_('Forgot your password?'); break;
case 'invalid-name': $label = $this->_('Invalid login name'); break;
case 'login': $label = $this->_('Login'); break; // Login submit button label
case 'login-failed': $label = $this->_('Login failed'); break;
case 'login-headline': $label = $this->_x('Login', 'headline'); break; // Login form headline
case 'logged-in': $label = $this->_('You are logged in.'); break;
case 'logged-out': $label = $this->_('You have logged out'); break;
case 'password': $label = $this->_('Password'); break; // Password input label
case 'username': $label = $this->_('Username'); break; // Username input label
case 'username-or-email': $label = $this->_('Username or Email'); break; // Name/email input label
default: $label = "Unknown label name: $name";
}
return $label;
}
/**
* Get or set custom markup
*
* @param string $name
* @param null|string $value
* @return string
* @since 3.0.154
*
*/
public function markup($name, $value = null) {
if($value !== null) $this->customMarkup[$name] = $value;
return isset($this->customMarkup[$name]) ? $this->customMarkup[$name] : "Unknown markup name: $name";
}
/**
* Use login by email?
*
* Returns false if no, int 1 of yes, int 2 if either email or name allowed
*
* @return bool|int
* @since 3.0.151
*
*/
public function useEmailLogin() {
if($this->useEmailLogin !== null) return $this->useEmailLogin;
if(!$this->allowEmail) return false;
if(!$this->emailField) return false;
/** @var Field $field */
$field = $this->wire()->fields->get($this->emailField);
if(!$field) return false;
if(!$field->type instanceof FieldtypeEmail) return false;
if(!$field->hasFlag(Field::flagUnique)) return false;
/** @var Template $template */
$template = $this->wire()->templates->get($this->wire()->config->userTemplateID);
if(!$template || !$template->hasField($field)) return false;
return (int) $this->allowEmail;
}
/**
* Set URL to redirect to after login success
*
* If not set, redirect will be back to the current page with a "login=1" GET variable.
* However, you should only check if the user is logged in with if($user->isLoggedin()).
*
* @param $url
* @return $this
* @throws WireException if given invalid URL
*
*/
public function setLoginURL($url) {
$url = $this->wire()->sanitizer->url($url, array('throw' => true));
$this->loginURL = $url;
return $this;
}
/**
* Set URL to redirect to after logout success
*
* If not set, redirect will be back to the current page with a "logout=2" GET variable.
*
* @param $url
* @return $this
* @throws WireException if given invalid URL
*
*/
public function setLogoutURL($url) {
$url = $this->wire()->sanitizer->url($url, array('throw' => true));
$this->logoutURL = $url;
return $this;
}
/**
* Set cache control headers to prevent caching
*
* Note that PHP already does this, but if someone has overridden PHP’s default settings
* then these ones will apply. This is in order to prevent a cached copy of the login form
* from being used since the login form is rendered prior to login session.
*
*/
protected function setCacheHeaders() {
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
}
/**
* Check if login posted and attempt login, otherwise render the login form
*
* @return string
*
*/
public function ___execute() {
$session = $this->wire()->session;
$input = $this->wire()->input;
$user = $this->wire()->user;
if($user->isLoggedin()) {
if($this->loginURL && !$input->get('login')) {
$this->afterLoginRedirect($this->loginURL);
}
if($input->get('layout')) return ''; // blank placeholder page option for admin themes
$this->message($this->labels('logged-in'));
if($this->isAdmin && $user->hasPermission('page-edit') && !$input->get('login')) {
$this->afterLoginRedirect();
}
// fallback if nothing set
return $this->afterLoginOutput();
} else if($input->urlSegmentStr() === 'logout') {
$session->location('../');
}
$tfa = $this->getTfa();
if($tfa && $tfa->active()) {
// two factor authentication
if($tfa->success()) {
$this->tfaLoginSuccess = true;
$this->loginSuccess($this->wire()->user);
$this->afterLoginRedirect('./');
} else {
return $tfa->render();
}
} else if($input->get('forgot') && $this->allowForgot) {
/** @var ProcessForgotPassword $process */
$process = $this->modules->get('ProcessForgotPassword');
if($this->useEmailLogin()) $process->askEmail = true;
return $process->execute();
}
$this->buildLoginForm();
$loginSubmit = $input->post('login_submit');
if(!$loginSubmit) {
$this->beforeLogin();
return $this->renderLoginForm();
}
$this->loginFormProcessReady($this->form);
$this->form->processInput($input->post);
// at this point login form has been submitted
$name = $this->getLoginName();
$pass = substr($this->passField->attr('value'), 0, 128);
$this->loginFormProcessed($this->form, $name);
if(!$name || !$pass) return $this->renderLoginForm();
// vars to copy from non-logged in session to logged-in session
$session->setFor($this, 'copyVars', array(
'hidpi' => $input->post('login_hidpi') ? true : false,
'touch' => $input->post('login_touch') ? true : false,
'clientWidth' => (int) $input->post('login_width'),
));
if($tfa) $tfa->start($name, $pass);
$this->login($name, $pass);
return $this->renderLoginForm();
}
/**
* Get Tfa instance or null if not applicable
*
* @return null|Tfa
* @since 3.0.160
*
*/
public function getTfa() {
$tfas = $this->wire()->modules->findByPrefix('Tfa');
if(!count($tfas)) return null;
$tfa = new Tfa();
$this->wire($tfa);
$tfa->rememberDays = $this->tfaRememberDays;
$tfa->rememberFingerprints = $this->tfaRememberFingerprints;
$tfa->autoType = $this->tfaAutoType && $this->tfaAutoType !== '0' ? $this->tfaAutoType : '';
$tfa->autoRoleIDs = $this->tfaAutoRoleIDs;
return $tfa;
}
/**
* Get login username (whether email or name used)
*
* @return string|bool
* @since 3.0.151
*
*/
protected function getLoginName() {
$sanitizer = $this->wire()->sanitizer;
$config = $this->wire()->config;
$users = $this->wire()->users;
$value = $this->nameField->attr('value');
if(!strlen($value)) return false;
$originalValue = $value;
if(!$this->useEmailLogin() || !strpos($value, '@')) {
$value = $this->sanitizer->pageNameUTF8($value);
$this->submitLoginName = $value;
if($originalValue !== $value && strtolower($originalValue) !== $value) {
// if sanitizer changed anything about the value (other than case) do not accept it
$this->loginFailed($value, $this->labels('invalid-name'));
$value = false;
}
return $value;
}
// at this point we are dealing with an email login
$value = strtolower($sanitizer->email($value));
$this->submitLoginName = $value;
if(empty($value)) return false;
if(strtolower($originalValue) !== $value) {
// if sanitizer changed anything about the email (not likely) do not accept it
$this->loginFailed($value, $this->labels('invalid-name'));
return false;
}
$error = $this->labels('email-not-supported');
$items = $users->find("include=all, $this->emailField=" . $sanitizer->selectorValue($value));
if(!$items->count()) {
// fail: no matches
$this->loginFailed($value);
return false;
} else if($items->count() > 1) {
// fail: more than one match
if($config->debug) $error .= ' (not unique)';
$this->loginFailed($value, $error);
return false;
}
// success: single match
$user = $items->first();
if($user->status > Page::statusHidden) {
// hidden, unpublished, trash
if($config->debug) $error .= ' (inactive)';
$this->loginFailed($value, $error);
return false;
}
return $user->name;
}
/**
* Determine the after login URL and page, then populate to session to pick up after login
*
* @since 3.0.167
*
*/
protected function determineAfterLoginUrl() {
$input = $this->wire()->input;
$session = $this->wire()->session;
// if we’ve already done this then exit early
if($session->getFor($this, 'afterLoginPageId') !== null) return;
// ProcessPageView sets a loginRequestPageID variable to its session
// this is the ID of the page that access control blocked and sent user to login
$requestPageId = (int) $session->getFor('ProcessPageView', 'loginRequestPageID');
if(!$requestPageId || $requestPageId === $this->wire()->page->id) return;
// load the requested page
$requestPage = $this->wire()->pages->get($requestPageId);
if(!$requestPage->id) {
$session->setFor($this, 'afterLoginPageId', 0);
return;
}
if($requestPage->process) {
// admin: this is likely an admin page with a Process module
$process = (string) $requestPage->process;
if(!$process || $process === "ProcessLogin") return;
$className = $this->wire()->modules->getModuleClass($process, true);
if(!$className || !class_exists($className)) return;
$url = call_user_func_array("$className::getAfterLoginUrl", array($requestPage));
} else {
// front-end
$url = '';
}
if(empty($url)) {
$url = $session->getFor('ProcessPageView', 'loginRequestURL');
} else {
// common integer GET vars in admin to identify if present and not already in $url
foreach(array('id', 'modal') as $name) {
$value = $input->get($name);
if($value === null || !ctype_digit("$value")) continue; // not an integer
if(preg_match('/[&?]' . $name . '=/', $url)) continue; // already present
$url .= (strpos($url, '?') ? '&' : '?') . "$name=" . ((int) $value);
}
}
// set what we found to session
$session->setFor($this, 'afterLoginUrl', $url);
$session->setFor($this, 'afterLoginPageId', $requestPage->id);
}
/**
* Perform login and redirect on success
*
* @param string $name
* @param string $pass
* @return bool Returns false on fail, performs redirect on success
*
*/
public function ___login($name, $pass) {
$session = $this->wire()->session;
$input = $this->wire()->input;
$this->loginAttemptReady($name);
if($name && $pass) {
$loginUser = $session->login($name, $pass);
} else {
$loginUser = false;
}
$this->loginAttempted($loginUser, $name);
if($loginUser && $loginUser->id) {
$this->loginSuccess($loginUser);
$url = $input->urlSegment1 === 'navJSON' ? '../' : './';
$this->afterLoginRedirect($url);
} else {
$this->loginFailed($this->submitLoginName ? $this->submitLoginName : $name);
}
return false;
}
/**
* Log the user out
*
* @return string
*
*/
public function ___executeLogout() {
if($this->logoutURL) {
$url = $this->logoutURL;
} else if($this->isAdmin || $this->wire()->page->template->name === 'admin') {
$url = $this->wire()->config->urls->admin . './?loggedout=1';
} else {
$url = "./?logout=2";
}
$session = $this->wire()->session;
$session->logout();
$session->redirect($url, false);
return '';
}
/**
* Check that sessions can be initiated and attempt to rectify situation if not
*
* Happens only on the admin login form.
*
*/
protected function ___beforeLogin() {
$session = $this->wire()->session;
$beforeLoginVars = $this->getBeforeLoginVars();
$session->setFor($this, 'beforeLoginVars', $beforeLoginVars);
// check if Process module provides an after login URL that it wants us to use
$this->determineAfterLoginUrl();
// if checks already completed don't run them again
if($session->getFor($this, 'beforeLoginChecks')) return;
$modules = $this->wire()->modules;
$config = $this->wire()->config;
$input = $this->wire()->input;
$files = $this->wire()->files;
$log = $this->wire()->log;
// any remaining checks only if currently in the admin
if(!$this->isAdmin) return;
if( ini_get('session.save_handler') == 'files'
&& !$modules->isInstalled('SessionHandlerDB')
&& !$input->get('db')
) {
$installSessionDB = false;
$path = $config->paths->sessions;
$error = '';
if(!file_exists($path)) {
$files->mkdir($path);
clearstatcache();
if(file_exists($path)) {
$log->message("Created session path $path");
} else {
$installSessionDB = true;
$error = "Session path $path does not exist and we are unable to create it.";
}
}
if(!is_writable($path)) {
$files->chmod($path);
clearstatcache();
if(is_writable($path)) {
$log->message("Updated session path to be writable $path");
} else {
$installSessionDB = true;
$error = "Unable to write to session path $path, and unable to fix the permissions.";
}
}
// if we can't get file-based sessions going, switch to database sessions to ensure admin can login
if($installSessionDB) {
if($error) $log->error($error);
if($modules->get('SessionHandlerDB')) {
$log->error("Installed SessionHandlerDB as an alternate session handler. If you wish to uninstall this, do so after correcting the session path error.");
$session->redirect("./?db=1"); // db param to prevent potential infinite redirect
} else {
$log->error("Unable to install alternate session handler module SessionHandlerDB");
$this->error("Session write error. Login may not be possible.");
}
}
}
$session->setFor($this, 'beforeLoginChecks', 1);
}
/**
* Hook called after login
*
* Notify admin if there are any issues that need their attention.
* Happens only on the admin login form after superuser login.
*
*/
protected function ___afterLogin() {
if($this->wire()->user->isSuperuser()) {
/** @var SystemUpdater $systemUpdater */
$systemUpdater = $this->wire()->modules->get('SystemUpdater');
if($systemUpdater) {
$updatesApplied = $systemUpdater->getUpdatesApplied();
$checks = $systemUpdater->getChecks();
$checks->setShowNotices(true);
//$checks->setTestAll(true);
if(count($updatesApplied)) {
$checks->checkWelcome();
$this->message(
sprintf(
$this->_('Skipping after-login system checks because updates were applied (%s)'),
implode(', ', $updatesApplied)
),
Notice::debug
);
} else {
$checks->execute();
}
}
}
}
/**
* Build the login form
*
* @return InputfieldForm
*
*/
protected function ___buildLoginForm() {
$modules = $this->wire()->modules;
$useEmailLogin = $this->useEmailLogin();
$nameInputType = 'InputfieldText';
$nameInputLabel = $this->labels('username'); // Login form: username field label
if($useEmailLogin === 1) {
$nameInputType = 'InputfieldEmail';
$nameInputLabel = $this->labels('email'); // Login form: email field label
} else if($useEmailLogin === 2) {
$nameInputLabel = $this->labels('username-or-email'); // Login form: username OR email field label
}
$this->nameField = $modules->get($nameInputType);
$this->nameField->label = $nameInputLabel;
$this->nameField->attr('id+name', 'login_name');
$this->nameField->attr('class', $this->className() . 'Name');
$this->nameField->addClass('InputfieldFocusFirst');
$this->nameField->collapsed = Inputfield::collapsedNever;
$this->passField = $modules->get('InputfieldText');
$this->passField->set('label', $this->labels('password')); // Login form: password field label
$this->passField->attr('id+name', 'login_pass');
$this->passField->attr('type', 'password');
$this->passField->attr('class', $this->className() . 'Pass');
$this->passField->collapsed = Inputfield::collapsedNever;
$this->submitField = $modules->get('InputfieldSubmit');
$this->submitField->attr('name', 'login_submit');
$this->submitField->attr('value', $this->labels('login')); // Login form: submit login button
$this->form = $modules->get('InputfieldForm');
// we'll retain an ID field in the GET url, if it was there (note: no longer used as anything but a toggle on/off)
$this->form->attr('action', "./" . ($this->id ? "?id=$this->id" : ''));
$this->form->addClass('InputfieldFormFocusFirst');
$this->form->attr('id', $this->className() . 'Form');
$this->form->add($this->nameField);
$this->form->add($this->passField);
$this->form->add($this->submitField);
if($this->isAdmin) {
// detect hidpi at login (populated from js)
/** @var InputfieldHidden $f */
$f = $modules->get('InputfieldHidden');
$f->attr('id+name', 'login_hidpi');
$f->attr('value', 0);
$this->form->add($f);
// detect touch device login (populated from js)
/** @var InputfieldHidden $f */
$f = $modules->get('InputfieldHidden');
$f->attr('id+name', 'login_touch');
$f->attr('value', 0);
$this->form->add($f);
// detect touch device login (populated from js)
/** @var InputfieldHidden $f */
$f = $modules->get('InputfieldHidden');
$f->attr('id+name', 'login_width');
$f->attr('value', 0);
$this->form->add($f);
}
/** @var InputfieldHidden $f */
$f = $modules->get('InputfieldHidden');
$f->attr('id+name', 'login_start');
$f->val(gmdate('U')); // GMT/UTC unix timestamp of when login form was rendered
$this->form->add($f);
$s = 'script';
$jsError = str_replace('{out}', $this->labels('fail-javascript'), $this->markup('error'));
$cookieError = str_replace(array('{out}', "'"), array($this->labels('fail-cookie'), '"'), $this->markup('error'));
$this->form->prependMarkup .= "<$s>if(!navigator.cookieEnabled) document.write('$cookieError');</$s>";
if($this->isAdmin) $this->form->prependMarkup .= "<no$s>$jsError</no$s>";
return $this->form;
}
/**
* Render the login form
*
* @return string
*
*/
protected function ___renderLoginForm() {
$loggedIn = $this->wire()->user->isLoggedin();
$out = '';
if($this->wire()->input->get('login') && $loggedIn) {
// redirect to page after login
$this->afterLoginRedirect();
} else if($loggedIn) {
// user is already logged in, do nothing
} else {
// render login form
if($this->isAdmin) $this->setCacheHeaders();
// note the space after 'Login ' is intentional to separate it from the Login button for translation purposes
$this->headline($this->labels('login-headline')); // Headline for login form page
$this->passField->attr('value', '');
$out = $this->form->render();
$links = $this->getLoginLinks();
if(count($links)) {
$out .= str_replace('{out}', implode($this->markup('login-links-split'), $links), $this->markup('login-links'));
}
if(!$this->wire()->modules->isInstalled('InputDetect')) {
$config = $this->wire()->config;
$config->scripts->prepend($config->urls('ProcessLogin') . 'what-input.min.js');
}
}
return $out;
}
/**
* Get array of links to display under login form
*
* Each item in returned array must be entire `<a>` tag for link
*
* #pw-hooker
*
* @return array
* @since 3.0.154
*
*/
protected function ___getLoginLinks() {
$links = array();
$markup = $this->markup('login-link');
if($this->allowForgot) {
$icon = $this->markup('forgot-icon');
$label = $this->labels('forgot-password');
$links['forgot'] = str_replace(
array('{url}', '{out}'),
array('./?forgot=1', "$icon $label"),
$markup
);
}
$home = $this->pages->get('/');
$icon = $this->markup('home-icon');
$label = $this->wire()->sanitizer->entities($home->getUnformatted('title'));
$links['home'] = str_replace(
array('{url}', '{out}'),
array($home->url, "$icon $label"),
$markup
);
return $links;
}
/**
* Output that appears if there is nowhere to redirect to after login
*
* Called only if login originated from the actual login page, OR if user does not have page-edit permission
* and thus can’t browse around in the admin.
*
* This method is not often used since it’s more common and recommended to redirect after login.
*
* @return string
*
*/
protected function ___afterLoginOutput() {
$config = $this->wire()->config;
/** @var InputfieldButton $btn */
$btn = $this->wire()->modules->get('InputfieldButton');
if($this->wire()->user->hasPermission('profile-edit')) {
$btn->value = $this->labels('edit-profile');
$btn->href = $config->urls->admin . 'profile/';
} else {
$btn->value = $this->labels('continue');
$btn->href = $config->urls->root;
}
return "<p>" . $btn->render() . "</p>";
}
/**
* Redirect to admin root after login
*
* @param string $url
*
*/
protected function ___afterLoginRedirect($url = '') {
$url = $this->afterLoginURL($url);
$session = $this->wire()->session;
$session->removeFor($this, 'beforeLoginVars');
$session->removeFor($this, 'beforeLoginChecks');
$session->removeFor($this, 'afterLoginUrl');
$session->removeFor($this, 'afterLoginPageId');
$session->removeFor('ProcessPageView', 'loginRequestPageID');
$session->removeFor('ProcessPageView', 'loginRequestURL');
if(strpos($url, '/navJSON') !== false) $url = str_replace(array('/navJSON/', '/navJSON'), '/', $url);
$session->redirect($url, false);
}
/**
* Hooks can modify the redirect URL with this hook
*
* #pw-hooker
* #pw-internal
*
* @param string $url
* @return string
*
*/
public function ___afterLoginURL($url = '') {
$session = $this->wire()->session;
$afterLoginUrl = $session->getFor($this, 'afterLoginUrl');
$id = (int) $session->getFor($this, 'afterLoginPageId');
if($afterLoginUrl) {
$page = $id ? $this->wire()->pages->get($id) : new NullPage();
if(!$page->id || $page->viewable()) return $afterLoginUrl;
}
if(empty($url)) {
$user = $this->wire()->user;
if($this->loginURL) {
$url = $this->loginURL;
} else if($this->isAdmin && $user->isLoggedin() && $user->hasPermission('page-edit')) {
if($this->id || ((string) $this->wire()->process) !== $this->className()) {
$url = './';
} else {
$url = $this->wire()->config->urls->admin . 'page/';
}
} else {
$url = './';
}
}
$beforeLoginVars = $session->getFor($this, 'beforeLoginVars');
if(!is_array($beforeLoginVars)) $beforeLoginVars = array();
if(!isset($beforeLoginVars['login'])) $beforeLoginVars['login'] = 1;
$a = array();
foreach($beforeLoginVars as $name => $value) {
if(strpos($url, "?$name=") !== false || strpos($url, "&$name=") !== false) continue; // skip if overridden
$a[$name] = $value;
}
if(count($a)) {
$url .= strpos($url, '?') !== false ? '&' : '?';
$url .= http_build_query($a);
}
return $url;
}
/**
* Get validated/sanitized variables in the query string for not logged-in user to retain after login
*
* Hook this if you need to add more than 'id' but make sure anything populated
* to the return value is fully validated and sanitized.
*
* @return array Associative array of variables
*
*/
public function ___getBeforeLoginVars() {
$session = $this->wire()->session;
$vars = $session->getFor($this, 'beforeLoginVars');
if(!is_array($vars)) $vars = array();
$id = $this->wire()->input->get('id');
if($id !== null) $vars['id'] = $this->wire()->sanitizer->intUnsigned($id);
return $vars;
}
/**
* Hook called right before a login is attempted
*
* #pw-hooker
*
* @param string $name
* @since 3.0.223
*
*/
protected function ___loginAttemptReady($name) {}
/**
* Hook called immediately after a login was attempted
*
* #pw-hooker
*
* @param User|false $user This will be User object on success, or false on fail
* @param string $name Attempted login name
* @since 3.0.223
*
*/
protected function ___loginAttempted($user, $name) {}
/**
* Hook called immediately before the login form in processed
*
* #pw-hooker