forked from CakeDC/users
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUsersAuthComponent.php
More file actions
255 lines (230 loc) · 8.4 KB
/
Copy pathUsersAuthComponent.php
File metadata and controls
255 lines (230 loc) · 8.4 KB
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
<?php
/**
* Copyright 2010 - 2017, Cake Development Corporation (https://www.cakedc.com)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2010 - 2017, Cake Development Corporation (https://www.cakedc.com)
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
namespace CakeDC\Users\Controller\Component;
use CakeDC\Users\Auth\TwoFactorAuthenticationCheckerFactory;
use CakeDC\Users\Exception\BadConfigurationException;
use Cake\Controller\Component;
use Cake\Core\Configure;
use Cake\Event\Event;
use Cake\Event\EventManager;
use Cake\Http\ServerRequest;
use Cake\Routing\Exception\MissingRouteException;
use Cake\Routing\Router;
use Cake\Utility\Hash;
class UsersAuthComponent extends Component
{
const EVENT_IS_AUTHORIZED = 'Users.Component.UsersAuth.isAuthorized';
const EVENT_BEFORE_LOGIN = 'Users.Component.UsersAuth.beforeLogin';
const EVENT_AFTER_LOGIN = 'Users.Component.UsersAuth.afterLogin';
const EVENT_FAILED_SOCIAL_LOGIN = 'Users.Component.UsersAuth.failedSocialLogin';
const EVENT_AFTER_COOKIE_LOGIN = 'Users.Component.UsersAuth.afterCookieLogin';
const EVENT_BEFORE_REGISTER = 'Users.Component.UsersAuth.beforeRegister';
const EVENT_AFTER_REGISTER = 'Users.Component.UsersAuth.afterRegister';
const EVENT_BEFORE_LOGOUT = 'Users.Component.UsersAuth.beforeLogout';
const EVENT_AFTER_LOGOUT = 'Users.Component.UsersAuth.afterLogout';
const EVENT_BEFORE_SOCIAL_LOGIN_REDIRECT = 'Users.Component.UsersAuth.beforeSocialLoginRedirect';
const EVENT_BEFORE_SOCIAL_LOGIN_USER_CREATE = 'Users.Component.UsersAuth.beforeSocialLoginUserCreate';
const EVENT_SOCIAL_LOGIN_EXISTING_ACCOUNT = 'Users.Component.UsersAuth.socialLoginExistingAccount';
const EVENT_AFTER_CHANGE_PASSWORD = 'Users.Component.UsersAuth.afterResetPassword';
const EVENT_ON_EXPIRED_TOKEN = 'Users.Component.UsersAuth.onExpiredToken';
const EVENT_AFTER_RESEND_TOKEN_VALIDATION = 'Users.Component.UsersAuth.afterResendTokenValidation';
/**
* Initialize method, setup Auth if not already done passing the $config provided and
* setup the default table to Users.Users if not provided
*
* @param array $config config options
* @return void
*/
public function initialize(array $config)
{
parent::initialize($config);
$this->_validateConfig();
$this->_initAuth();
if (Configure::read('Users.Social.login')) {
$this->_loadSocialLogin();
}
if (Configure::read('Users.RememberMe.active')) {
$this->_loadRememberMe();
}
if ($this->getTwoFactorAuthenticationChecker()->isEnabled()) {
$this->_loadGoogleAuthenticator();
}
$this->_attachPermissionChecker();
}
/**
* Load GoogleAuthenticator object
*
* @return void
*/
protected function _loadGoogleAuthenticator()
{
$this->getController()->loadComponent('CakeDC/Users.GoogleAuthenticator');
}
/**
* Load Social Auth object
*
* @return void
*/
protected function _loadSocialLogin()
{
$this->getController()->Auth->setConfig('authenticate', [
Configure::read('Users.Social.authenticator')
], true);
}
/**
* Load RememberMe component and Auth objects
*
* @return void
*/
protected function _loadRememberMe()
{
$this->getController()->loadComponent('CakeDC/Users.RememberMe');
}
/**
* Attach the isUrlAuthorized event to allow using the Auth authorize from the UserHelper
*
* @return void
*/
protected function _attachPermissionChecker()
{
EventManager::instance()->on(self::EVENT_IS_AUTHORIZED, [], [$this, 'isUrlAuthorized']);
}
/**
* Initialize the AuthComponent and configure allowed actions
*
* @return void
*/
protected function _initAuth()
{
if (Configure::read('Users.auth')) {
//initialize Auth
$this->getController()->loadComponent('Auth', Configure::read('Auth'));
}
list($plugin, $controller) = pluginSplit(Configure::read('Users.controller'));
if ($this->getController()->getRequest()->getParam('plugin', null) === $plugin &&
$this->getController()->getRequest()->getParam('controller') === $controller
) {
$this->getController()->Auth->allow([
// LoginTrait
'twitterLogin',
'login',
'socialEmail',
'verify',
// RegisterTrait
'register',
'validateEmail',
// PasswordManagementTrait used in RegisterTrait
'changePassword',
'resetPassword',
'requestResetPassword',
// UserValidationTrait used in PasswordManagementTrait
'resendTokenValidation',
// Social
'endpoint',
'authenticated',
'u2f',
'u2fRegister',
'u2fRegisterFinish',
'u2fAuthenticate',
'u2fAuthenticateFinish',
]);
}
}
/**
* Check if a given url is authorized
*
* @param Event $event event
*
* @return bool
*/
public function isUrlAuthorized(Event $event)
{
$url = Hash::get((array)$event->getData(), 'url');
if (empty($url)) {
return false;
}
if (is_array($url)) {
$requestUrl = Router::normalize(Router::reverse($url));
$requestParams = Router::parseRequest(new ServerRequest($requestUrl));
} else {
try {
//remove base from $url if exists
$normalizedUrl = Router::normalize($url);
$requestParams = Router::parseRequest(new ServerRequest($normalizedUrl));
} catch (MissingRouteException $ex) {
//if it's a url pointing to our own app
if (substr($normalizedUrl, 0, 1) === '/') {
throw $ex;
}
return true;
}
$requestUrl = $url;
}
// check if controller action is allowed
if ($this->_isActionAllowed($requestParams)) {
return true;
}
// check we are logged in
$user = $this->getController()->Auth->user();
if (empty($user)) {
return false;
}
$request = new ServerRequest($requestUrl);
$request = $request->withAttribute('params', $requestParams);
$isAuthorized = $this->getController()->Auth->isAuthorized(null, $request);
return $isAuthorized;
}
/**
* Validate if the passed configuration makes sense
*
* @throws BadConfigurationException
* @return void
*/
protected function _validateConfig()
{
if (!Configure::read('Users.Email.required') && Configure::read('Users.Email.validate')) {
$message = __d('CakeDC/Users', 'You can\'t enable email validation workflow if use_email is false');
throw new BadConfigurationException($message);
}
}
/**
* Check if the action is in allowedActions array for the controller
* Important, this function will check only for allowed actions in the current
* controller, creating a new instance and providing initialization for the Auth
* instance in another controller could lead to undesired side effects.
*
* @param array $requestParams request parameters
* @return bool
*/
protected function _isActionAllowed($requestParams = [])
{
if (empty($requestParams['action'])) {
return false;
}
if (!empty($requestParams['controller']) && $requestParams['controller'] !== $this->getController()->getName()) {
return false;
}
$action = strtolower($requestParams['action']);
if (in_array($action, array_map('strtolower', $this->getController()->Auth->allowedActions))) {
return true;
}
return false;
}
/**
* Get the configured two factory authentication
*
* @return \CakeDC\Users\Auth\TwoFactorAuthenticationCheckerInterface
*/
protected function getTwoFactorAuthenticationChecker()
{
return (new TwoFactorAuthenticationCheckerFactory())->build();
}
}