-
Notifications
You must be signed in to change notification settings - Fork 452
/
controller.php
428 lines (372 loc) · 15.8 KB
/
controller.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
<?php
namespace Concrete\Authentication\Concrete;
use Concrete\Core\Authentication\AuthenticationTypeController;
use Concrete\Core\Config\Repository\Repository;
use Concrete\Core\Database\Connection\Connection;
use Concrete\Core\Encryption\PasswordHasher;
use Concrete\Core\Error\UserMessageException;
use Concrete\Core\Support\Facade\Application;
use Concrete\Core\User\Exception\FailedLoginThresholdExceededException;
use Concrete\Core\User\Exception\InvalidCredentialsException;
use Concrete\Core\User\Exception\UserDeactivatedException;
use Concrete\Core\User\Exception\UserException;
use Concrete\Core\User\Exception\UserPasswordResetException;
use Concrete\Core\User\Login\LoginService;
use Concrete\Core\User\User;
use Concrete\Core\User\PersistentAuthentication\CookieService;
use Concrete\Core\User\ValidationHash;
use Concrete\Core\Validation\CSRF\Token;
use Config;
use Core;
use Database;
use Exception;
use Session;
use UserInfo;
use View;
use Concrete\Core\Validator\String\EmailValidator;
class Controller extends AuthenticationTypeController
{
public $apiMethods = ['forgot_password', 'v', 'change_password', 'password_changed', 'email_validated', 'invalid_token', 'required_password_upgrade'];
public function getHandle()
{
return 'concrete';
}
public function deauthenticate(User $u)
{
$authCookie = $this->app->make(CookieService::class)->getCookie();
if ($authCookie === null || $authCookie->getAuthenticationTypeHandle() !== 'concrete') {
return;
}
$hasher = $this->app->make(PasswordHasher::class);
$db = $this->app->make(Connection::class);
foreach ($db->fetchAll('select token from authTypeConcreteCookieMap WHERE uID = ? ORDER BY validThrough DESC', [$authCookie->getUserID()]) as $row) {
if ($hasher->checkPassword($authCookie->getToken(), $row['token'])) {
$db->delete('authTypeConcreteCookieMap', ['uID' => $authCookie->getUserID(), 'token' => $row['token']]);
}
}
}
public function getAuthenticationTypeIconHTML()
{
return '<i class="fas fa-user"></i>';
}
public function verifyHash(User $u, $hash)
{
$uID = (int) $u->getUserID();
$db = $this->app->make(Connection::class);
$hasher = $this->app->make(PasswordHasher::class);
$validRow = false;
$validThrough = (new \DateTime())->getTimestamp();
$rows = $db->fetchAll('SELECT validThrough, token FROM authTypeConcreteCookieMap WHERE uID = ? AND validThrough > ? ORDER BY validThrough DESC', [$uID, $validThrough]);
foreach ($rows as $row) {
if ($hasher->checkPassword($hash, $row['token'])) {
$validRow = true;
break;
}
}
// delete all invalid entries for this user
$db->executeUpdate('DELETE FROM authTypeConcreteCookieMap WHERE uID = ? AND validThrough < ?', [$uID, $validThrough]);
return $validRow;
}
public function view()
{
}
public function buildHash(User $u, $test = 1)
{
if ($test > 10) {
// This should only ever happen if by some stroke of divine intervention,
// we end up pulling 10 hashes that already exist. the chances of this are very very low.
throw new \Exception(t('There was a database error, try again.'));
}
$db = Database::connection();
$validThrough = time() + (int) $this->app->make('config')->get('concrete.session.remember_me.lifetime');
$token = $this->genString();
$hasher = $this->app->make(PasswordHasher::class);
try {
$db->executeQuery(
'INSERT INTO authTypeConcreteCookieMap (token, uID, validThrough) VALUES (?,?,?)',
[$hasher->hashPassword($token), $u->getUserID(), $validThrough]
);
} catch (\Exception $e) {
// HOLY CRAP.. SERIOUSLY?
$this->buildHash($u, ++$test);
}
return $token;
}
private function genString($a = 16)
{
if (function_exists('random_bytes')) { // PHP7+
return bin2hex(random_bytes($a));
}
if (function_exists('mcrypt_create_iv')) {
// Use /dev/urandom if available, otherwise fall back to PHP's rand (below)
// Don't use (MCRYPT_DEV_URANDOM|MCRYPT_RAND) here, because we prefer
// openssl first.
// Use @ here because otherwise mcrypt throws a noisy warning if
// /dev/urandom is missing.
$iv = @mcrypt_create_iv($a, MCRYPT_DEV_URANDOM);
if ($iv !== false) {
return bin2hex($iv);
}
}
// don't use elseif, we need the fallthrough here.
if (function_exists('openssl_random_pseudo_bytes')) {
$iv = openssl_random_pseudo_bytes($a, $crypto_strong);
if ($iv !== false && $crypto_strong) {
return bin2hex($iv);
}
}
// this means we've not yet returned, so MCRYPT_DEV_URANDOM isn't available.
if (function_exists('mcrypt_create_iv')) {
// terrible, but still better than what we're doing below
$iv = mcrypt_create_iv($a, MCRYPT_RAND);
if ($iv !== false) {
return bin2hex($iv);
}
}
// This really is a last resort.
$o = '';
$chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+{}|":<>?\'\\';
$l = strlen($chars);
while ($a--) {
$o .= substr($chars, rand(0, $l), 1);
}
return md5($o);
}
public function isAuthenticated(User $u)
{
return $u->isRegistered();
}
public function saveAuthenticationType($values)
{
}
/**
* Called when a user tries to log in after his password has been reset by "Global Password Reset".
*/
public function required_password_upgrade()
{
$email = $this->post('uEmail');
$token = $this->app->make(Token::class);
$this->set('token', $token);
if ($email) {
$errorValidator = Core::make('helper/validation/error');
$userInfo = Core::make('Concrete\Core\User\UserInfoRepository')->getByName(Session::get('uPasswordResetUserName'));
try {
if ($userInfo && $email != $userInfo->getUserEmail()) {
throw new \Exception(t(sprintf('Invalid email address %s provided resetting a password', $email)));
}
} catch (\Exception $e) {
$errorValidator->add($e);
}
$this->forgot_password();
} else {
$this->set('authType', $this->getAuthenticationType());
$this->set('intro_msg', Core::make('config/database')->get('concrete.password.reset.message'));
}
}
/**
* Called when a user wants a password reset email sent, is passed in the user's email address.
*/
public function forgot_password()
{
$loginData['success'] = 0;
$error = $this->app->make('helper/validation/error');
$em = $this->post('uEmail');
$token = $this->app->make(Token::class);
$this->set('authType', $this->getAuthenticationType());
$this->set('token', $token);
if ($em) {
try {
if (!$token->validate()) {
throw new \Exception($token->getErrorMessage());
}
$e = $this->app->make('error');
if (!$this->app->make(EmailValidator::class)->isValid($em, $e)) {
throw new \Exception($e->toText());
}
$oUser = UserInfo::getByEmail($em);
if ($oUser) {
$mh = $this->app->make('helper/mail');
//$mh->addParameter('uPassword', $oUser->resetUserPassword());
if (Config::get('concrete.user.registration.email_registration')) {
$mh->addParameter('uName', $oUser->getUserEmail());
} else {
$mh->addParameter('uName', $oUser->getUserName());
}
$mh->to($oUser->getUserEmail());
//generate hash that'll be used to authenticate user, allowing them to change their password
$h = new ValidationHash();
$uHash = $h->add($oUser->getUserID(), intval(UVTYPE_CHANGE_PASSWORD), true);
$changePassURL = View::url(
'/login',
'callback',
$this->getAuthenticationType()->getAuthenticationTypeHandle(),
'change_password',
$uHash);
$mh->addParameter('changePassURL', $changePassURL);
$fromEmail = (string) Config::get('concrete.email.forgot_password.address');
if (!strpos($fromEmail, '@')) {
$adminUser = UserInfo::getByID(USER_SUPER_ID);
if (is_object($adminUser)) {
$fromEmail = $adminUser->getUserEmail();
} else {
$fromEmail = '';
}
}
if ($fromEmail) {
$fromName = (string) Config::get('concrete.email.forgot_password.name');
if ($fromName === '') {
$fromName = t('Forgot Password');
}
$mh->from($fromEmail, $fromName);
}
$mh->addParameter('siteName', tc('SiteName', $this->app->make('site')->getSite()->getSiteName()));
$mh->load('forgot_password');
@$mh->sendMail();
}
} catch (\Exception $e) {
$error->add($e);
}
if ($error->has()) {
$this->set('error', $error);
} else {
$this->redirect('/login', $this->getAuthenticationType()->getAuthenticationTypeHandle(),
'password_sent');
}
}
}
public function change_password($uHash = '')
{
$this->set('authType', $this->getAuthenticationType());
$e = Core::make('helper/validation/error');
if (is_string($uHash)) {
$ui = UserInfo::getByValidationHash($uHash);
} else {
$ui = null;
}
if (is_object($ui)) {
$vh = new ValidationHash();
if ($vh->isValid($uHash)) {
if (isset($_POST['uPassword']) && strlen($_POST['uPassword'])) {
Core::make('validator/password')->isValidFor($_POST['uPassword'], $ui, $e);
if (strlen($_POST['uPassword']) && $_POST['uPasswordConfirm'] != $_POST['uPassword']) {
$e->add(t('The two passwords provided do not match.'));
}
if (!$e->has()) {
$ui->changePassword($_POST['uPassword']);
$h = Core::make('helper/validation/identifier');
$h->deleteKey('UserValidationHashes', 'uHash', $uHash);
$this->set('passwordChanged', true);
$this->redirect('/login', $this->getAuthenticationType()->getAuthenticationTypeHandle(), 'password_changed');
} else {
$this->set('error', $e);
}
}
$this->set('uHash', $uHash);
$this->set('authTypeElement', 'change_password');
return;
}
}
$this->redirect('/login', $this->getAuthenticationType()->getAuthenticationTypeHandle(), 'invalid_token');
}
public function password_changed()
{
$this->view();
}
public function email_validated($mode = false)
{
if ($mode) {
$this->set('workflowPending', true);
$this->set('validated', false);
} else {
$this->set('validated', true);
}
$this->view();
}
public function invalid_token()
{
$this->view();
}
public function authenticate()
{
$post = $this->post();
if (empty($post['uName']) || empty($post['uPassword'])) {
/** @var Repository $config */
$config = $this->app->make(Repository::class);
if ($config->get('concrete.user.registration.email_registration')) {
throw new Exception(t('Please provide both email address and password.'));
} else {
throw new Exception(t('Please provide both username and password.'));
}
}
$uName = $post['uName'];
$uPassword = $post['uPassword'];
/** @var \Concrete\Core\Permission\IPService $ip_service */
$ip_service = Core::make('ip');
if ($ip_service->isDenylisted()) {
throw new \Exception($ip_service->getErrorMessage());
}
$loginService = $this->app->make(LoginService::class);
try {
$user = $loginService->login($uName, $uPassword);
} catch (UserPasswordResetException $e) {
Session::set('uPasswordResetUserName', $this->post('uName'));
$this->redirect('/login/', $this->getAuthenticationType()->getAuthenticationTypeHandle(), 'required_password_upgrade');
} catch (UserException $e) {
$this->handleFailedLogin($loginService, $uName, $uPassword, $e);
}
if ($user->isError()) {
throw new UserMessageException(t('Unknown login error occurred. Please try again.'));
}
if (isset($post['uMaintainLogin']) && $post['uMaintainLogin']) {
$user->setAuthTypeCookie('concrete');
}
$loginService->logLoginAttempt($uName);
return $user;
}
protected function handleFailedLogin(LoginService $loginService, $uName, $uPassword, UserException $e)
{
if ($e instanceof InvalidCredentialsException) {
// Track the failed login
try {
$loginService->failLogin($uName, $uPassword);
} catch (FailedLoginThresholdExceededException $e) {
$loginService->logLoginAttempt($uName, ['Failed Login Threshold Exceeded', $e->getMessage()]);
// Rethrow the failed threshold error
throw $e;
} catch (UserDeactivatedException $e) {
$loginService->logLoginAttempt($uName, ['User Deactivated', $e->getMessage()]);
// Rethrow the user deactivated exception
throw $e;
}
}
$loginService->logLoginAttempt($uName, ['Invalid Credentials', $e->getMessage()]);
// Rethrow the exception
throw $e;
}
private function isPasswordReset()
{
$app = Application::getFacadeApplication();
$db = $app['database']->connection();
if (Config::get('concrete.user.registration.email_registration')) {
return $db->GetOne('select uIsPasswordReset from Users where uEmail = ?', [$this->post('uName')]);
} else {
return $db->GetOne('select uIsPasswordReset from Users where uName = ?', [$this->post('uName')]);
}
}
public function v($hash = '')
{
$ui = UserInfo::getByValidationHash($hash);
if (is_object($ui)) {
$ui->markValidated();
$this->set('uEmail', $ui->getUserEmail());
if ($ui->triggerActivate('register_activate', USER_SUPER_ID)) {
$mode = '';
} else {
$mode = 'workflow';
}
$this->redirect('/login/callback/concrete', 'email_validated', $mode);
exit;
}
$this->redirect('/login/callback/concrete', 'invalid_token');
}
}