Passed
Push — master ( bda737...e0ed8e )
by Nils
09:32
created

AuthModel::getUserJWT()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 8
rs 10
1
<?php
2
/**
3
 * Teampass - a collaborative passwords manager.
4
 * ---
5
 * This library is distributed in the hope that it will be useful,
6
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
7
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
8
 * ---
9
 *
10
 * @project   Teampass API
11
 *
12
 * @file      AuthModel.php
13
 * ---
14
 *
15
 * @author    Nils Laumaillé ([email protected])
16
 *
17
 * @copyright 2009-2022 Teampass.net
18
 *
19
 * @license   https://spdx.org/licenses/GPL-3.0-only.html#licenseText GPL-3.0
20
 * ---
21
 *
22
 * @see       https://www.teampass.net
23
 */
24
require_once PROJECT_ROOT_PATH . "/Model/Database.php";
25
26
 
27
class AuthModel extends Database
28
{
29
    public function getUserAuth($login, $password, $apikey)
30
    {
31
        // Check if user exists
32
        $userInfo = $this->select("SELECT id, pw FROM " . prefixTable('users') . " WHERE login='".$login."'");
33
        
34
        // Check password
35
        include_once PROJECT_ROOT_PATH . '/../sources/SplClassLoader.php';
36
        $pwdlib = new SplClassLoader('PasswordLib', PROJECT_ROOT_PATH . '/../includes/libraries');
37
        $pwdlib->register();
38
        $pwdlib = new PasswordLib\PasswordLib();
39
        if ($pwdlib->verifyPasswordHash($password, $userInfo[0]['pw']) === true) {
40
            // Correct credentials
41
            // Now check apikey
42
            $apiInfo = $this->select("SELECT count(*) FROM " . prefixTable('api') . " WHERE value='".$apikey."'");
43
            if ((int) $apiInfo[0]['count(*)'] === 1) {
44
                return $this->getUserJWT($userInfo[0]['id'], $login);
45
            } else {
46
                return array("error" => "Login failed.", "apikey" => "Not valid");
47
            }
48
        } else {
49
            return array("error" => "Login failed.", "password" => $password);
50
        }
51
    }
52
53
    private function getUserJWT($id, $login): array
54
    {
55
        require PROJECT_ROOT_PATH . '/../includes/config/tp.config.php';
56
        $headers = array('alg'=>'HS256','typ'=>'JWT');
57
		$payload = array('username'=>$login, 'id'=>$id, 'exp'=>(time() + $SETTINGS['api_token_duration']));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $SETTINGS seems to be never defined.
Loading history...
58
59
        include_once PROJECT_ROOT_PATH . '/inc/jwt_utils.php';
60
		return array('token' => generate_jwt($headers, $payload));
61
    }
62
}