Completed
Push — master ( f7411e...e3f775 )
by Patrick
04:11
created

LDAPUser::setCachedOnlyProp()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 2
b 0
f 0
nc 3
nop 2
dl 0
loc 13
rs 9.4285
1
<?php
2
namespace Auth;
3
4
class LDAPUser extends User
5
{
6
    use LDAPCachableObject;
7
8
    private $ldapObj;
9
    private $server;
10
11
    public function __construct($data = false)
12
    {
13
        $this->server = \LDAP\LDAPServer::getInstance();
14
        $this->initialize($data);
15
    }
16
17
    private function check_child_group($array)
18
    {
19
        $res = false;
20
        for($i = 0; $i < $array['count']; $i++)
21
        {
22
            if(strpos($array[$i], $this->server->group_base) !== false)
23
            {
24
                $dn = explode(',', $array[$i]);
25
                $res = $this->isInGroupNamed(substr($dn[0], 3));
26
                if($res)
27
                {
28
                    return $res;
29
                }
30
            }
31
        }
32
        return $res;
33
    }
34
35
    /**
36
     * @param string $listName The name of the list to search
37
     * @param Group $group The group to search inside
38
     * @param string $dn The distringuished name to search for
39
     */
40
    private function isInListOrChild($listName, $group, $dn)
41
    {
42
        if(!isset($group[$listName]))
43
        {
44
            return false;
45
        }
46
        if(in_array($dn, $group[$listName]))
47
        {
48
            return true;
49
        }
50
        return $this->check_child_group($group[$listName]);
51
    }
52
53
    public function isInGroupNamed($name)
54
    {
55
        $filter = new \Data\Filter('cn eq '.$name);
56
        $group = $this->server->read($this->server->group_base, $filter);
57
        if(!empty($group))
58
        {
59
            $group = $group[0];
60
            $dn  = $this->ldapObj->dn;
61
            $uid = $this->ldapObj->uid[0];
62
            $ret = $this->isInListOrChild('member', $group, $dn);
63
            if($ret === false)
64
            {
65
                $ret = $this->isInListOrChild('uniquemember', $group, $dn);
66
            }
67
            if($ret === false && isset($group['memberUid']) && in_array($uid, $group['memberUid']))
68
            {
69
                return true;
70
            }
71
            return $ret;
72
        }
73
        return false;
74
    }
75
76
    protected $valueDefaults = array(
77
        'o' => 'Volunteer'
78
    );
79
80
    protected $multiValueProps = array(
81
        'title',
82
        'ou',
83
        'host'
84
    );
85
86
    protected $cachedOnlyProps = array(
87
        'uid'
88
    );
89
90
    protected function getValueWithDefault($propName)
91
    {
92
        if(isset($this->valueDefaults[$propName]))
93
        {
94
            $tmp = $this->getFieldSingleValue($propName);
95
            if($tmp === false)
96
            {
97
                return $this->valueDefaults[$propName];
98
            }
99
            return $tmp;
100
        }
101
        return false;
102
    }
103
104
    protected function getMultiValueProp($propName)
105
    {
106
        if(in_array($propName, $this->multiValueProps))
107
        {
108
            $tmp = $this->getField($propName);
109
            if(isset($tmp['count']))
110
            {
111
                unset($tmp['count']);
112
            }
113
            return $tmp;
114
        }
115
        return false;
116
    }
117
118
    public function __get($propName)
119
    {
120
        $tmp = $this->getValueWithDefault($propName);
121
        if($tmp !== false)
122
        {
123
            return $tmp;
124
        }
125
        $tmp = $this->getMultiValueProp($propName);
126
        if($tmp !== false)
127
        {
128
            return $tmp;
129
        }
130
        return $this->getFieldSingleValue($propName);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->getFieldSingleValue($propName); (string) is incompatible with the return type of the parent method Auth\User::__get of type boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
131
    }
132
133
    protected function setCachedOnlyProp($propName, $value)
134
    {
135
        if(in_array($propName, $this->cachedOnlyProps))
136
        {
137
            if(!is_object($this->ldapObj))
138
            {
139
                $this->setFieldLocal($propName, $value);
140
                return true;
141
            }
142
            throw new \Exception('Unsupported!');
143
        }
144
        return false;
145
    }
146
147
    protected function setMultiValueProp($propName, $value)
148
    {
149
        if(in_array($propName, $this->multiValueProps) && !is_array($value))
150
        {
151
             $this->setField($propName, array($value));
152
             return true;
153
        }
154
        return false;
155
    }
156
157
    public function __set($propName, $value)
158
    {
159
        if($this->setCachedOnlyProp($propName, $value) === true)
160
        {
161
            return;
162
        }
163
        if($this->setMultiValueProp($propName, $value) === true)
164
        {
165
            return;
166
        }
167
        $this->setField($propName, $value);
168
    }
169
170
    /**
171
     * Allow write for the user
172
     *
173
     * @SuppressWarnings("StaticAccess")
174
     */
175
    protected function enableReadWrite()
176
    {
177
        //Make sure we are bound in write mode
178
        $auth = \AuthProvider::getInstance();
179
        $ldap = $auth->getMethodByName('Auth\LDAPAuthenticator');
180
        if($ldap !== false)
181
        {
182
            $ldap->get_and_bind_server(true);
183
        }
184
    }
185
186
    public function getGroups()
187
    {
188
        $res = array();
189
        $groups = $this->server->read($this->server->group_base);
190
        if(!empty($groups))
191
        {
192
            $count = count($groups);
193
            for($i = 0; $i < $count; $i++)
194
            {
195
                if($this->isInGroupNamed($groups[$i]['cn'][0]))
196
                {
197
                    array_push($res, new LDAPGroup($groups[$i]));
198
                }
199
            }
200
            return $res;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $res; (array) is incompatible with the return type of the parent method Auth\User::getGroups of type boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
201
        }
202
        else
203
        {
204
            return false;
205
        }
206
    }
207
208
    public function addLoginProvider($provider)
209
    {
210
        return $this->appendField('host', $provider);
211
    }
212
213
    private function generateLDAPPass($pass)
214
    {
215
        mt_srand((double)microtime() * 1000000);
216
        $salt = pack("CCCC", mt_rand(), mt_rand(), mt_rand(), mt_rand());
217
        $hash = base64_encode(pack('H*', sha1($pass.$salt)).$salt);
218
        return '{SSHA}'.$hash;
219
    }
220
221
    public function setPass($password)
222
    {
223
        if(!is_object($this->ldapObj))
224
        {
225
            return $this->setFieldLocal('userPassword', $this->generateLDAPPass($password));
226
        }
227
        $obj = array('dn'=>$this->ldapObj->dn);
228
        $obj['userPassword'] = $this->generateLDAPPass($password);
229
        if(isset($this->ldapObj->uniqueidentifier))
230
        {
231
            $obj['uniqueIdentifier'] = null;
232
        }
233
        //Make sure we are bound in write mode
234
        $auth = \AuthProvider::getInstance();
235
        $ldap = $auth->getMethodByName('Auth\LDAPAuthenticator');
236
        $ldap->get_and_bind_server(true);
237
        return $this->update($obj);
238
    }
239
240
    public function validate_password($password)
241
    {
242
        return $this->server->bind($this->ldapObj->dn, $password) !== false;
243
    }
244
245
    public function validate_reset_hash($hash)
246
    {
247
        if(isset($this->ldapObj->uniqueidentifier) && strcmp($this->ldapObj->uniqueidentifier[0], $hash) === 0)
248
        {
249
            return true;
250
        }
251
        return false;
252
    }
253
254 View Code Duplication
    public static function from_name($name, $data = false)
0 ignored issues
show
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...
255
    {
256
        if($data === false)
257
        {
258
            throw new \Exception('data must be set for LDAPUser');
259
        }
260
        $filter = new \Data\Filter("uid eq $name");
261
        $user = $data->read($data->user_base, $filter);
0 ignored issues
show
Bug introduced by
The method read cannot be called on $data (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
262
        if($user === false || !isset($user[0]))
263
        {
264
            return false;
265
        }
266
        return new static($user[0]);
267
    }
268
269
    public function flushUser()
270
    {
271
        if(is_object($this->ldapObj))
272
        {
273
            //In this mode we are always up to date
274
            return true;
275
        }
276
        $obj = $this->ldapObj;
277
        $obj['objectClass'] = array('top', 'inetOrgPerson', 'extensibleObject');
278
        $obj['dn'] = 'uid='.$this->ldapObj['uid'].','.$this->server->user_base;
279
        if(!isset($obj['sn']))
280
        {
281
            $obj['sn'] = $obj['uid'];
282
        }
283
        if(!isset($obj['cn']))
284
        {
285
            $obj['cn'] = $obj['uid'];
286
        }
287
        $ret = $this->server->create($obj);
288
        return $ret;
289
    }
290
291
    public function getPasswordResetHash()
292
    {
293
        //Make sure we are bound in write mode
294
        $this->enableReadWrite();
295
        $ldapObj = $this->server->read($ldap->user_base, new \Data\Filter('uid eq '.$this->uid));
0 ignored issues
show
Bug introduced by
The variable $ldap does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
296
        $ldapObj = $ldapObj[0];
297
        $hash = false;
0 ignored issues
show
Unused Code introduced by
$hash 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...
298
        if(isset($ldapObj->userpassword))
299
        {
300
            $hash = hash('sha512', $ldapObj->dn.';'.$ldapObj->userpassword[0].';'.$ldapObj->mail[0]);
301
        }
302
        else
303
        {
304
            $hash = hash('sha512', $ldapObj->dn.';'.openssl_random_pseudo_bytes(10).';'.$ldapObj->mail[0]);
305
        }
306
        $obj = array('dn'=>$this->ldapObj->dn);
307
        $obj['uniqueIdentifier'] = $hash;
308
        if($this->server->update($obj) === false)
309
        {
310
            throw new \Exception('Unable to create hash in LDAP object!');
311
        }
312
        return $hash;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $hash; (string) is incompatible with the return type of the parent method Auth\User::getPasswordResetHash of type boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
313
    }
314
315
    public function delete()
316
    {
317
        //Make sure we are bound in write mode
318
        $this->enableReadWrite();
319
        return $this->server->delete($this->ldapObj->dn);
320
    }
321
}
322
/* vim: set tabstop=4 shiftwidth=4 expandtab: */
323