Passed
Push — master ( 7515f9...ca1078 )
by Nils
04:09
created

checkUser()   C

Complexity

Conditions 17
Paths 25

Size

Total Lines 88
Code Lines 55

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 17
eloc 55
c 2
b 0
f 0
nc 25
nop 4
dl 0
loc 88
rs 5.2166

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * Teampass - a collaborative passwords manager.
7
 * ---
8
 * This library is distributed in the hope that it will be useful,
9
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11
 * ---
12
 * @project   Teampass
13
 * @file      checks.php
14
 * ---
15
 * @author    Nils Laumaillé ([email protected])
16
 * @copyright 2009-2023 Teampass.net
17
 * @license   https://spdx.org/licenses/GPL-3.0-only.html#licenseText GPL-3.0
18
 * ---
19
 * @see       https://www.teampass.net
20
 */
21
22
23
require_once 'SecureHandler.php';
24
25
// Load config
26
if (file_exists('../includes/config/tp.config.php')) {
27
    include_once '../includes/config/tp.config.php';
28
} elseif (file_exists('./includes/config/tp.config.php')) {
29
    include_once './includes/config/tp.config.php';
30
} elseif (file_exists('../../includes/config/tp.config.php')) {
31
    include_once '../../includes/config/tp.config.php';
32
} else {
33
    throw new Exception('Error file "/includes/config/tp.config.php" not exists', 1);
34
}
35
36
require_once $SETTINGS['cpassman_dir'] . '/includes/config/include.php';
37
require_once $SETTINGS['cpassman_dir'] . '/sources/main.functions.php';
38
39
// Prepare sanitization
40
$data = [
41
    'forbidenPfs' => isset($_POST['type']) === true ? $_POST['type'] : '',
42
];
43
$inputData = dataSanitizer(
44
    [
45
        'type' => isset($_POST['type']) === true ? $_POST['type'] : '',
46
    ],
47
    [
48
        'type' => 'trim|escape',
49
    ],
50
    $SETTINGS['cpassman_dir']
51
);
52
53
/*
54
Handle CASES
55
 */
56
switch ($inputData['type']) {
57
    case 'checkSessionExists':
58
        // Case permit to check if SESSION is still valid
59
        session_name('teampass_session');
60
        session_start();
61
62
        if (isset($_SESSION['CPM']) === true) {
63
            echo json_encode([
64
                'status' => true,
65
            ]);
66
        } else {
67
            // In case that no session is available
68
            // Force the page to be reloaded and attach the CSRFP info
69
            // Load CSRFP
70
            $csrfp_array = include '../includes/libraries/csrfp/libs/csrfp.config.php';
71
72
            // Send back CSRFP info
73
            echo $csrfp_array['CSRFP_TOKEN'] . ';' . filter_input(INPUT_POST, $csrfp_array['CSRFP_TOKEN'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
74
        }
75
76
        break;
77
}
78
79
/**
80
 * Returns the page the user is visiting.
81
 *
82
 * @return string The page name
83
 */
84
function curPage($SETTINGS)
85
{
86
    // Load libraries
87
    include_once $SETTINGS['cpassman_dir'] . '/includes/libraries/protect/SuperGlobal/SuperGlobal.php';
88
    $superGlobal = new protect\SuperGlobal\SuperGlobal();
89
90
    // Parse the url
91
    parse_str(
92
        substr(
93
            (string) $superGlobal->get('REQUEST_URI', 'SERVER'),
94
            strpos((string) $superGlobal->get('REQUEST_URI', 'SERVER'), '?') + 1
95
        ),
96
        $result
97
    );
98
99
    return $result['page'];
100
}
101
102
/**
103
 * Checks if user is allowed to open the page.
104
 *
105
 * @param int    $userId      User's ID
106
 * @param int    $userKey     User's temporary key
107
 * @param string $pageVisited Page visited
108
 * @param array  $SETTINGS    Settings
109
 *
110
 * @return bool
111
 */
112
function checkUser($userId, $userKey, $pageVisited, $SETTINGS)
113
{
114
    // Should we start?
115
    if (empty($userId) === true || empty($pageVisited) === true || empty($userKey) === true) {
116
        return false;
117
    }
118
119
    // Definition
120
    $pagesRights = array(
121
        'user' => array(
122
            'home', 'items', 'search', 'kb', 'favourites', 'suggestion', 'profile', 'import', 'export', 'folders', 'offline',
123
        ),
124
        'manager' => array(
125
            'home', 'items', 'search', 'kb', 'favourites', 'suggestion', 'folders', 'roles', 'utilities', 'users', 'profile',
126
            'import', 'export', 'offline', 'process',
127
            'utilities.deletion', 'utilities.renewal', 'utilities.database', 'utilities.logs', 'tasks',
128
        ),
129
        'human_resources' => array(
130
            'home', 'items', 'search', 'kb', 'favourites', 'suggestion', 'folders', 'roles', 'utilities', 'users', 'profile',
131
            'import', 'export', 'offline', 'process',
132
            'utilities.deletion', 'utilities.renewal', 'utilities.database', 'utilities.logs', 'tasks',
133
        ),
134
        'admin' => array(
135
            'home', 'items', 'search', 'kb', 'favourites', 'suggestion', 'folders', 'manage_roles', 'manage_folders',
136
            'import', 'export', 'offline', 'process',
137
            'manage_views', 'manage_users', 'manage_settings', 'manage_main',
138
            'admin', '2fa', 'profile', '2fa', 'api', 'backups', 'emails', 'ldap', 'special',
139
            'statistics', 'fields', 'options', 'views', 'roles', 'folders', 'users', 'utilities',
140
            'utilities.deletion', 'utilities.renewal', 'utilities.database', 'utilities.logs', 'tasks',
141
        ),
142
    );
143
    // Convert to array
144
    $pageVisited = (is_array(json_decode($pageVisited, true)) === true) ? json_decode($pageVisited, true) : [$pageVisited];
145
146
    // Load
147
    include_once $SETTINGS['cpassman_dir'] . '/includes/config/include.php';
148
    include_once $SETTINGS['cpassman_dir'] . '/includes/config/settings.php';
149
150
    // Load libraries
151
    include_once $SETTINGS['cpassman_dir'] . '/includes/libraries/protect/SuperGlobal/SuperGlobal.php';
152
    $superGlobal = new protect\SuperGlobal\SuperGlobal();
153
154
    // Securize language
155
    if (
156
        is_null($superGlobal->get('user_language', 'SESSION', 'user')) === true
157
        || empty($superGlobal->get('user_language', 'SESSION', 'user')) === true
158
    ) {
159
        $superGlobal->put('user_language', 'english', 'SESSION', 'user');
160
    }
161
162
    include_once $SETTINGS['cpassman_dir'] . '/includes/language/' . $superGlobal->get('user_language', 'SESSION', 'user') . '.php';
163
    include_once 'SplClassLoader.php';
164
    include_once 'main.functions.php';
165
166
    // Connect to mysql server
167
    include_once $SETTINGS['cpassman_dir'] . '/includes/libraries/Database/Meekrodb/db.class.php';
168
    DB::$host = DB_HOST;
169
    DB::$user = DB_USER;
170
    DB::$password = defined('DB_PASSWD_CLEAR') === false ? defuseReturnDecrypted(DB_PASSWD, $SETTINGS) : DB_PASSWD_CLEAR;
171
    DB::$dbName = DB_NAME;
172
    DB::$port = DB_PORT;
173
    DB::$encoding = DB_ENCODING;
174
    DB::$ssl = DB_SSL;
175
    DB::$connect_options = DB_CONNECT_OPTIONS;
176
177
    // load user's data
178
    $data = DB::queryfirstrow(
179
        'SELECT login, key_tempo, admin, gestionnaire, can_manage_all_users FROM ' . prefixTable('users') . ' WHERE id = %i',
180
        $userId
181
    );
182
183
    // check if user exists and tempo key is coherant
184
    if (empty($data['login']) === true || empty($data['key_tempo']) === true || $data['key_tempo'] !== $userKey) {
185
        return false;
186
    }
187
    
188
    if (
189
        ((int) $data['admin'] === 1 && isInArray($pageVisited, $pagesRights['admin']) === true)
190
        ||
191
        (((int) $data['gestionnaire'] === 1 || (int) $data['can_manage_all_users'] === 1)
192
        && (isInArray($pageVisited, array_merge($pagesRights['manager'], $pagesRights['human_resources'])) === true))
193
        ||
194
        (isInArray($pageVisited, $pagesRights['user']) === true)
195
    ) {
196
        return true;
197
    }
198
199
    return false;
200
}
201
202
/**
203
 * Permits to check if at least one input is in array.
204
 *
205
 * @param array $pages Input
206
 * @param array $table Checked against this array
207
 *
208
 * @return bool
209
 */
210
function isInArray($pages, $table)
211
{
212
    foreach ($pages as $page) {
213
        if (in_array($page, $table) === true) {
214
            return true;
215
        }
216
    }
217
218
    return false;
219
}
220