GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — hypernext ( 1f9f67...b8f172 )
by Nico
03:15
created

Local::tryAuth()   B

Complexity

Conditions 9
Paths 7

Size

Total Lines 46
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 10.0285

Importance

Changes 0
Metric Value
cc 9
eloc 31
nc 7
nop 0
dl 0
loc 46
ccs 23
cts 30
cp 0.7667
crap 10.0285
rs 8.0555
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @author Nicolas CARPi <[email protected]>
5
 * @copyright 2012 Nicolas CARPi
6
 * @see https://www.elabftw.net Official website
7
 * @license AGPL-3.0
8
 * @package elabftw
9
 */
10
11
declare(strict_types=1);
12
13
namespace Elabftw\Auth;
14
15
use DateTimeImmutable;
16
use Elabftw\Elabftw\AuthResponse;
17
use Elabftw\Elabftw\Db;
0 ignored issues
show
Bug introduced by
The type Elabftw\Elabftw\Db was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
18
use Elabftw\Enums\EnforceMfa;
19
use Elabftw\Exceptions\ImproperActionException;
20
use Elabftw\Exceptions\InvalidCredentialsException;
21
use Elabftw\Exceptions\QuantumException;
22
use Elabftw\Exceptions\ResourceNotFoundException;
23
use Elabftw\Interfaces\AuthInterface;
24
use Elabftw\Models\ExistingUser;
25
use Elabftw\Models\Users;
26
use Elabftw\Services\Filter;
0 ignored issues
show
Bug introduced by
The type Elabftw\Services\Filter was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
27
use Elabftw\Services\UsersHelper;
28
use PDO;
29
use SensitiveParameter;
0 ignored issues
show
Bug introduced by
The type SensitiveParameter was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
30
use Override;
0 ignored issues
show
Bug introduced by
The type Override was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
31
32
use function password_hash;
33
use function password_needs_rehash;
34
use function password_verify;
35
36
/**
37
 * Local auth service
38
 */
39
final class Local implements AuthInterface
40
{
41
    private Db $Db;
42
43
    private int $userid;
44
45
    private AuthResponse $AuthResponse;
46
47
    public function __construct(
48 8
        private string $email,
49
        #[SensitiveParameter]
50 8
        private readonly string $password,
51 1
        private readonly bool $isDisplayed = true,
52
        private readonly bool $isOnlySysadminWhenHidden = false,
53 8
        private readonly bool $isOnlySysadmin = false,
54 8
        private readonly int $maxPasswordAgeDays = 0,
55 8
    ) {
56 8
        if (empty($password)) {
57
            throw new QuantumException(_('Invalid email/password combination.'));
58
        }
59 5
        $this->Db = Db::getConnection();
60
        $this->email = Filter::sanitizeEmail($email);
61 5
        $this->userid = $this->getUseridFromEmail();
62 5
        $this->AuthResponse = new AuthResponse();
63 5
    }
64 5
65 5
    #[Override]
66
    public function tryAuth(): AuthResponse
67 5
    {
68 2
        $sql = 'SELECT is_sysadmin, password_hash, mfa_secret, validated, password_modified_at FROM users WHERE userid = :userid;';
69
        $req = $this->Db->prepare($sql);
70
        $req->bindParam(':userid', $this->userid, PDO::PARAM_INT);
71 3
        $this->Db->execute($req);
72
        $res = $req->fetch();
73
74
        // if local_login is disabled, only a sysadmin can login if local_login_hidden_only_sysadmin is set
75
        if (!$this->isDisplayed && $res['is_sysadmin'] === 0 && $this->isOnlySysadminWhenHidden) {
76
            throw new ImproperActionException(_('Only a Sysadmin account can use local authentication when it is hidden.'));
77
        }
78
        // there is also a setting that only allows sysadmins to login
79
        if ($this->isOnlySysadmin && $res['is_sysadmin'] === 0) {
80 3
            throw new ImproperActionException(_('Only a Sysadmin account can use local authentication.'));
81 3
        }
82 3
83 3
        // verify password
84 3
        if (password_verify($this->password, $res['password_hash']) !== true) {
85 3
            throw new InvalidCredentialsException($this->userid);
86 3
        }
87
        // check if it needs rehash (new algo)
88
        if (password_needs_rehash($res['password_hash'], PASSWORD_DEFAULT)) {
89
            $passwordHash = password_hash($this->password, PASSWORD_DEFAULT);
90 3
            $sql = 'UPDATE users SET password_hash = :password_hash WHERE userid = :userid';
91 3
            $req = $this->Db->prepare($sql);
92 3
            $req->bindParam(':password_hash', $passwordHash);
93 3
            $req->bindParam(':userid', $this->userid, PDO::PARAM_INT);
94 3
            $this->Db->execute($req);
95 3
        }
96
        // check if last password modification date was too long ago and require changing it if yes
97
        if ($this->maxPasswordAgeDays > 0) {
98
            $modifiedAt = new DateTimeImmutable($res['password_modified_at']);
99
            $now = new DateTimeImmutable();
100
            $diff = $now->diff($modifiedAt);
101 1
            $daysDifference = (int) $diff->format('%a');
102
            $this->AuthResponse->mustRenewPassword = $daysDifference > $this->maxPasswordAgeDays;
103
        }
104
105 1
        $this->AuthResponse->userid = $this->userid;
106 1
        $this->AuthResponse->mfaSecret = $res['mfa_secret'];
107 1
        $this->AuthResponse->isValidated = (bool) $res['validated'];
108 1
        $UsersHelper = new UsersHelper($this->AuthResponse->userid);
109 1
        $this->AuthResponse->setTeams($UsersHelper);
110
        return $this->AuthResponse;
111
    }
112
113
    /**
114
     * Enforce MFA for user if there is no secret stored?
115 2
     */
116
    public static function enforceMfa(
117 2
        AuthResponse $AuthResponse,
118 2
        int $enforceMfa
119
    ): bool {
120
        return !$AuthResponse->mfaSecret
121 2
            && self::isMfaEnforced(
122 1
                $AuthResponse->userid,
123 2
                $enforceMfa,
124 2
            );
125 1
    }
126 1
127
    /**
128 1
     * Is MFA enforced for a given user (SysAdmin or Everyone)?
129
     */
130
    public static function isMfaEnforced(int $userid, int $enforceMfa): bool
131
    {
132 8
        $EnforceMfaSetting = EnforceMfa::tryFrom($enforceMfa);
133
        $Users = new Users($userid);
134
135 8
        switch ($EnforceMfaSetting) {
136 1
            case EnforceMfa::Everyone:
137
                return true;
138 1
            case EnforceMfa::SysAdmins:
139
                return $Users->userData['is_sysadmin'] === 1;
140 8
            case EnforceMfa::Admins:
141
                return $Users->isAdminSomewhere();
142
            default:
143
                return false;
144
        }
145
    }
146
147
    private function getUseridFromEmail(): int
148
    {
149
        try {
150
            $Users = ExistingUser::fromEmail($this->email);
151
        } catch (ResourceNotFoundException) {
152
            // here we rethrow an quantum exception because we don't want to let the user know if the email exists or not
153
            throw new QuantumException(_('Invalid email/password combination.'));
154
        }
155
        return $Users->userData['userid'];
156
    }
157
}
158