Test Failed
Pull Request — master (#3)
by Chauncey
01:59
created

AbstractAuthToken::getUserIdFromToken()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 37
rs 8.3946
c 0
b 0
f 0
cc 7
nc 6
nop 2
1
<?php
2
3
namespace Charcoal\User;
4
5
use DateTime;
6
use DateTimeInterface;
7
use InvalidArgumentException;
8
9
// From 'charcoal-core'
10
use Charcoal\Model\AbstractModel;
11
12
// From 'charcoal-object'
13
use Charcoal\Object\TimestampableInterface;
14
use Charcoal\Object\TimestampableTrait;
15
16
// From 'charcoal-user'
17
use Charcoal\User\AuthTokenMetadata;
18
19
/**
20
 * Base Authorization Token
21
 */
22
abstract class AbstractAuthToken extends AbstractModel implements
23
    AuthTokenInterface,
24
    TimestampableInterface
25
{
26
    use TimestampableTrait;
27
28
    /**
29
     * The token key.
30
     *
31
     * @var string
32
     */
33
    private $ident;
34
35
    /**
36
     * The token value.
37
     *
38
     * @var string
39
     */
40
    private $token;
41
42
    /**
43
     * The related user ID.
44
     *
45
     * @var string
46
     */
47
    private $userId;
48
49
    /**
50
     * The token's expiration date.
51
     *
52
     * @var DateTimeInterface|null
53
     */
54
    private $expiry;
55
56
    /**
57
     * @return string
58
     */
59
    public function key()
60
    {
61
        return 'ident';
62
    }
63
64
    /**
65
     * @param  string $ident The token ident.
66
     * @return self
67
     */
68
    public function setIdent($ident)
69
    {
70
        $this->ident = $ident;
71
        return $this;
72
    }
73
74
    /**
75
     * @return string
76
     */
77
    public function getIdent()
78
    {
79
        return $this->ident;
80
    }
81
82
    /**
83
     * @param  string $token The token.
84
     * @return self
85
     */
86
    public function setToken($token)
87
    {
88
        $this->token = $token;
89
        return $this;
90
    }
91
92
    /**
93
     * @return string
94
     */
95
    public function getToken()
96
    {
97
        return $this->token;
98
    }
99
100
    /**
101
     * @param  string $id The user ID.
102
     * @throws InvalidArgumentException If the user ID is not a string.
103
     * @return self
104
     */
105
    public function setUserId($id)
106
    {
107
        if (!is_string($id)) {
108
            throw new InvalidArgumentException(
109
                'Set User ID: identifier must be a string'
110
            );
111
        }
112
113
        $this->userId = $id;
114
        return $this;
115
    }
116
117
    /**
118
     * @return string
119
     */
120
    public function getUserId()
121
    {
122
        return $this->userId;
123
    }
124
125
    /**
126
     * @param  DateTimeInterface|string|null $expiry The date/time at object's creation.
127
     * @throws InvalidArgumentException If the date/time is invalid.
128
     * @return self
129
     */
130 View Code Duplication
    public function setExpiry($expiry)
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...
131
    {
132
        if ($expiry === null) {
133
            $this->expiry = null;
134
            return $this;
135
        }
136
137
        if (is_string($expiry)) {
138
            $expiry = new DateTime($expiry);
139
        }
140
141
        if (!($expiry instanceof DateTimeInterface)) {
142
            throw new InvalidArgumentException(
143
                'Invalid "Expiry" value. Must be a date/time string or a DateTime object.'
144
            );
145
        }
146
147
        $this->expiry = $expiry;
148
        return $this;
149
    }
150
151
    /**
152
     * @return DateTimeInterface|null
153
     */
154
    public function getExpiry()
155
    {
156
        return $this->expiry;
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->expiry; of type DateTimeInterface|null adds the type DateTimeInterface to the return on line 156 which is incompatible with the return type declared by the interface Charcoal\User\AuthTokenInterface::getExpiry of type Charcoal\User\DateTimeInterface|null.
Loading history...
157
    }
158
159
    /**
160
     * Generate auth token data for the given user ID.
161
     *
162
     * Note: the `random_bytes()` function is new to PHP-7. Available in PHP 5 with `compat-random`.
163
     *
164
     * @param  string $userId The user ID to generate the auth token from.
165
     * @return self
166
     */
167
    public function generate($userId)
168
    {
169
        if (!$this->isEnabled()) {
170
            return $this;
171
        }
172
173
        $metadata = $this->metadata();
174
175
        $this['ident']  = bin2hex(random_bytes(16));
176
        $this['token']  = bin2hex(random_bytes(32));
177
        $this['userId'] = $userId;
178
        $this['expiry'] = 'now + '.$metadata['tokenDuration'];
179
180
        return $this;
181
    }
182
183
    /**
184
     * Determine if authentication by token is supported.
185
     *
186
     * @return boolean
187
     */
188
    public function isEnabled()
189
    {
190
        return $this->metadata()['enabled'];
191
    }
192
193
    /**
194
     * Determine if authentication by token should be only over HTTPS.
195
     *
196
     * @return boolean
197
     */
198
    public function isSecure()
199
    {
200
        return $this->metadata()['httpsOnly'];
201
    }
202
203
    /**
204
     * @param  mixed  $ident The auth-token identifier.
205
     * @param  string $token The token to validate against.
206
     * @return mixed The user id. An empty string if no token match.
207
     */
208
    public function getUserIdFromToken($ident, $token)
209
    {
210
        if (!$this->isEnabled()) {
211
            return null;
212
        }
213
214
        if (!$this->source()->tableExists()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Charcoal\Source\SourceInterface as the method tableExists() does only exist in the following implementations of said interface: Charcoal\Source\DatabaseSource.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
215
            return null;
216
        }
217
218
        $this->load($ident);
219
        if (!$this['ident']) {
220
            $this->logger->warning(sprintf(
221
                'Auth token not found: "%s"',
222
                $ident
223
            ));
224
            return null;
225
        }
226
227
        // Expired token
228
        $now = new DateTime('now');
229
        if (!$this['expiry'] || $now > $this['expiry']) {
230
            $this->logger->warning('Expired auth token');
231
            $this->delete();
232
            return null;
233
        }
234
235
        // Validate encrypted token
236
        if (password_verify($token, $this['token']) !== true) {
237
            $this->panic();
238
            $this->delete();
239
            return null;
240
        }
241
242
        // Success!
243
        return $this['userId'];
244
    }
245
246
    /**
247
     * Delete all auth tokens from storage for the current user.
248
     *
249
     * @return void
250
     */
251
    public function deleteUserAuthTokens()
252
    {
253
        $userId = $this['userId'];
254
        if (isset($userId)) {
255
            $sql = sprintf(
256
                'DELETE FROM `%s` WHERE user_id = :userId',
257
                $this->source()->table()
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Charcoal\Source\SourceInterface as the method table() does only exist in the following implementations of said interface: Charcoal\Source\DatabaseSource.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
258
            );
259
            $this->source()->dbQuery($sql, [
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Charcoal\Source\SourceInterface as the method dbQuery() does only exist in the following implementations of said interface: Charcoal\Source\DatabaseSource.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
260
                'userId' => $userId,
261
            ]);
262
        }
263
    }
264
265
    /**
266
     * Something is seriously wrong: a auth ident was in the database but with a tampered token.
267
     *
268
     * @return void
269
     */
270
    protected function panic()
271
    {
272
        $this->logger->error(
273
            'Possible security breach: an authentication token was found in the database but its token does not match.'
274
        );
275
276
        $this->deleteUserAuthTokens();
277
    }
278
279
    /**
280
     * @see \Charcoal\Source\StorableTrait::preSave()
281
     *
282
     * @return boolean
283
     */
284
    protected function preSave()
285
    {
286
        $result = parent::preSave();
287
288
        $this->touchToken();
289
290
        $this['created']      = 'now';
291
        $this['lastModified'] = 'now';
292
293
        return $result;
294
    }
295
296
    /**
297
     * @see \Charcoal\Source\StorableTrait::preUpdate()
298
     *
299
     * @param  array $properties The properties (ident) set for update.
300
     * @return boolean
301
     */
302
    protected function preUpdate(array $properties = null)
303
    {
304
        $result = parent::preUpdate($properties);
305
306
        $this['lastModified'] = 'now';
307
308
        return $result;
309
    }
310
311
    /**
312
     * @return void
313
     */
314
    protected function touchToken()
315
    {
316
        $token = $this['token'];
317
        if (password_needs_rehash($token, PASSWORD_DEFAULT)) {
318
            $this['token'] = password_hash($token, PASSWORD_DEFAULT);
319
        }
320
    }
321
322
    /**
323
     * Create a new metadata object.
324
     *
325
     * @param  array $data Optional metadata to merge on the object.
326
     * @return AuthTokenMetadata
327
     */
328
    protected function createMetadata(array $data = null)
329
    {
330
        $class = $this->metadataClass();
331
        return new $class($data);
332
    }
333
334
    /**
335
     * Retrieve the class name of the metadata object.
336
     *
337
     * @return string
338
     */
339
    protected function metadataClass()
340
    {
341
        return AuthTokenMetadata::class;
342
    }
343
}
344