Completed
Push — 2.0 ( 369485...d81882 )
by Nicolas
15:25
created

TokenCan::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
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\Contracts\Authentication;
8
use Modules\User\Entities\UserInterface;
9
use Modules\User\Repositories\UserTokenRepository;
10
11
class TokenCan
12
{
13
    /**
14
     * @var UserTokenRepository
15
     */
16
    private $userToken;
17
    /**
18
     * @var Authentication
19
     */
20
    private $auth;
21
22
    public function __construct(UserTokenRepository $userToken, Authentication $auth)
23
    {
24
        $this->userToken = $userToken;
25
        $this->auth = $auth;
26
    }
27
28
    /**
29
     * @param Request $request
30
     * @param \Closure $next
31
     * @param string $permission
32
     * @return Response
33
     */
34
    public function handle(Request $request, \Closure $next, $permission)
35
    {
36
        if ($request->header('Authorization') === null) {
37
            return new Response('Forbidden', Response::HTTP_FORBIDDEN);
38
        }
39
40
        $user = $this->getUserFromToken($request->header('Authorization'));
0 ignored issues
show
Bug introduced by
It seems like $request->header('Authorization') targeting Illuminate\Http\Request::header() can also be of type array; however, Modules\User\Http\Middle...Can::getUserFromToken() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
41
42
        if ($user->hasAccess($permission) === false) {
43
            return response('Unauthorized.', Response::HTTP_UNAUTHORIZED);
44
        }
45
46
        return $next($request);
47
    }
48
49
    /**
50
     * @param string $token
51
     * @return UserInterface
52
     */
53
    private function getUserFromToken($token)
54
    {
55
        $token = $this->userToken->findByAttributes(['access_token' => $this->parseToken($token)]);
56
57
        return $token->user;
58
    }
59
60
    /**
61
     * @param string $token
62
     * @return string
63
     */
64
    private function parseToken($token)
65
    {
66
        return str_replace('Bearer ', '', $token);
67
    }
68
}
69