-
-
Notifications
You must be signed in to change notification settings - Fork 998
Expand file tree
/
Copy pathAuth.php
More file actions
759 lines (610 loc) · 23.2 KB
/
Copy pathAuth.php
File metadata and controls
759 lines (610 loc) · 23.2 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
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
<?php
namespace Leantime\Domain\Auth\Services;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Session\SessionManager;
use Illuminate\Support\Facades\Log;
use Laravel\Sanctum\HasApiTokens;
use Leantime\Core\Configuration\Environment as EnvironmentCore;
use Leantime\Core\Controller\Frontcontroller as FrontcontrollerCore;
use Leantime\Core\Events\DispatchesEvents;
use Leantime\Core\Language as LanguageCore;
use Leantime\Core\Mailer as MailerCore;
use Leantime\Core\UI\Theme;
use Leantime\Domain\Auth\Models\Roles;
use Leantime\Domain\Auth\Repositories\AccessTokenRepository;
use Leantime\Domain\Auth\Repositories\Auth as AuthRepository;
use Leantime\Domain\Ldap\Services\Ldap;
use Leantime\Domain\Setting\Repositories\Setting as SettingRepository;
use Leantime\Domain\Users\Repositories\Users as UserRepository;
use Ramsey\Uuid\Uuid;
use RobThree\Auth\TwoFactorAuth;
class Auth implements Authenticatable
{
use DispatchesEvents, HasApiTokens, \Illuminate\Auth\Authenticatable;
/**
* @var int|null user id from DB
*/
private ?int $userId = null;
/**
* @var int|null user id from DB
*/
private ?int $clientId = null;
/**
* @var string|null username from db
*/
private ?string $username = null;
/**
* @var string username from db
*/
private string $name = '';
/**
* @var string profileid (image) from db
*/
private string $profileId = '';
private ?string $password = null;
/**
* @var string|null username (emailaddress)
*/
private ?string $user = null;
/**
* @var string|null username (emailaddress)
*/
private ?string $mail = null;
private bool $twoFAEnabled;
private string $twoFASecret;
private ?SessionManager $session = null;
/**
* @var string userrole (admin, client, employee)
*/
public string $role = '';
public array $settings = [];
/**
* @var int time for cookie
*/
public mixed $cookieTime;
public string $error = '';
public string $success = '';
public string|bool $resetInProgress = false;
/**
* How often can a user reset a password before it has to be changed
*/
public int $pwResetLimit = 5;
private EnvironmentCore $config;
public LanguageCore $language;
public SettingRepository $settingsRepo;
public AuthRepository $authRepo;
public UserRepository $userRepo;
private AccessTokenRepository $tokenRepo;
/**
* __construct - getInstance of session and get sessionId and refers to login if post is set
*
* @throws BindingResolutionException
*/
public function __construct(
EnvironmentCore $config,
?SessionManager $session,
LanguageCore $language,
SettingRepository $settingsRepo,
AuthRepository $authRepo,
UserRepository $userRepo,
AccessTokenRepository $tokenRepo
) {
$this->config = $config;
$this->session = $session;
$this->language = $language;
$this->settingsRepo = $settingsRepo;
$this->authRepo = $authRepo;
$this->userRepo = $userRepo;
$this->tokenRepo = $tokenRepo;
$this->cookieTime = $this->config->sessionExpiration;
}
/**
* @return string|bool returns role as string or false on failure
*
* @throws BindingResolutionException
*/
public static function getRoleToCheck(bool $forceGlobalRoleCheck): string|bool
{
if (session()->exists('userdata') === false) {
return false;
}
if ($forceGlobalRoleCheck) {
$roleToCheck = session('userdata.role');
// If projectRole is not defined or if it is set to inherited
} elseif (! session()->exists('userdata.projectRole') || session('userdata.projectRole') == 'inherited' || session('userdata.projectRole') == '') {
$roleToCheck = session('userdata.role');
// Do not overwrite admin or owner roles
} elseif (session('userdata.role') == Roles::$owner || session('userdata.role') == Roles::$admin || session('userdata.role') == Roles::$manager) {
$roleToCheck = session('userdata.role');
// In all other cases check the project role
} else {
$roleToCheck = session('userdata.projectRole');
}
// Ensure the role is a valid role. An unresolvable role here makes the permission engine
// deny EVERYTHING (every #[RequiresPermission] check fails) — so log it loudly with
// context. This exact breadcrumb ("invalid role detected: 50") is what surfaced the 3.9.x
// Bearer regression where a session stored the raw role int instead of its name string.
if (in_array($roleToCheck, Roles::getRoles()) === false) {
Log::warning('Invalid role in session — authorization will deny everything. Resolved role: '.var_export($roleToCheck, true).' (user '.(session('userdata.id') ?? 'guest').'). Expected one of: '.implode(', ', Roles::getRoles()));
return false;
}
return $roleToCheck;
}
/**
* login - Validate POST-data with DB
*
*
*
* @throws BindingResolutionException
*/
public function login(string $username, string $password): bool
{
self::dispatch_event('beforeLoginCheck', ['username' => $username, 'password' => $password]);
// different identity providers can live here
// they all need to
// // A: ensure the user is in leantime (with a valid role) and if not create the user
// // B: set the session variables
// // C: update users from the identity provider,
// Try Ldap
if ($this->config->useLdap === true && extension_loaded('ldap')) {
$ldap = app()->make(Ldap::class);
if ($ldap->connect() && $ldap->bind($username, $password)) {
// Update username to include domain
$usernameWDomain = $ldap->getEmail($username);
// Get user
$user = $this->userRepo->getUserByEmail($usernameWDomain);
$ldapUser = $ldap->getSingleUser($username);
if ($ldapUser === false) {
return false;
}
// If user does not exist create user
if (! $user) {
$userArray = [
'firstname' => $ldapUser['firstname'],
'lastname' => $ldapUser['lastname'],
'phone' => $ldapUser['phone'],
'user' => $ldapUser['user'],
'role' => $ldapUser['role'],
'department' => $ldapUser['department'],
'jobTitle' => $ldapUser['jobTitle'],
'jobLevel' => $ldapUser['jobLevel'],
'password' => '',
'clientId' => '',
'source' => 'ldap',
'status' => 'a',
];
$userId = $this->userRepo->addUser($userArray);
if ($userId !== false) {
$user = $this->userRepo->getUserByEmail($usernameWDomain);
} else {
Log::error('Ldap user creation failed.');
return false;
}
// @TODO: create a better login response. This will return that the username or password was not correct
} else {
$user['firstname'] = $ldapUser['firstname'];
$user['lastname'] = $ldapUser['lastname'];
$user['phone'] = $ldapUser['phone'];
$user['user'] = $user['username'];
$user['department'] = $ldapUser['department'];
$user['jobTitle'] = $ldapUser['jobTitle'];
$user['jobLevel'] = $ldapUser['jobLevel'];
$this->userRepo->editUser($user, $user['id']);
}
if ($user !== false && is_array($user)) {
$this->setUserSession($user, true);
return true;
} else {
Log::info('Could not retrieve user by email');
return false;
}
}
// Don't return false, to allow the standard login provider to check the db for contractors or clients not
// in ldap
} elseif ($this->config->useLdap === true && ! extension_loaded('ldap')) {
Log::error("Can't use ldap. Extension not installed");
}
// TODO: Single Sign On?
// Standard login
// Check if the user is in our db
// Check even if ldap is turned on to allow contractors and clients to have an account
$user = $this->authRepo->getUserByLogin($username, $password);
if ($user !== false && is_array($user)) {
$this->setUserSession($user);
self::dispatch_event('afterLoginCheck', ['username' => $username, 'password' => $password, 'authService' => app()->make(self::class)]);
return true;
} else {
$this->logFailedLogin($username);
self::dispatch_event('afterLoginCheck', ['username' => $username, 'password' => $password, 'authService' => app()->make(self::class)]);
return false;
}
}
/**
* Create a new personal access token
*/
public function createToken(string $name, array $abilities = ['*']): array
{
if (! $this->loggedIn()) {
throw new \Exception('User must be authenticated to create token');
}
return $this->tokenRepo->createToken($this->getUserId(), $name, $abilities);
}
/**
* @return false|void
*
* @throws BindingResolutionException
*/
public function setUserSession(mixed $user, bool $isExternalAuth = false)
{
if (! $user || ! is_array($user)) {
return false;
}
// Web-login session. twoFAVerified: false — the web flow enforces interactive 2FA via the
// AuthCheck gate. Built via the shared factory (role NAME string + consistent fields), with
// the web-only globalUserId added on top.
$currentUser = UserSessionBuilder::build($user, isExternalAuth: $isExternalAuth, twoFAVerified: false);
$currentUser['globalUserId'] = Uuid::uuid5(Uuid::NAMESPACE_DNS, strtolower($user['username']));
$currentUser = self::dispatch_filter('user_session_vars', $currentUser);
session(['userdata' => $currentUser]);
session(['usersettings' => $currentUser['settings']]);
$this->updateUserSessionDB($currentUser['id'], session()->getId());
// Clear user theme cache on login
Theme::clearCache();
}
public function updateUserSessionDB(int $userId, string $sessionID): bool
{
return $this->authRepo->updateUserSession($userId, $sessionID, time());
}
/**
* logged_in - Check if logged in and Update sessions
*/
public function loggedIn(): bool
{
// Check if we actually have a php session available
if (session()->exists('userdata')) {
return true;
// If the session doesn't have any session data we are out of sync. Start again
} else {
return false;
}
}
/**
* Checks if a user is logged in.
*
* @return bool Returns true if the user is logged in, false otherwise.
*/
public static function isLoggedIn(): bool
{
// Check if we actually have a php session available
if (session()->exists('userdata')) {
return true;
} else {
return false;
}
}
/**
* logout - destroy sessions and cookies
*
*
* @throws BindingResolutionException
*/
public function logout(): void
{
$this->authRepo->invalidateSession($this->session->getId());
$sessionsToDestroy = self::dispatch_filter('sessions_vars_to_destroy', [
'userdata',
'template',
'subdomainData',
'currentProject',
'currentSprint',
'projectsettings',
'currentSubscriptions',
'lastTicketView',
'lastFilteredTicketTableView',
]);
foreach ($sessionsToDestroy as $key) {
session()->forget($key);
}
self::dispatch_event('afterSessionDestroy', ['authService' => app()->make(self::class)]);
}
/**
* validateResetLink - validates that the password reset link belongs to a user account in the database
*
* @param string $hash invite link hash
*/
public function validateResetLink(string $hash): bool
{
return $this->authRepo->validateResetLink($hash);
}
/**
* getUserByInviteLink - gets the user by invite link
*
* @param string $hash invite link hash
*/
public function getUserByInviteLink(string $hash): bool|array
{
return $this->authRepo->getUserByInviteLink($hash);
}
/**
* generateLinkAndSendEmail - generates an invitation link (hash) and sends email to user
*
* @param string $username new user to be invited (email)
* @return bool returns true on success, false on failure
*
* @throws BindingResolutionException
*/
public function generateLinkAndSendEmail(string $username): bool
{
$userFromDB = $this->userRepo->getUserByEmail($username);
if ($userFromDB !== false && count($userFromDB) > 0) {
if ($userFromDB['pwResetCount'] < $this->pwResetLimit) {
$permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyz';
$resetLink = substr(str_shuffle($permitted_chars), 0, 32);
$result = $this->authRepo->setPWResetLink($username, $resetLink);
if ($result) {
// Don't queue, send right away
$mailer = app()->make(MailerCore::class);
$mailer->setContext('password_reset');
$mailer->setSubject($this->language->__('email_notifications.password_reset_subject'));
$actual_link = ''.BASE_URL.'/auth/resetPw/'.$resetLink;
$mailer->setHtml(sprintf($this->language->__('email_notifications.password_reset_message'), $actual_link));
$to = [$username];
$mailer->sendMail($to, 'Leantime System');
return true;
}
} elseif ($this->config->debug) {
Log::warning('PW reset failed: maximum request count has been reached for user '.$userFromDB['id']);
}
}
return false;
}
public function changePw(string $password, string $hash): bool
{
return $this->authRepo->changePW($password, $hash);
}
/**
* checkPasswordStrength - validates that a password meets the minimum strength requirements.
*
* Password must be at least 8 characters and include an upper case letter,
* a lower case letter, a number and a special character.
*
* @param string $password the password to validate
* @return bool returns true if the password is strong enough, false otherwise
*/
public function checkPasswordStrength(string $password): bool
{
$uppercase = preg_match('@[A-Z]@', $password);
$lowercase = preg_match('@[a-z]@', $password);
$number = preg_match('@[0-9]@', $password);
$specialChars = preg_match('@[^\w]@', $password);
if (! $uppercase || ! $lowercase || ! $number || ! $specialChars || strlen($password) < 8) {
return false;
}
return true;
}
/**
* resetPassword - validates and applies a password reset for a given reset link.
*
* Performs the password match check, strength check and persists the new
* password. Returns a status string the caller can map to a notification:
* 'success', 'mismatch', 'weak' or 'error'.
*
* @param string $password the new password
* @param string $passwordConfirm the password confirmation
* @param string $hash the password reset link hash
* @return string one of 'success', 'mismatch', 'weak', 'error'
*
* @api
*/
public function resetPassword(string $password, string $passwordConfirm, string $hash): string
{
if (strlen($password) === 0 || $password !== $passwordConfirm) {
return 'mismatch';
}
if (! $this->checkPasswordStrength($password)) {
return 'weak';
}
if ($this->changePw($password, $hash)) {
return 'success';
}
return 'error';
}
/**
* resolveSafeRedirect - resolves a user supplied redirect target into a safe,
* application-internal absolute URL, guarding against open redirects.
*
* @param string|null $redirect the raw redirect target (typically from the request)
* @return string an absolute URL that is safe to redirect to
*
* @api
*/
public function resolveSafeRedirect(?string $redirect): string
{
$redirectUrl = BASE_URL.'/dashboard/home';
if ($redirect !== null && trim($redirect) !== '' && trim($redirect) !== '/') {
$url = urldecode($redirect);
// Check for open redirects, don't allow redirects to external sites.
if (
filter_var($url, FILTER_VALIDATE_URL) === false &&
! in_array($url, ['/auth/logout'])
) {
$redirectUrl = BASE_URL.'/'.$url;
}
}
return $redirectUrl;
}
/**
* shouldHideLoginForm - determines whether the default login form should be hidden,
* combining the admin setting with the configured disableLoginForm flag.
*
* @return bool returns true if the default login form should be hidden
*
* @api
*/
public function shouldHideLoginForm(): bool
{
$hideLogin = $this->settingsRepo->getSetting('auth.hideDefaultLogin');
if (! empty($hideLogin) && $hideLogin == 'on') {
return true;
}
return (bool) $this->config->disableLoginForm;
}
/**
* getLoginInputPlaceholder - returns the translation key for the login input placeholder
* depending on whether LDAP authentication is enabled.
*
* @return string the placeholder translation key
*
* @api
*/
public function getLoginInputPlaceholder(): string
{
if ($this->config->useLdap) {
return 'input.placeholders.enter_email_or_username';
}
return 'input.placeholders.enter_email';
}
/**
* @throws BindingResolutionException
*/
public static function userIsAtLeast(string $role, bool $forceGlobalRoleCheck = false): bool
{
// Force Global Role check to circumvent projectRole checks for global controllers (users, projects, clients etc)
$roleToCheck = self::getRoleToCheck($forceGlobalRoleCheck);
if ($roleToCheck === false) {
return false;
}
$testKey = array_search($role, Roles::getRoles());
if ($role == '' || $testKey === false) {
Log::warning('Check for invalid role detected: '.$role);
return false;
}
$currentUserKey = array_search($roleToCheck, Roles::getRoles());
if ($testKey <= $currentUserKey) {
return true;
} else {
return false;
}
}
/**
* @throws HttpResponseException
*/
public static function authOrRedirect(array|string $role, bool $forceGlobalRoleCheck = false): bool
{
if (self::userHasRole($role, $forceGlobalRoleCheck)) {
return true;
}
throw new HttpResponseException(FrontcontrollerCore::redirect(BASE_URL.'/errors/error403'));
}
/**
* @throws BindingResolutionException
*/
public static function userHasRole(string|array $role, bool $forceGlobalRoleCheck = false): bool
{
// Force Global Role check to circumvent projectRole checks for global controllers (users, projects, clients etc)
$roleToCheck = self::getRoleToCheck($forceGlobalRoleCheck);
if (is_array($role) && in_array($roleToCheck, $role)) {
return true;
} elseif ($role == $roleToCheck) {
return true;
}
return false;
}
public static function getRole(): void {}
public static function getUserClientId(): mixed
{
return session('userdata.clientId');
}
public static function getUserId(): mixed
{
return session('userdata.id');
}
public function use2FA(): mixed
{
return session('userdata.twoFAEnabled');
}
public function verify2FA(string $code): bool
{
$twoFactorAuthentication = new TwoFactorAuth('Leantime');
return $twoFactorAuthentication->verifyCode(session('userdata.twoFASecret'), $code);
}
public function get2FAVerified(): mixed
{
return session('userdata.twoFAVerified');
}
public function set2FAVerified(): void
{
session(['userdata.twoFAVerified' => true]);
}
private function logFailedLogin(string $user): void
{
$user = $user == '' ? 'unknown' : $user;
$date = new \DateTime;
$date = $date->format('y:m:d h:i:s');
$ip = $_SERVER['REMOTE_ADDR'];
$msg = '['.$date.']['.$ip.'] Login failed for user: '.$user;
Log::info($msg);
}
public function getAuthIdentifierName()
{
return 'id';
}
public function getAuthIdentifier()
{
return $this->userId;
}
public function getAuthPassword()
{
return $this->password;
}
public function getAuthPasswordName()
{
return 'password';
}
public function getRememberToken()
{
return ''; // Not implemented yet (Authenticatable::getRememberToken is contractually a string)
}
public function setRememberToken($value)
{
// Not implemented yet
}
public function getRememberTokenName()
{
return 'remember_token';
}
public function getUserById($id)
{
return (object) $this->userRepo->getUser($id);
}
public function validateToken(string $token): bool
{
$user = $this->getUserByToken($token);
if ($user) {
$this->setUserSession($user);
// Turn off 2FA for token verification
$this->set2FAVerified();
return true;
}
return false;
}
public function getUserByToken(string $token): array|bool
{
$tokenModel = $this->tokenRepo->findToken($token);
if (! $tokenModel) {
return false;
}
if ($tokenModel['expires_at'] && strtotime($tokenModel['expires_at']) < time()) {
return false;
}
// Load the user associated with this token
$user = $this->userRepo->getUser($tokenModel['tokenable_id']);
if (! $user) {
return false;
}
$this->tokenRepo->updateLastUsedAt($tokenModel['id']);
return $user;
}
}