Ubiquity 2.5.2
php rapid development framework
Loading...
Searching...
No Matches
AuthController.php
Go to the documentation of this file.
1<?php
2
4
15use Ajax\service\Javascript;
18use Ajax\semantic\html\collections\form\HtmlForm;
19use Ajax\php\ubiquity\JsUtils;
20
27
32 protected $authFiles;
33 protected $_controller;
34 protected $_action;
35 protected $_actionParams;
36 protected $_noAccessMsg;
37 protected $_loginCaption;
38 protected $_attemptsSessionKey = '_attempts';
40 protected $_compileJS = true;
41 protected $_invalid=false;
42
43 public function __construct($instance = null) {
44 parent::__construct ();
45 $this->_insertJquerySemantic ();
46 $this->_controller = Startup::getController ();
47 $this->_action = Startup::getAction ();
48 $this->_actionParams = Startup::getActionParams ();
49 $this->_noAccessMsg = new FlashMessage ( 'You are not authorized to access the page <b>{url}</b> !', 'Forbidden access', 'error', 'warning circle' );
50 $this->_loginCaption = 'Log in';
51 $this->_controllerInstance = $instance;
52 if (isset ( $instance )){
53 Startup::injectDependencies ( $instance );
54 }
55 if($this->useAjax() && !URequest::isAjax()) {
56 $this->_addAjaxBehavior($instance->jquery??$this->jquery);
57 }
58 }
59
60 public function index() {
61 if (($nbAttempsMax = $this->attemptsNumber ()) !== null) {
62 $nb = USession::getTmp ( $this->_attemptsSessionKey, $nbAttempsMax );
63 if ($nb <= 0) {
64 $this->badLogin ();
65 return;
66 }
67 }
68 if($this->useAjax()){
69 $this->_addFrmAjaxBehavior('frm-login');
70 }
71 $vData=[ 'action' => $this->getBaseUrl () . '/connect','loginInputName' => $this->_getLoginInputName (),'loginLabel' => $this->loginLabel (),'passwordInputName' => $this->_getPasswordInputName (),'passwordLabel' => $this->passwordLabel (),'rememberCaption' => $this->rememberCaption () ];
72 $this->addAccountCreationViewData($vData,true);
73 $this->authLoadView ( $this->_getFiles ()->getViewIndex (), $vData );
74 }
75
81 public final function isValid($action) {
82 return true;
83 }
84
90 public function noAccess($urlParts) {
91 if (! \is_array ( $urlParts )) {
92 $urlParts = \explode ( '.', $urlParts );
93 }
94 USession::set ( 'urlParts', $urlParts );
95 $fMessage = $this->_noAccessMsg;
96 $this->noAccessMessage ( $fMessage );
97 $message = $this->fMessage ( $fMessage->parseContent ( [ 'url' => \implode ( '/', $urlParts ) ] ) );
98
99 if (URequest::isAjax ()) {
100 $this->jquery->get ( $this->_getBaseRoute () . '/info/f', '#_userInfo', [ 'historize' => false,'jqueryDone' => 'replaceWith','hasLoader' => false,'attr' => '' ] );
101 $this->jquery->compile ( $this->view );
102 }
103 $vData=[ '_message' => $message,'authURL' => $this->getBaseUrl (),'bodySelector' => $this->_getBodySelector (),'_loginCaption' => $this->_loginCaption ];
104 $this->addAccountCreationViewData($vData);
105 $this->authLoadView ( $this->_getFiles ()->getViewNoAccess (), $vData);
106 }
107
113 #[\Ubiquity\attributes\items\router\Post]
114 public function connect() {
115 if (URequest::isPost ()) {
116 if ($connected = $this->_connect ()) {
117 if (isset ( $_POST ['ck-remember'] )) {
118 $this->rememberMe ( $connected );
119 }
120 if (USession::exists ( $this->_attemptsSessionKey )) {
121 USession::delete ( $this->_attemptsSessionKey );
122 }
123 if($this->has2FA($connected)){
124 $this->initializeAuth();
125 USession::set($this->_getUserSessionKey().'-2FA', $connected);
126 $this->send2FACode();
127 $this->confirm();
128 $this->finalizeAuth();
129 }else{
130 $this->onConnect ( $connected );
131 }
132 } else {
133 $this->_invalid=true;
134 $this->initializeAuth();
135 $this->onBadCreditentials ();
136 $this->finalizeAuth();
137 }
138 }
139 }
140
146 #[\Ubiquity\attributes\items\router\NoRoute]
147 public function badLogin() {
148 $fMessage = new FlashMessage ( 'Invalid creditentials!', 'Connection problem', 'warning', 'warning circle' );
149 $this->badLoginMessage ( $fMessage );
150 $attemptsMessage = '';
151 if (($nbAttempsMax = $this->attemptsNumber ()) !== null) {
152 $nb = USession::getTmp ( $this->_attemptsSessionKey, $nbAttempsMax );
153 $nb --;
154 if ($nb < 0) {
155 $nb = 0;
156 }
157 if ($nb == 0) {
158 $fAttemptsNumberMessage = $this->noAttempts ();
159 } else {
160 $fAttemptsNumberMessage = new FlashMessage ( '<i class="ui warning icon"></i> You still have {_attemptsCount} attempts to log in.', null, 'bottom attached warning', '' );
161 }
162 USession::setTmp ( $this->_attemptsSessionKey, $nb, $this->attemptsTimeout () );
163 $this->attemptsNumberMessage ( $fAttemptsNumberMessage, $nb );
164 $fAttemptsNumberMessage->parseContent ( [ '_attemptsCount' => $nb,'_timer' => '<span id="timer"></span>' ] );
165 $attemptsMessage = $this->fMessage ( $fAttemptsNumberMessage, 'timeout-message' );
166 $fMessage->addType ( "attached" );
167 }
168 $message = $this->fMessage ( $fMessage, 'bad-login' ) . $attemptsMessage;
169 $this->authLoadView ( $this->_getFiles ()->getViewNoAccess (), [ '_message' => $message,'authURL' => $this->getBaseUrl (),'bodySelector' => $this->_getBodySelector (),'_loginCaption' => $this->_loginCaption ] );
170 }
171
176 public function terminate() {
177 USession::terminate ();
178 $fMessage = new FlashMessage ( 'You have been properly disconnected!', 'Logout', 'success', 'checkmark' );
179 $this->terminateMessage ( $fMessage );
180 $message = $this->fMessage ( $fMessage );
181 $this->authLoadView ( $this->_getFiles ()->getViewNoAccess (), [ '_message' => $message,'authURL' => $this->getBaseUrl (),'bodySelector' => $this->_getBodySelector (),'_loginCaption' => $this->_loginCaption ] );
182 }
183
184 public function _disConnected() {
185 $fMessage = new FlashMessage ( 'You have been disconnected from the application!', 'Logout', '', 'sign out' );
186 $this->disconnectedMessage ( $fMessage );
187 $message = $this->fMessage ( $fMessage );
188 $this->jquery->getOnClick ( '._signin', $this->getBaseUrl (), $this->_getBodySelector (), [ 'stopPropagation' => false,'preventDefault' => false ] );
189 $this->jquery->execOn ( 'click', '._close', "window.open(window.location,'_self').close();" );
190 return $this->jquery->renderView ( $this->_getFiles ()->getViewDisconnected (), [ "_title" => 'Session ended','_message' => $message ], true );
191 }
192
201 public function info($force = null) {
202 if (isset ( $force )) {
203 $displayInfoAsString = $force === true;
204 } else {
205 $displayInfoAsString = $this->_displayInfoAsString ();
206 }
207 return $this->loadView ( $this->_getFiles ()->getViewInfo (), [ 'connected' => USession::get ( $this->_getUserSessionKey () ),'authURL' => $this->getBaseUrl (),'bodySelector' => $this->_getBodySelector () ], $displayInfoAsString );
208 }
209
210 public function checkConnection() {
211 UResponse::asJSON ();
212 echo \json_encode(['valid'=> $this->_isValidUser ()]);
213 }
214
224 public function _setNoAccessMsg($content, $title = NULL, $type = NULL, $icon = null) {
225 $this->_noAccessMsg->setValues ( $content, $title, $type, $icon );
226 }
227
233 $this->_loginCaption = $_loginCaption;
234 }
235
239 public function _autoConnect() {
240 $cookie = $this->getCookieUser ();
241 if (isset ( $cookie )) {
242 $user = $this->fromCookie ( $cookie );
243 if (isset ( $user )) {
244 USession::set ( $this->_getUserSessionKey (), $user );
245 }
246 }
247 }
248
252 public function forgetConnection() {
253 UCookie::delete ( $this->_getUserSessionKey () );
254 $this->index ();
255 }
256
262 public function finalize() {
263 if (! UResponse::isJSON ()) {
264 if(Startup::getAction()!=='connect') {
265 $this->finalizeAuth();
266 }
267 $this->jquery->execAtLast ( "if($('#_userInfo').length){\$('#_userInfo').replaceWith(" . \preg_replace ( "/$\R?^/m", "", Javascript::prep_element ( $this->info () ) ) . ");}" );
268 if ($this->_compileJS) {
269 echo $this->jquery->compile ();
270 }
271 }
272 }
273
274 protected function finalizeAuth() {
275 if (!URequest::isAjax()) {
276 $this->loadView('@activeTheme/main/vFooter.html');
277 }
278 }
279
285 public function initialize() {
286 if(Startup::getAction()!=='connect') {
287 $this->initializeAuth();
288 }
289 }
290
291 protected function initializeAuth() {
292 if (!URequest::isAjax()) {
293 $this->loadView('@activeTheme/main/vHeader.html');
294 }
295 }
296
301 public function _forward($url, $initialize = null, $finalize = null) {
302 if (! isset ( $initialize )) {
303 $initialize = (! isset ( $this->_controllerInstance ) || URequest::isAjax ());
304 }
305 if (! isset ( $finalize )) {
306 $finalize = $initialize;
307 }
308 Startup::forward ( $url, $initialize, $finalize );
309 }
310
311 public function _addAjaxBehavior(JsUtils $jquery=null,$ajaxParameters=['hasLoader'=>'$(this).children(".button")','historize'=>false,'listenerOn'=>'body']){
313 $jquery->getHref('.ajax[data-target]','', $ajaxParameters);
314 $jquery->postFormAction('.ui.form',$this->_getBodySelector(),$ajaxParameters);
315 }
316
317 public function _addFrmAjaxBehavior($id):HtmlForm{
318 $frm=$this->jquery->semantic()->htmlForm($id);
319 $frm->addExtraFieldRule($this->_getLoginInputName(),'empty');
320 $frm->addExtraFieldRule($this->_getPasswordInputName(),'empty');
321 $frm->setValidationParams(['inline'=>true,'on'=>'blur']);
322 return $frm;
323 }
324 public function _init(){
325
326 }
327}
Base class for controllers.
Starts the framework.
Definition Startup.php:19
static getController()
Returns the active controller name.
Definition Startup.php:291
static forward(string $url, bool $initialize=true, bool $finalize=true)
Forwards to url.
Definition Startup.php:102
static injectDependencies($controller)
Injects the dependencies from the di config key in a controller.
Definition Startup.php:225
static getActionParams()
Returns the active parameters.
Definition Startup.php:327
static getAction()
Returns tha active action.
Definition Startup.php:318
loadView(string $viewName, $pData=NULL, bool $asString=false)
forgetConnection()
Deletes the cookie for auto connection and returns to index.
info($force=null)
Action displaying the logged user information if _displayInfoAsString returns true,...
_addAjaxBehavior(JsUtils $jquery=null, $ajaxParameters=['hasLoader'=> '$(this).children(".button")', 'historize'=>false, 'listenerOn'=> 'body'])
connect()
Override to implement the complete connection procedure.
initialize()
{Method called before each action Can be override in derived class.}
finalize()
{Method called after each action Can be override in derived class.}
noAccess($urlParts)
Action called when the user does not have access rights to a requested resource.
terminate()
Logout action Terminate the session and display a logout message.
_forward($url, $initialize=null, $finalize=null)
isValid($action)
{Returns True if access to the controller is allowed To be override in sub classes....
_setNoAccessMsg($content, $title=NULL, $type=NULL, $icon=null)
Sets the default noAccess message Default : "You are not authorized to access the page <b>{url}</b> !...
badLogin()
Default Action for invalid creditentials.
_connect()
Processes the data posted by the login form Have to return the connected user instance.
rememberMe($connected)
Saves the connected user identifier in a cookie.
onBadCreditentials()
To override for defining a new action when creditentials are invalid.
_isValidUser($action=null)
Checks if user is valid for the action.
fromCookie($cookie)
Loads the user from database using the cookie value.
Ubiquity\controllers\auth$AuthControllerVariablesTrait This class is part of Ubiquity.
disconnectedMessage(FlashMessage $fMessage)
To override for modifying the disconnect message.
attemptsNumber()
To override Returns int the maximum number of allowed login attempts.
noAccessMessage(FlashMessage $fMessage)
Override for modifying the noAccess message.
_displayInfoAsString()
Override to define if user info is displayed as string.
attemptsNumberMessage(FlashMessage $fMessage, $attempsCount)
Override for modifying attempts message You can use {_timer} and {_attemptsCount} variables in messag...
terminateMessage(FlashMessage $fMessage)
To override for modifying the logout message.
badLoginMessage(FlashMessage $fMessage)
To override for modifying the bad login message.
has2FA($accountValue=null)
To override Returns true for a two factor authentification for this account.
Ubiquity\controllers\auth\traits$AuthAccountRecoveryTrait This class is part of Ubiquity.
String utilities.
Definition UString.php:15
Http Request utilities, wrapper for accessing to $_GET, $_POST and php://input.
Definition URequest.php:18
Http Response utilities.
Definition UResponse.php:17
Http Session utilities This class is part of Ubiquity.
Definition USession.php:16