Completed
Pull Request — master (#47)
by
unknown
11:14
created

AuthorisedApiToken::handle()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
rs 9.4285
cc 3
eloc 6
nc 3
nop 2
1
<?php
2
3
namespace Modules\User\Http\Middleware;
4
5
use Illuminate\Http\Request;
6
use Illuminate\Http\Response;
7
use Modules\User\Repositories\UserTokenRepository;
8
9
class AuthorisedApiToken
10
{
11
    /**
12
     * @var UserTokenRepository
13
     */
14
    private $userToken;
15
16
    public function __construct(UserTokenRepository $userToken)
17
    {
18
        $this->userToken = $userToken;
19
    }
20
21
    public function handle(Request $request, \Closure $next)
22
    {
23
        if ($request->header('Authorization') === null) {
24
            return new Response('Forbidden', 403);
25
        }
26
27
        if ($this->isValidToken($request->header('Authorization')) === false) {
28
            return new Response('Forbidden', 403);
29
        }
30
31
        return $next($request);
32
    }
33
34
    private function isValidToken($token)
35
    {
36
        $found = $this->userToken->findByAttributes(['access_token' => $this->parseToken($token)]);
37
38
        if ($found === null) {
39
            return false;
40
        }
41
42
        return true;
43
    }
44
45
    private function parseToken($token)
46
    {
47
        return str_replace('Bearer ', '', $token);
48
    }
49
}
50