User_model   B
last analyzed

Complexity

Total Complexity 38

Size/Duplication

Total Lines 377
Duplicated Lines 2.39 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
dl 9
loc 377
rs 8.3999
c 0
b 0
f 0
wmc 38
lcom 0
cbo 0

18 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B resolve_user_login() 0 28 4
A user_exist() 0 18 2
C user_ldap() 0 63 8
A get_uid_from_username() 0 10 1
B set_user() 0 89 5
A clean() 0 3 1
A decrypt() 0 11 1
A encrypt() 9 9 1
A ip_is_private() 0 21 2
A external_login_blocked() 0 14 2
A external_login_fail() 0 15 2
A external_login_reset() 0 5 1
A user_log() 0 12 1
A function_log() 0 20 2
A resolve_passkey() 0 12 1
A get_passkey_details() 0 5 1
A log_passkey() 0 17 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
defined('BASEPATH') OR exit('No direct script access allowed');
4
5
class User_model extends CI_Model {
6
7
    public function __construct() {
8
        parent::__construct();
9
        $this->load->library('encrypt');
10
    }
11
12
    function resolve_user_login($username, $password) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
13
14
        $ldap = ldap_connect($this->config->item('ldapserver'));
15
16
        $ldaprdn = $this->config->item('ldapshortdomain') . $username;
17
18
        ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
19
        ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
20
21
        //bind with users creds
22
        $bind = @ldap_bind($ldap, $ldaprdn, $password);
23
24
        if ($bind) {
25
            $filter = "(sAMAccountName=$username)";
26
            $result = ldap_search($ldap, $this->config->item('ldapuserou'), $filter);
27
            ldap_sort($ldap, $result, "sn");
28
            $info = ldap_get_entries($ldap, $result);
29
            for ($i = 0; $i < $info["count"]; $i++) {
0 ignored issues
show
Unused Code introduced by
$i++; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
30
                return TRUE;
31
            }
32
            @ldap_close($ldap);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
33
            if (@ldap_close($ldap) === false) {
34
                echo "Could not close LDAP connection";
35
            }
36
        } else {
37
            return FALSE;
38
        }
39
    }
40
41
    function user_exist($username) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
42
43
        $db_intranet = $this->load->database('intranet', TRUE);
44
45
        $db_intranet->select('uID');
46
        $db_intranet->from('Users');
47
        $db_intranet->where('uName', $username);
48
49
        $query = $db_intranet->get();
50
51
        if ($query->num_rows() > 0) {
52
            return true;
53
        } else {
54
            return false;
55
        }
56
57
        $this->db->close();
0 ignored issues
show
Unused Code introduced by
$this->db->close(); does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
58
    }
59
60
    function user_ldap($username) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
61
62
        $ldap = ldap_connect($this->config->item('ldapserver'));
63
64
        //bind with ldapquery
65
        $ldaprdn = $this->config->item('ldapshortdomain').$this->config->item('ldapbindun');
66
        $ldappass = $this->config->item('ldapbindpass');
67
68
        ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION, 3);
69
        ldap_set_option($ldap, LDAP_OPT_REFERRALS, 0);
70
71
        $bind = @ldap_bind($ldap, $ldaprdn, $ldappass);
72
73
        if ($bind) {
74
            $filter = "(sAMAccountName=$username)";
75
            $result = ldap_search($ldap, $this->config->item('ldapuserou'), $filter);
76
            ldap_sort($ldap, $result, "sn");
77
            $info = ldap_get_entries($ldap, $result);
78
            for ($i = 0; $i < $info["count"]; $i++) {
0 ignored issues
show
Unused Code introduced by
$i++; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
79
                if ($info['count'] > 1)
80
                    break;
81
82
                //clean
83
                $groups = $info[$i]["memberof"];
84
                unset($groups['count']);
85
86
                //only dashboard groups
87
                foreach ($groups as $key => $value) {
88
                    $exp_key = explode(',', $value);
89
                    if ($exp_key[1] == $this->config->item('ldapdashboardgroupsou')) {
90
                        $dashboard_groups = array();
91
                        $dashboard_groups[] = $value;
92
                    }
93
                }
94
95
                // if no dashboard groups
96
                if (isset($dashboard_groups) === FALSE) {
97
                    $dashboard_groups = 0;
98
                }
99
100
                return array(
101
                    'useraccountcontrol' => $info[$i]["useraccountcontrol"][0],
102
                    'full_name' => $info[$i]["displayname"][0],
103
                    'first_name' => $info[$i]["givenname"][0],
104
                    'last_name' => isset($info[$i]["sn"][0]),
105
                    'username' => $username,
106
                    'email' => $info[$i]["mail"][0],
107
                    'phone' => isset($info[$i]["telephonenumber"][0]),
108
                    'position' => isset($info[$i]["title"][0]),
109
                    'department' => isset($info[$i]["department"][0]),
110
                    'ern' => isset($info[$i]["employeeid"][0]),
111
                    'groups' => $groups,
112
                    'dashboard_groups' => $dashboard_groups,
0 ignored issues
show
Bug introduced by
The variable $dashboard_groups does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
113
                );
114
            }
115
            @ldap_close($ldap);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
116
            if (@ldap_close($ldap) === false) {
117
                echo "Could not close LDAP connection";
118
            }
119
        } else {
120
            return FALSE;
121
        }
122
    }
123
124
    public function get_uid_from_username($username) {
125
126
        $db_intranet = $this->load->database('intranet', TRUE);
127
128
        $db_intranet->select('uID');
129
        $db_intranet->from('Users');
130
        $db_intranet->where('uName', $username);
131
132
        return $db_intranet->get()->row('uID');
133
    }
134
135
    public function set_user($uid, $username, $ip) {
136
137
        $this->db->where('uid', $uid);
138
        $query = $this->db->get('users');
139
        $current = $query->result_array();
140
141
        // always available in model
142
        $two_hour_login = strtotime("-2 hours");
143
        $current_timestamp = date("Y-m-d H:i:s", time());
144
        $login_count = 1;
0 ignored issues
show
Unused Code introduced by
$login_count is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
145
        $browser = $this->agent->browser() . ' ' . $this->agent->version();
146
147
        if ($query->num_rows() > 0) {
148
149
            // model overide
150
            $last_timestamp = strtotime($current[0]['last_login']);
151
            $login_count = $current[0]['login_count'] + 1;
152
153
            if ($this->user_model->ip_is_private($ip) === FALSE) {
154
                // add 1 if external ip
155
                $external_login = $current[0]['external_login'] + 1;
156
                $ip_external = $ip;
157
                $ip_internal = $current[0]['ip_internal'];
158
                $last_external = $current_timestamp;
159
            } else {
160
                $external_login = $current[0]['external_login'];
161
                $ip_external = $current[0]['ip_external'];
162
                $ip_internal = $ip;
163
                $last_external = $current[0]['last_external'];
164
            }
165
166
            if ($last_timestamp <= $two_hour_login) {
167
                // update very 2 hours only
168
                $this->db->where('uid', $uid);
169
                return $this->db->update('users', array('last_login' => $current_timestamp,
170
                            'login_count' => $login_count,
171
                            'external_login' => $external_login,
172
                            'ip_last' => $ip,
173
                            'ip_internal' => $ip_internal,
174
                            'ip_external' => $ip_external,
175
                            'external_login' => $external_login,
176
                            'browser' => $browser,
177
                            'os' => $this->agent->platform(),
178
                            'last_external' => $last_external,
179
                ));
180
            } else {
181
                // always up-to-date
182
                $this->db->where('uid', $uid);
183
                return $this->db->update('users', array('ip_last' => $ip,
184
                            'ip_internal' => $ip_internal,
185
                            'ip_external' => $ip_external,
186
                            'external_login' => $external_login,
187
                            'browser' => $browser,
188
                            'os' => $this->agent->platform(),
189
                            'last_active' => $current_timestamp,
190
                            'last_external' => $last_external,
191
                ));
192
            }
193
        } else {
194
195
            if ($this->user_model->ip_is_private($ip) === FALSE) {
196
                // add 1 if external ip
197
                $external_login = 1;
198
                $ip_external = $ip;
199
                $ip_internal = 0;
200
                $last_external = $current_timestamp;
201
            } else {
202
                $external_login = 0;
203
                $ip_external = 0;
204
                $ip_internal = $ip;
205
                $last_external = NULL;
206
            }
207
208
            // first time login
209
            return $this->db->insert('users', array('uid' => $uid,
210
                        'username' => $username,
211
                        'last_login' => $current_timestamp,
212
                        'login_count' => '1',
213
                        'external_login' => $external_login,
214
                        'ip_last' => $ip,
215
                        'ip_internal' => $ip_internal,
216
                        'ip_external' => $ip_external,
217
                        'browser' => $browser,
218
                        'os' => $this->agent->platform(),
219
                        'last_active' => $current_timestamp,
220
                        'last_external' => $last_external,
221
            ));
222
        }
223
    }
224
225
    function clean($string) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
226
        return preg_replace('/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F]/', '', $string);
227
    }
228
229
    function decrypt($key, $cookie) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
230
231
        define('IV_SIZE', mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
232
233
        $combo = base64_decode($cookie);
234
        $iv = substr($combo, 0, IV_SIZE);
235
        $crypt = substr($combo, IV_SIZE, strlen($combo));
236
        $username = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $crypt, MCRYPT_MODE_CBC, $iv);
237
238
        return $this->user_model->clean($username);
239
    }
240
241 View Code Duplication
    function encrypt($key, $encrypt_item) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
242
243
        $iv = mcrypt_create_iv(IV_SIZE, MCRYPT_DEV_URANDOM);
244
        $crypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $encrypt_item, MCRYPT_MODE_CBC, $iv);
245
        $combo = $iv . $crypt;
0 ignored issues
show
Unused Code introduced by
$combo is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
246
        $output = base64_encode($iv . $crypt);
247
248
        return $output;
249
    }
250
251
    function ip_is_private($ip) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
252
       $safe_ip = array(
253
           $this->config->item('safeipone'),
254
           $this->config->item('safeiptwo'),
255
           $this->config->item('safeipthree'),
256
           $this->config->item('safeipfour'),
257
           $this->config->item('safeipfive'),
258
           $this->config->item('safeipsix'),
259
           $this->config->item('safeipseven'),
260
           $this->config->item('safeipeight'),
261
           $this->config->item('safeipnine'),
262
           $this->config->item('safeipten'),
263
       );      
264
      
265
      if (in_array($_SERVER['REMOTE_ADDR'], $safe_ip)) {
266
            return true;
267
        } else {
268
            return false;
269
        }  
270
       
271
    }
272
273
    function external_login_blocked($uid) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
274
275
        $this->db->select('external_login_block');
276
        $this->db->from('users');
277
        $this->db->where('uid', $uid);
278
279
        $query = $this->db->get()->result_array();
280
281
        if ($query[0]['external_login_block'] === '0') {
282
            return true;
283
        } else {
284
            return false;
285
        }
286
    }
287
288
    function external_login_fail($uid) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
289
290
        $this->db->where('uid', $uid);
291
        $query = $this->db->get('users');
292
        $current = $query->result_array();
293
294
        if ($current[0]['external_login_block'] == '0') {
295
            $new = 0;
296
        } else {
297
            $new = $current[0]['external_login_block'] - 1;
298
        }
299
300
        $this->db->where('uid', $uid);
301
        return $this->db->update('users', array('external_login_block' => $new));
302
    }
303
304
    function external_login_reset($uid) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
305
306
        $this->db->where('uid', $uid);
307
        return $this->db->update('users', array('external_login_block' => 5));
308
    }
309
310
    public function user_log() {
311
        
312
        $ip = $_SERVER['REMOTE_ADDR'];
313
        $data = array(
314
            'timestamp' => date("Y-m-d H:i:s", time()),
315
            'ip' => $ip,
316
            'username' => $_SESSION['username'],
317
            'url' => current_url(),
318
        );
319
320
        return $this->db->insert('users_log', $data);
321
    }
322
    
323
    public function function_log($function) {
324
325
        $ip = $_SERVER['REMOTE_ADDR'];
326
        
327
        if (isset($_SESSION['username'])) {
328
            $username = $_SESSION['username'];
329
        } else {
330
            $username = NULL;
331
        }
332
        
333
        $data = array(
334
            'timestamp' => date("Y-m-d H:i:s", time()),
335
            'ip' => $ip,
336
            'username' => $username,
337
            'url' => current_url(),
338
            'function' => $function
339
        );
340
341
        return $this->db->insert('users_log', $data);
342
    }
343
344
    public function resolve_passkey($passid, $passkey) {
345
346
        $this->db->select('passkey');
347
        $this->db->from('passkey');
348
        $this->db->where('passid', $passid);
349
        $decrypt = $this->db->get()->row('passkey');
350
351
        $hash = $this->encrypt->decode($decrypt);
352
353
        return password_verify($passkey, password_hash($hash, PASSWORD_BCRYPT));
354
        ;
355
    }
356
357
    public function get_passkey_details($passid) {
358
359
        $query = $this->db->get_where('passkey', array('passid' => $passid));
360
        return $query->result_array();
361
    }
362
363
    public function log_passkey($ip, $passid) {
364
365
        if (isset($_SESSION['username']) === TRUE) {
366
            $username = $_SESSION['username'];
367
        } else {
368
            $username = NULL;
369
        }
370
371
        $data = array(
372
            'timestamp' => date("Y-m-d H:i:s", time()),
373
            'ip' => $ip,
374
            'passid' => $passid,
375
            'username' => $username,
376
        );
377
378
        return $this->db->insert('passkey_log', $data);
379
    }
380
381
}
382
383
// END model
384