-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBaseController.php
1142 lines (902 loc) · 40.6 KB
/
BaseController.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);
namespace SlimMvcTools\Controllers;
use \Psr\Http\Message\ServerRequestInterface,
\Psr\Http\Message\ResponseInterface,
\SlimMvcTools\ContainerKeys,
\SlimMvcTools\Utils;
/**
* A base controller class that should be extended to build mvc controllers
* in https://github.com/rotexsoft/slim-skeleton-mvc-app applications.
* There is a command-line tool for building such controllers.
*
* @author Rotimi Adegbamigbe
*/
class BaseController
{
/**
* View object for rendering layout files.
*/
protected \Rotexsoft\FileRenderer\Renderer $layout_renderer;
/**
* View object for rendering view files associated with controller actions.
*/
protected \Rotexsoft\FileRenderer\Renderer $view_renderer;
/**
* An auth object used by the following methods of this class:
* - isLoggedIn
* - actionLogin
* - doLogin
* - actionLogout
* - actionLoginStatus
*/
protected \Vespula\Auth\Auth $vespula_auth;
/**
* Object for getting locale specific translations of text to be displayed
*/
protected \Vespula\Locale\Locale $vespula_locale;
/**
* @psalm-suppress PossiblyUnusedMethod
*/
public function getVespulaLocale(): \Vespula\Locale\Locale {
return $this->vespula_locale;
}
/**
* @psalm-suppress PossiblyUnusedMethod
*/
public function setVespulaLocale(\Vespula\Locale\Locale $nu_locale): self {
$this->vespula_locale = $nu_locale;
return $this;
}
/**
* Object for logging events
*/
protected \Psr\Log\LoggerInterface $logger;
/**
* @psalm-suppress PossiblyUnusedMethod
*/
public function getLogger(): \Psr\Log\LoggerInterface {
return $this->logger;
}
/**
* @psalm-suppress PossiblyUnusedMethod
*/
public function setLogger(\Psr\Log\LoggerInterface $nu_logger): self {
$this->logger = $nu_logger;
return $this;
}
/**
* Will be used in actionLogin() to construct the url to redirect to upon successful login,
* if $_SESSION[self::SESSN_PARAM_LOGIN_REDIRECT] is not set.
*/
protected string $login_success_redirect_action = 'login-status';
/**
* @psalm-suppress PossiblyUnusedMethod
*/
public function getLoginSuccessRedirectAction(): string {
return $this->login_success_redirect_action;
}
/**
* Will be used in actionLogin() to construct the url to redirect to upon successful login,
* if $_SESSION[self::SESSN_PARAM_LOGIN_REDIRECT] is not set.
*/
protected string $login_success_redirect_controller = 'base-controller';
/**
* @psalm-suppress PossiblyUnusedMethod
*/
public function getLoginSuccessRedirectController(): string {
return $this->login_success_redirect_controller;
}
/**
* The action section of the url.
*
* It should be set to an empty string if the action was not specified via the url
*
* Eg. http://localhost/slim-skeleton-mvc-app/public/base-controller/action-index
* will result in $this->action_name_from_uri === 'action-index'
*
* http://localhost/slim-skeleton-mvc-app/public/base-controller/
* will result in $this->action_name_from_uri === ''
*/
protected string $action_name_from_uri = '';
/**
* @psalm-suppress PossiblyUnusedMethod
*/
public function getActionNameFromUri(): string {
return $this->action_name_from_uri;
}
/**
* The controller section of the url.
*
* It should be set to an empty string if the controller was not specified via the url
*
* Eg. http://localhost/slim-skeleton-mvc-app/public/base-controller/action-index
* will result in $this->controller_name_from_uri === 'base-controller'
*
* http://localhost/slim-skeleton-mvc-app/public/
* will result in $this->controller_name_from_uri === ''
*/
protected string $controller_name_from_uri = '';
/**
* @psalm-suppress PossiblyUnusedMethod
*/
public function getControllerNameFromUri(): string {
return $this->controller_name_from_uri;
}
/**
* The name of the layout file that will be rendered by $this->layout_renderer inside
* $this->renderLayout(..)
*/
protected string $layout_template_file_name = 'main-template.php';
//////////////////////////////////
// Constants
//////////////////////////////////
public const GET_QUERY_PARAM_SELECTED_LANG = 'selected_lang';
//////////////////////////////////
// Session Parameter keys
//////////////////////////////////
public const SESSN_PARAM_LOGIN_REDIRECT = self::class . '_login_redirect_path';
// This item in the session represents the current language selected by the user
public const SESSN_PARAM_CURRENT_LOCALE_LANG = self::class . '_current_locale_language';
/**
* @psalm-suppress PossiblyUnusedMethod
*/
public function __construct(
/**
* A container object containing dependencies needed by the controller.
*/
protected \Psr\Container\ContainerInterface $container,
string $controller_name_from_uri,
string $action_name_from_uri,
/**
* Request Object
*/
protected \Psr\Http\Message\ServerRequestInterface $request,
/**
* Response Object
*/
protected \Psr\Http\Message\ResponseInterface $response
) {
$this->action_name_from_uri = ($action_name_from_uri !== '') ? $action_name_from_uri : $this->action_name_from_uri;
$this->controller_name_from_uri = ($controller_name_from_uri !== '') ? $controller_name_from_uri : $this->controller_name_from_uri;
/** @psalm-suppress MixedAssignment */
$this->logger = $this->getContainerItem(ContainerKeys::LOGGER);
/** @psalm-suppress MixedAssignment */
$this->vespula_locale = $this->getContainerItem(ContainerKeys::LOCALE_OBJ);
/** @psalm-suppress MixedAssignment */
$this->vespula_auth = $this->getContainerItem(ContainerKeys::VESPULA_AUTH);
/**
* @psalm-suppress MixedAssignment
*/
$this->layout_renderer = $this->getContainerItem(ContainerKeys::LAYOUT_RENDERER);
/**
* @psalm-suppress MixedAssignment
*/
$this->view_renderer = $this->getContainerItem(ContainerKeys::VIEW_RENDERER);
$uri_path = ($this->request->getUri() instanceof \Psr\Http\Message\UriInterface)
? $this->request->getUri()->getPath() : '';
if(
( ($this->controller_name_from_uri === '') || ($this->action_name_from_uri === '') )
&& ( ($uri_path !== '') && ($uri_path !== '/') && (str_contains($uri_path, '/')) )
) {
// Calculate $this->controller_name_from_uri and / or
// $this->action_name_from_uri if necessary
if( $uri_path[0] === '/' ) {
// Remove leading slash /
$uri_path = substr($uri_path, 1);
}
$uri_path_parts = explode('/', $uri_path);
if( ($this->controller_name_from_uri === '') ) {
$this->controller_name_from_uri = $uri_path_parts[0];
}
if( count($uri_path_parts) >= 2 && ($this->action_name_from_uri === '') ) {
$this->action_name_from_uri = $uri_path_parts[1];
}
}
$this->storeCurrentUrlForLoginRedirection();
$this->updateSelectedLanguage();
}
protected function startSession(): void {
$session_start_settings =
$this->getAppSetting('session_start_options') !== null
? (array)$this->getAppSetting('session_start_options')
: [];
if(isset($session_start_settings['name'])) {
session_name((string)$session_start_settings['name']);
}
session_start($session_start_settings);
}
/**
* @psalm-suppress InvalidScalarArgument
*/
public function updateSelectedLanguage() : void {
$query_params = $this->request->getQueryParams();
/**
* @psalm-suppress MixedArgument
*/
if(
array_key_exists(self::GET_QUERY_PARAM_SELECTED_LANG, $query_params)
&& in_array(
$query_params[self::GET_QUERY_PARAM_SELECTED_LANG],
$this->getContainerItem(ContainerKeys::VALID_LOCALES)
)
) {
// User specified a language in the uri which is an acceptable
// language defined for this application
/**
* @psalm-suppress MixedArgument
*/
$this->vespula_locale->setCode($query_params[self::GET_QUERY_PARAM_SELECTED_LANG]);
if (session_status() !== \PHP_SESSION_ACTIVE) {
$this->startSession();
}
// also store in session
/**
* @psalm-suppress MixedAssignment
*/
$_SESSION[self::SESSN_PARAM_CURRENT_LOCALE_LANG] =
$query_params[self::GET_QUERY_PARAM_SELECTED_LANG];
} elseif (
session_status() === \PHP_SESSION_ACTIVE
&& array_key_exists(self::SESSN_PARAM_CURRENT_LOCALE_LANG, $_SESSION)
) {
$this->vespula_locale->setCode($_SESSION[self::SESSN_PARAM_CURRENT_LOCALE_LANG]);
}
// else { // default lang is already preconfigured in dependencies file }
}
/**
* @psalm-suppress PossiblyUnusedMethod
*/
public function getVespulaAuthObject(): \Vespula\Auth\Auth {
return $this->vespula_auth;
}
/**
* @psalm-suppress PossiblyUnusedMethod
*/
public function setVespulaAuthObject(\Vespula\Auth\Auth $vespula_auth): self {
$this->vespula_auth = $vespula_auth;
return $this;
}
/**
* @psalm-suppress PossiblyUnusedMethod
*/
public function getLayoutRenderer(): \Rotexsoft\FileRenderer\Renderer {
return $this->layout_renderer;
}
/**
* @psalm-suppress PossiblyUnusedMethod
*/
public function setLayoutRenderer(\Rotexsoft\FileRenderer\Renderer $renderer): self {
$this->layout_renderer = $renderer;
return $this;
}
/**
* @psalm-suppress PossiblyUnusedMethod
*/
public function getViewRenderer(): \Rotexsoft\FileRenderer\Renderer {
return $this->view_renderer;
}
/**
* @psalm-suppress PossiblyUnusedMethod
*/
public function setViewRenderer(\Rotexsoft\FileRenderer\Renderer $renderer): self {
$this->view_renderer = $renderer;
return $this;
}
/**
* @psalm-suppress PossiblyUnusedMethod
*/
public function getRequest():\Psr\Http\Message\ServerRequestInterface {
return $this->request;
}
/**
* @psalm-suppress PossiblyUnusedMethod
*/
public function setRequest(\Psr\Http\Message\ServerRequestInterface $request): self {
$this->request = $request;
return $this;
}
/**
* @psalm-suppress PossiblyUnusedMethod
*/
public function getResponse(): \Psr\Http\Message\ResponseInterface {
return $this->response;
}
public function setResponse(\Psr\Http\Message\ResponseInterface $response): self {
$this->response = $response;
return $this;
}
/** @psalm-suppress MixedInferredReturnType */
public function getAppBasePath(): string {
/**
* @psalm-suppress MixedArrayAccess
* @psalm-suppress MixedReturnStatement
*/
return $this->getAppSetting('app_base_path');
}
/**
* @return mixed
*/
public function getAppSetting(string $setting_key) {
/**
* @psalm-suppress MixedAssignment
*/
$settings = $this->getContainerItem(ContainerKeys::APP_SETTINGS);
/**
* @psalm-suppress MixedArrayAccess
*/
return $settings[$setting_key] ?? null;
}
public function makeLink(string $path): string {
return rtrim($this->getAppBasePath(), '/') . '/' . ltrim($path, '/');
}
/**
* Executes a PHP file and returns its output as a string. This file is
* supposed to contain the layout template of your site.
*
* @param string $file_name name of the file (including extension eg. `read.php`)
* containing valid php to be executed and returned as
* string.
* @param array $data an array of data to be passed to the layout file. Each
* key in this array is automatically converted to php
* variables accessible in the layout file.
* Eg. passing ['content'=>'yabadabadoo'] to this method
* will result in a variable named $content (with a
* value of 'yabadabadoo') being available in the layout
* file (i.e. the file named $file_name).
*
* @psalm-suppress MixedInferredReturnType
*/
public function renderLayout( string $file_name, array $data = ['content'=>'Content should be placed here!'] ): string {
$self = $this;
$data['sMVC_MakeLink'] = fn(string $path): string => $self->makeLink($path);
$data['controller_object'] = $this;
/**
* @psalm-suppress MixedAssignment
*/
$this->layout_renderer = $this->getContainerItem(ContainerKeys::LAYOUT_RENDERER); // get new instance for each call to this method renderLayout
/**
* @psalm-suppress MixedReturnStatement
* @psalm-suppress MixedMethodCall
*/
return $this->layout_renderer->renderToString($file_name, $data);
}
/**
* Executes a PHP file and returns its output as a string. This file is
* supposed to contain the output markup (usually html) for the current
* controller action method being executed.
*
* @param string $file_name name of the file (including extension eg. `read.php`)
* containing valid php to be executed and returned as
* string.
* @param array $data an array of data to be passed to the view file. Each
* key in this array is automatically converted to php
* variables accessible in the view file.
* Eg. passing ['content'=>'yabadabadoo'] to this method
* will result in a variable named $content (with a
* value of 'yabadabadoo') being available in the view
* file (i.e. the file named $file_name).
*
* @psalm-suppress MixedInferredReturnType
*/
public function renderView( string $file_name, array $data = [] ): string {
$parent_classes = [];
$parent_class = get_parent_class($this);
/**
* @psalm-suppress MixedAssignment
*/
$this->view_renderer = $this->getContainerItem(ContainerKeys::VIEW_RENDERER); // get new instance for each call to this method renderView
while( $parent_class !== self::class && ($parent_class !== '' && $parent_class !== false) ) {
$parent_classes[] =
(new \ReflectionClass($parent_class))->getShortName();
$parent_class = get_parent_class($parent_class);
}
//Try to prepend view folder for this controller.
//It takes precedence over the view folder
//for the base controller.
$ds = DIRECTORY_SEPARATOR;
/** @psalm-suppress UndefinedConstant */
$path_2_view_files = SMVC_APP_ROOT_PATH.$ds.'src'.$ds.'views'.$ds;
while ( $parent_class = array_pop($parent_classes) ) {
$parent_class_folder = \SlimMvcTools\Functions\Str\toDashes($parent_class);
/** @psalm-suppress MixedMethodCall */
if(
!$this->view_renderer->hasPath($path_2_view_files . $parent_class_folder)
&& file_exists($path_2_view_files . $parent_class_folder)
) {
/** @psalm-suppress MixedMethodCall */
$this->view_renderer->prependPath($path_2_view_files . $parent_class_folder);
}
}
//finally add my view folder
/** @psalm-suppress MixedMethodCall */
if(
$this->controller_name_from_uri !== ''
&& !$this->view_renderer->hasPath($path_2_view_files . $this->controller_name_from_uri)
&& file_exists($path_2_view_files . $this->controller_name_from_uri)
) {
/** @psalm-suppress MixedMethodCall */
$this->view_renderer->prependPath($path_2_view_files . $this->controller_name_from_uri);
}
$self = $this;
$data['sMVC_MakeLink'] = fn(string $path): string => $self->makeLink($path);
$data['controller_object'] = $this;
/**
* @psalm-suppress MixedReturnStatement
* @psalm-suppress MixedMethodCall
*/
return $this->view_renderer->renderToString($file_name, $data);
}
/**
* @psalm-suppress PossiblyUnusedMethod
*/
public function actionIndex(): ResponseInterface|string {
//get the contents of the view first
$view_str = $this->renderView('index.php', ['controller_object'=>$this]);
return $this->renderLayout( $this->layout_template_file_name, ['content'=>$view_str] );
}
/**
* Display an HTML table containing all the potential MVC routes in the application
*
* @param bool $onlyPublicMethodsPrefixedWithAction true to include only public methods prefixed with `action`
* or false to include all public methods
* @param bool $stripActionPrefixFromMethodName true to strip the `action-` prefix from methods displayed or false to leave the `action-` prefix
*
* @psalm-suppress PossiblyUnusedMethod
*/
public function actionRoutes($onlyPublicMethodsPrefixedWithAction=true, $stripActionPrefixFromMethodName=true): ResponseInterface|string {
$resp = $this->getResponseObjForLoginRedirectionIfNotLoggedIn();
if($resp instanceof \Psr\Http\Message\ResponseInterface) {
return $resp;
}
ini_set('memory_limit', '256M');
ini_set('max_execution_time', '0');
/** @psalm-suppress RedundantCastGivenDocblockType */
$view_str = $this->renderView(
'controller-classes-by-action-methods-report.php',
[
'onlyPublicMethodsPrefixedWithAction'=> ((bool)$onlyPublicMethodsPrefixedWithAction),
'stripActionPrefixFromMethodName'=> ((bool)$stripActionPrefixFromMethodName),
]
);
return $this->renderLayout( $this->layout_template_file_name, ['content'=>$view_str] );
}
/**
* @psalm-suppress PossiblyUnusedMethod
*/
public function actionLogin(): ResponseInterface|string {
$data_4_login_view = [
'controller_object' => $this, 'error_message' => '',
'username' => '', 'password' => ''
];
if( strtoupper($this->request->getMethod()) === 'GET' ) {
//show login form
//get the contents of the view first
$view_str = $this->renderView('login.php', $data_4_login_view);
return $this->renderLayout( $this->layout_template_file_name, ['content' => $view_str]);
} else {
//this is a POST request, process login
$controller = $this->login_success_redirect_controller ?: 'base-controller';
// SMVC_APP_AUTO_PREPEND_ACTION_TO_ACTION_METHOD_NAMES === true
// means that links generated in this action do not need to be prefixed
// with action- since when users click on them, the framework will
// automatically append action to the resolved method name
// see \SlimMvcTools\MvcRouteHandler::__invoke(...)
/** @psalm-suppress UndefinedConstant */
$prepend_action = !SMVC_APP_AUTO_PREPEND_ACTION_TO_ACTION_METHOD_NAMES;
$action = (
$prepend_action
&& !str_starts_with(mb_strtolower($this->login_success_redirect_action, 'UTF-8'), 'action')
)
? 'action-' : '';
$success_redirect_path =
$this->makeLink("{$controller}/{$action}{$this->login_success_redirect_action}");
$auth = $this->vespula_auth; //get the auth object
/** @psalm-suppress MixedAssignment */
$username = sMVC_GetSuperGlobal('post', 'username', '');
/** @psalm-suppress MixedAssignment */
$password = sMVC_GetSuperGlobal('post', 'password', '');
$error_msg = '';
if( $username === '' ) {
/**
* @psalm-suppress MixedOperand
*/
$error_msg .= $this->vespula_locale
->gettext('base_controller_action_login_empty_username_msg');
}
if( $password === '' ) {
$error_msg .= (($error_msg === ''))? '' : '<br>';
/**
* @psalm-suppress MixedOperand
*/
$error_msg .= $this->vespula_locale->gettext('base_controller_action_login_empty_password_msg');
}
if( ($error_msg === '') ) {
$credentials = [
'username'=> filter_var($username, FILTER_UNSAFE_RAW),
'password'=> $password, //Not sanitizing this. Sanitizing or
//validating passwords should be app
//specific & done during user creation.
//For example an app can be setup to
//allow only alphanumeric passwords
//with a specific list of allowed
//special characters.
];
$msg = $this->doLogin($auth, $credentials, $success_redirect_path);
} else {
$msg = $error_msg;
}
/**
* @psalm-suppress UndefinedConstant
* @psalm-suppress UndefinedFunction
*/
if( sMVC_GetCurrentAppEnvironment() !== SMVC_APP_ENV_PRODUCTION ) {
$msg .= '<br>'.nl2br(sMVC_DumpAuthinfo($auth));
}
if( $auth->isValid() ) {
//re-direct
/** @psalm-suppress MixedArgument */
return $this->response
->withStatus(302)
->withHeader('Location', $success_redirect_path);
} else {
//re-display login form with error messages
$data_4_login_view['error_message'] = $msg;
/** @psalm-suppress MixedAssignment */
$data_4_login_view['username'] = $username;
/** @psalm-suppress MixedAssignment */
$data_4_login_view['password'] = $password;
//get the contents of the view first
$view_str = $this->renderView('login.php', $data_4_login_view);
return $this->renderLayout( $this->layout_template_file_name, ['content'=>$view_str] );
}
} // if( strtoupper($this->request->getMethod()) === 'GET' ) else {....}
}
/** @psalm-suppress MixedInferredReturnType */
protected function doLogin(\Vespula\Auth\Auth $auth, array $credentials, string &$success_redirect_path): string {
$_msg = '';
try {
$potential_success_redirect_path = '';
/** @psalm-suppress MixedArrayOffset */
if( isset($_SESSION[self::SESSN_PARAM_LOGIN_REDIRECT]) ) {
////////////////////////////////////////////////////////////////
// There is an active session with a redirect url stored in it
//
// NOTE: we capture this value here because \Vespula\Auth\Auth->login()
// calls session_regenerate_id(true) under the hood which will delete
// old session data including this value we are capturing here.
/** @psalm-suppress MixedAssignment */
$potential_success_redirect_path = $_SESSION[self::SESSN_PARAM_LOGIN_REDIRECT];
}
$auth->login($credentials); //try to login
if( $auth->isValid() ) { // login successful
/**
* @psalm-suppress MixedArgument
* @psalm-suppress MixedMethodCall
* @psalm-suppress PossiblyInvalidOperand
*/
$this->logger
->info(
"User `{$auth->getUsername()}` successfully logged in." . PHP_EOL .PHP_EOL
);
/**
* @psalm-suppress MixedAssignment
* @psalm-suppress MixedOperand
*/
$_msg = $this->vespula_locale->gettext('base_controller_do_login_auth_is_valid_msg');
/** @psalm-suppress MixedAssignment */
$success_redirect_path =
($potential_success_redirect_path !== '')
? $potential_success_redirect_path : $success_redirect_path;
/** @psalm-suppress MixedArrayOffset */
if( isset($_SESSION[self::SESSN_PARAM_LOGIN_REDIRECT]) ) {
//since login is successful remove stored redirect url,
//it has served its purpose & we'll be redirecting now.
unset($_SESSION[self::SESSN_PARAM_LOGIN_REDIRECT]);
}
//since we are successfully logged in, resume session if any
if (session_status() !== \PHP_SESSION_ACTIVE) {
$this->startSession();
}
} else {
/**
* @psalm-suppress MixedAssignment
* @psalm-suppress MixedOperand
*/
$_msg = $this->vespula_locale->gettext('base_controller_do_login_auth_not_is_valid_msg');
/**
* @psalm-suppress UndefinedFunction
* @psalm-suppress UndefinedConstant
*/
if( sMVC_GetCurrentAppEnvironment() !== SMVC_APP_ENV_PRODUCTION ) {
/** @psalm-suppress MixedOperand */
$_msg .= '<br>' . $auth->getAdapter()->getError();
}
}
} catch (\Vespula\Auth\Exception $vaExc) {
$backendIssues = [
'EXCEPTION_LDAP_CONNECT_FAILED',
'Could not bind to basedn',
'LDAP extension not loaded',
'Missing basedn in bind options',
'Missing binddn in bind options',
'Missing bindpw in bind options',
'Missing filter in bind options',
'Invalid data passed. Must be a filename or array of users',
];
$usernamePswdMismatchIssues = [
'The LDAP DN search failed',
\Vespula\Auth\Adapter\Sql::ERROR_PASSWORD_COL,
\Vespula\Auth\Adapter\Sql::ERROR_USERNAME_COL,
'Invalid credentials array. Must have keys `username` and `password`.',
];
/**
* @psalm-suppress MixedAssignment
* @psalm-suppress MixedOperand
*/
$_msg = $this->vespula_locale->gettext('base_controller_do_login_auth_v_auth_exception_general_msg');
if(\in_array($vaExc->getMessage(), $backendIssues) || str_starts_with($vaExc->getMessage(), 'File not found ')) {
/**
* @psalm-suppress MixedAssignment
* @psalm-suppress MixedOperand
*/
$_msg = $this->vespula_locale->gettext('base_controller_do_login_auth_v_auth_exception_back_end_msg');
}
if(\in_array($vaExc->getMessage(), $usernamePswdMismatchIssues)) {
/**
* @psalm-suppress MixedAssignment
* @psalm-suppress MixedOperand
*/
$_msg = $this->vespula_locale->gettext('base_controller_do_login_auth_v_auth_exception_user_passwd_msg');
}
/**
* @psalm-suppress MixedArgument
* @psalm-suppress MixedMethodCall
* @psalm-suppress PossiblyInvalidOperand
*/
$this->logger
->error(
\str_replace('<br>', PHP_EOL, $_msg)
. Utils::getThrowableAsStr($vaExc)
);
} catch(\Exception $basExc) {
/**
* @psalm-suppress MixedAssignment
* @psalm-suppress MixedOperand
*/
$_msg = $this->vespula_locale->gettext('base_controller_do_login_auth_exception_msg');
/**
* @psalm-suppress MixedArgument
* @psalm-suppress MixedMethodCall
* @psalm-suppress PossiblyInvalidOperand
*/
$this->logger
->error(
\str_replace('<br>', PHP_EOL, $_msg)
. Utils::getThrowableAsStr($basExc)
);
}
/** @psalm-suppress MixedReturnStatement */
return $_msg;
}
/**
* @param mixed $show_status_on_completion any value that evaluates to true or false.
* When the value is true, the user will be
* redirected to actionLoginStatus(). When it
* is false, the user will be redirected to
* actionLogin()
* @psalm-suppress PossiblyUnusedMethod
*/
public function actionLogout(mixed $show_status_on_completion = false): ResponseInterface {
$auth = $this->vespula_auth;
$logged_in_user = $this->isLoggedIn() ? $auth->getUsername() : '';
$redirect_path = '';
/** @psalm-suppress MixedArrayOffset */
if(
session_status() === \PHP_SESSION_ACTIVE
&& isset($_SESSION[self::SESSN_PARAM_LOGIN_REDIRECT])
) {
//there is an active session with a redirect url stored in it
/** @psalm-suppress MixedAssignment */
$redirect_path = $_SESSION[self::SESSN_PARAM_LOGIN_REDIRECT];
}
$auth->logout(); //logout
if( !$auth->isAnon() ) {
//logout failed. Definitely redirect to actionLoginStatus
$show_status_on_completion = true;
} elseif ($logged_in_user !== '') {
/**
* @psalm-suppress MixedArgument
* @psalm-suppress MixedMethodCall
* @psalm-suppress PossiblyInvalidOperand
*/
$this->logger
->info(
"User `{$logged_in_user}` successfully logged out" . PHP_EOL .PHP_EOL
);
}
if($redirect_path === '' || ((bool)$show_status_on_completion)) {
// SMVC_APP_AUTO_PREPEND_ACTION_TO_ACTION_METHOD_NAMES === true
// means that links generated in this action do not need to be prefixed
// with action- since when users click on them, the framework will
// automatically append action to the resolved method name
// see \SlimMvcTools\MvcRouteHandler::__invoke(...)
/** @psalm-suppress UndefinedConstant */
$prepend_action = !SMVC_APP_AUTO_PREPEND_ACTION_TO_ACTION_METHOD_NAMES;
$action = ($prepend_action) ? 'action-' : '';
$actn = ((bool)$show_status_on_completion) ? $action.'login-status' : $action.'login';
$controller = $this->controller_name_from_uri;
if( ($controller === '') ) {
$controller = 'base-controller';
}
$redirect_path = $this->makeLink("/{$controller}/{$actn}");
}
//re-direct
/** @psalm-suppress MixedArgument */
return $this->response->withStatus(302)->withHeader('Location', $redirect_path);
}
/**
* @psalm-suppress PossiblyUnusedMethod
* @psalm-suppress UnusedVariable
*/
public function actionLoginStatus(): string {
$msg = '';
$auth = $this->vespula_auth;
//Just get the current login status
/** @psalm-suppress MixedAssignment */
$msg = match (true) {
$auth->isAnon() => $this->vespula_locale->gettext('base_controller_action_login_status_is_anon_msg'),
$auth->isIdle() => $this->vespula_locale->gettext('base_controller_action_login_status_is_idle_msg'),
$auth->isExpired() => $this->vespula_locale->gettext('base_controller_action_login_status_is_expired_msg'),
$auth->isValid() => $this->vespula_locale->gettext('base_controller_action_login_status_is_valid_msg'),
default => $this->vespula_locale->gettext('base_controller_action_login_status_unknown_msg'),
};
/**
* @psalm-suppress UndefinedConstant
* @psalm-suppress UndefinedFunction
*/
if( sMVC_GetCurrentAppEnvironment() !== SMVC_APP_ENV_PRODUCTION ) {
/** @psalm-suppress MixedOperand */
$msg .= '<br>'.nl2br(sMVC_DumpAuthinfo($auth));
}
//get the contents of the view first
$view_str = $this->renderView( 'login-status.php', ['message'=>$msg, 'is_logged_in'=>$this->isLoggedIn(), 'controller_object'=>$this] );
return $this->renderLayout( $this->layout_template_file_name, ['content'=>$view_str] );
}
public function isLoggedIn(): bool {
return ($this->vespula_auth->isValid());
}
/**
* Return a response object (an instance of \Psr\Http\Message\ResponseInterface)
* if the user is not logged in (The url the user is currently accessing will be
* stored in $_SESSION with the key `static::SESSN_PARAM_LOGIN_REDIRECT`. Upon
* a successful login, the user will be redirected back to the current url in
* $this->actionLogin().
*
* False is returned if the user is logged in and there is no need to redirect to
* the login page.
*/
public function getResponseObjForLoginRedirectionIfNotLoggedIn(): bool|\Psr\Http\Message\ResponseInterface {
if( !$this->isLoggedIn() ) {
$this->storeCurrentUrlForLoginRedirection();
$controller = $this->controller_name_from_uri;
if( ($controller === '') ) {
$controller = 'base-controller';
}
// SMVC_APP_AUTO_PREPEND_ACTION_TO_ACTION_METHOD_NAMES === true
// means that links generated in this action do not need to be prefixed
// with action- since when users click on them, the framework will
// automatically append action to the resolved method name
// see \SlimMvcTools\MvcRouteHandler::__invoke(...)
/** @psalm-suppress UndefinedConstant */
$action = (SMVC_APP_AUTO_PREPEND_ACTION_TO_ACTION_METHOD_NAMES) ? 'login' : 'action-login';
$redr_path = $this->makeLink("/{$controller}/$action");
return $this->response->withStatus(302)->withHeader('Location', $redr_path);
}