Passed
Push — master ( dfeadf...0d8182 )
by Jean-Christophe
04:51
created

AuthController::_forward()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.072

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 6
ccs 4
cts 5
cp 0.8
rs 10
c 0
b 0
f 0
cc 3
nc 2
nop 1
crap 3.072
1
<?php
2
namespace Ubiquity\controllers\auth;
3
4
use Ubiquity\utils\http\USession;
5
use Ubiquity\utils\http\URequest;
6
use Ubiquity\utils\flash\FlashMessage;
7
use Ubiquity\controllers\ControllerBase;
8
use Ubiquity\controllers\Auth\AuthFiles;
9
use Ubiquity\utils\http\UResponse;
10
use Ubiquity\utils\base\UString;
11
use Ubiquity\controllers\Startup;
12
use Ajax\service\Javascript;
13
use Ubiquity\utils\http\UCookie;
14
15
 /**
16
 * Controller Auth
17
 * @property \Ajax\php\ubiquity\JsUtils $jquery
18
 **/
19
abstract class AuthController extends ControllerBase{
20
	use AuthControllerCoreTrait,AuthControllerVariablesTrait,AuthControllerOverrideTrait;
21
	
22
	/**
23
	 * @var AuthFiles
24
	 */
25
	protected $authFiles;
26
	protected $_controller;
27
	protected $_action;
28
	protected $_actionParams;
29
	protected $_noAccessMsg;
30
	protected $_loginCaption;
31
	protected $_attemptsSessionKey="_attempts";
32
	protected $_controllerInstance;
33
	
34 3
	public function __construct($instance=null){
35 3
		parent::__construct();
36 3
		$this->_controller=Startup::getController();
37 3
		$this->_action=Startup::getAction();
38 3
		$this->_actionParams=Startup::getActionParams();
39 3
		$this->_noAccessMsg=new FlashMessage("You are not authorized to access the page <b>{url}</b> !","Forbidden access","error","warning circle");
40 3
		$this->_loginCaption="Log in";
41 3
		$this->_controllerInstance=$instance;
42 3
		if(isset($instance))
43
			Startup::injectDependences($instance);
44 3
	}
45
	
46 1
	public function index(){
47 1
		if(($nbAttempsMax=$this->attemptsNumber())!==null){
48
			$nb=USession::getTmp($this->_attemptsSessionKey,$nbAttempsMax);
49
			if($nb<=0){
50
				$this->badLogin();
51
				return;
52
			}
53
		}
54 1
		$this->authLoadView($this->_getFiles()->getViewIndex(),["action"=>$this->getBaseUrl()."/connect",
55 1
				"loginInputName"=>$this->_getLoginInputName(),"loginLabel"=>$this->loginLabel(),
56 1
				"passwordInputName"=>$this->_getPasswordInputName(),"passwordLabel"=>$this->passwordLabel(),
57 1
				"rememberCaption"=>$this->rememberCaption()
58
		]);
59 1
	}
60
	
61
	/**
62
	 * {@inheritDoc}
63
	 * @see \controllers\ControllerBase::isValid()
64
	 */
65 1
	public final function isValid($action) {
66 1
		return true;
67
	}
68
	
69
	/**
70
	 * Action called when the user does not have access rights to a requested resource
71
	 * @param array|string $urlParts
72
	 */
73 1
	public function noAccess($urlParts){
74 1
		if(!is_array($urlParts)){
75
			$urlParts=explode(".", $urlParts);
76
		}
77 1
		USession::set("urlParts", $urlParts);
78 1
		$fMessage=$this->_noAccessMsg;
79 1
		$this->noAccessMessage($fMessage);
80 1
		$message=$this->fMessage($fMessage->parseContent(["url"=>implode("/",$urlParts)]));
81
		/*if(URequest::isAjax()){
82
			$this->jquery->get($this->_getBaseRoute()."/info/f","#_userInfo",["historize"=>false,"jqueryDone"=>"replaceWith","hasLoader"=>false,"attr"=>""]);
83
			$this->jquery->compile($this->view);
84
		}*/
85 1
		$this->authLoadView($this->_getFiles()->getViewNoAccess(),["_message"=>$message,"authURL"=>$this->getBaseUrl(),"bodySelector"=>$this->_getBodySelector(),"_loginCaption"=>$this->_loginCaption]);
86 1
	}
87
	
88
89
	
90
	/**
91
	 * Override to implement the complete connection procedure 
92
	 */
93 1
	public function connect(){
94 1
		if(URequest::isPost()){
95 1
			if($connected=$this->_connect()){
96 1
				if(isset($_POST["ck-remember"])){
97
					$this->rememberMe($connected);
98
				}
99 1
				if(USession::exists($this->_attemptsSessionKey)){
100
					USession::delete($this->_attemptsSessionKey);
101
				}
102 1
				$this->onConnect($connected);
103
			}else{
104 1
				$this->onBadCreditentials();
105
			}
106
		}
107 1
	}
108
	
109
	/**
110
	 * Default Action for invalid creditentials
111
	 */
112 1
	public function badLogin(){
113 1
		$fMessage=new FlashMessage("Invalid creditentials!","Connection problem","warning","warning circle");
114 1
		$this->badLoginMessage($fMessage);
115 1
		$attemptsMessage="";
116 1
		if(($nbAttempsMax=$this->attemptsNumber())!==null){
117
			$nb=USession::getTmp($this->_attemptsSessionKey,$nbAttempsMax);
118
			$nb--;
119
			if($nb<0) $nb=0;
120
			if($nb==0){
121
				$fAttemptsNumberMessage=$this->noAttempts();
122
			}else{
123
				$fAttemptsNumberMessage=new FlashMessage("<i class='ui warning icon'></i> You still have {_attemptsCount} attempts to log in.",null,"bottom attached warning","");
124
			}
125
			USession::setTmp($this->_attemptsSessionKey, $nb,$this->attemptsTimeout());
126
			$this->attemptsNumberMessage($fAttemptsNumberMessage,$nb);
127
			$fAttemptsNumberMessage->parseContent(["_attemptsCount"=>$nb,"_timer"=>"<span id='timer'></span>"]);
128
			$attemptsMessage=$this->fMessage($fAttemptsNumberMessage,"timeout-message");
129
			$fMessage->addType("attached");
130
		}
131 1
		$message=$this->fMessage($fMessage,"bad-login").$attemptsMessage;
132 1
		$this->authLoadView($this->_getFiles()->getViewNoAccess(),["_message"=>$message,"authURL"=>$this->getBaseUrl(),"bodySelector"=>$this->_getBodySelector(),"_loginCaption"=>$this->_loginCaption]);
133 1
	}
134
	
135
	/**
136
	 * Logout action
137
	 * Terminate the session and display a logout message
138
	 */
139 1
	public function terminate(){
140 1
		USession::terminate();
141 1
		$fMessage=new FlashMessage("You have been properly disconnected!","Logout","success","checkmark");
142 1
		$this->terminateMessage($fMessage);
143 1
		$message=$this->fMessage($fMessage);
144 1
		$this->authLoadView($this->_getFiles()->getViewNoAccess(),["_message"=>$message,"authURL"=>$this->getBaseUrl(),"bodySelector"=>$this->_getBodySelector(),"_loginCaption"=>$this->_loginCaption]);
145 1
	}
146
	
147
	public function _disConnected(){
148
		$fMessage=new FlashMessage("You have been disconnected from the application!","Logout","","sign out");
149
		$this->disconnectedMessage($fMessage);
150
		$message=$this->fMessage($fMessage);
151
		$this->jquery->getOnClick("._signin", $this->getBaseUrl(),$this->_getBodySelector(),["stopPropagation"=>false,"preventDefault"=>false]);
152
		$this->jquery->execOn("click", "._close", "window.open(window.location,'_self').close();");
153
		return $this->jquery->renderView($this->_getFiles()->getViewDisconnected(),["_title"=>"Session ended","_message"=>$message],true);
154
	}
155
	
156
	/**
157
	 * Action displaying the logged user information 
158
	 * if _displayInfoAsString returns true, use _infoUser var in views to display user info
159
	 * @return string|null
160
	 */
161 1
	public function info($force=null){
162 1
		if(isset($force)){
163
			$displayInfoAsString=($force===true)?true:false;
164
		}else{
165 1
			$displayInfoAsString=$this->_displayInfoAsString();
166
		}
167 1
		return $this->loadView($this->_getFiles()->getViewInfo(),["connected"=>USession::get($this->_getUserSessionKey()),"authURL"=>$this->getBaseUrl(),"bodySelector"=>$this->_getBodySelector()],$displayInfoAsString);
168
	}
169
	
170
	public function checkConnection(){
171
		UResponse::asJSON();
172
		echo "{\"valid\":".UString::getBooleanStr($this->_isValidUser())."}";
173
	}
174
	
175
	/**
176
	 * Sets the default noAccess message
177
	 * Default : "You are not authorized to access the page <b>{url}</b> !"
178
	 * @param string $content
179
	 * @param string $title
180
	 * @param string $type
181
	 * @param string $icon
182
	 */
183
	public function _setNoAccessMsg($content,$title=NULL,$type=NULL,$icon=null) {
184
		$this->_noAccessMsg->setValues($content,$title,$type,$icon);
185
	}
186
	/**
187
	 * @param string $_loginCaption
188
	 */
189
	public function _setLoginCaption($_loginCaption) {
190
		$this->_loginCaption = $_loginCaption;
191
	}
192
	
193
	/**
194
	 * Auto connect the user
195
	 */
196 1
	public function _autoConnect() {
197 1
		$cookie=$this->getCookieUser();
198 1
		if(isset($cookie)){
199
			$user=$this->fromCookie($cookie);
200
			if(isset($user)){
201
				USession::set($this->_getUserSessionKey(), $user);
202
			}
203
		}
204 1
	}
205
	/**
206
	 * Deletes the cookie for auto connection and returns to index
207
	 */
208
	public function forgetConnection(){
209
		UCookie::delete($this->_getUserSessionKey());
210
		$this->index();
211
	}
212
	
213
	/**
214
	 * {@inheritDoc}
215
	 * @see \Ubiquity\controllers\ControllerBase::finalize()
216
	 */
217 1
	public function finalize() {
218 1
		if(!UResponse::isJSON()){
219 1
			if(!URequest::isAjax()){
220 1
				if(isset($this->_controllerInstance)){
221
					call_user_func_array(array($this->_controllerInstance, 'parent::finalize'), []);
222
				}else{
223 1
					parent::finalize();	
224
				}
225
			}
226 1
			$this->jquery->execAtLast("if($('#_userInfo').length){\$('#_userInfo').html(".preg_replace("/$\R?^/m", "",Javascript::prep_element($this->info())).");}");
227 1
			echo $this->jquery->compile();
228
		}
229 1
	}
230
231
	/**
232
	 * {@inheritDoc}
233
	 * @see \Ubiquity\controllers\ControllerBase::initialize()
234
	 */
235 1
	public function initialize() {
236 1
		if(!URequest::isAjax()){
237 1
			if(isset($this->_controllerInstance)){
238
				call_user_func_array(array($this->_controllerInstance, 'parent::initialize'), []);
239
			}else{
240 1
				parent::initialize();
241
			}
242
		}
243 1
	}
244
	
245
	/**
246
	 * @param string $url
247
	 */
248 1
	public function _forward($url){
249 1
		$initFinalize=true;
250 1
		if(isset($this->_controllerInstance) && !URequest::isAjax()){
251
			$initFinalize=false;
252
		}
253 1
		Startup::forward($url,$initFinalize,$initFinalize);
254 1
	}
255
}
256