Completed
Pull Request — master (#746)
by
unknown
62:20
created

OAuthMiddleware   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 5
Bugs 2 Features 2
Metric Value
wmc 6
c 5
b 2
f 2
lcom 1
cbo 2
dl 0
loc 69
ccs 0
cts 17
cp 0
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A handle() 0 15 2
A validateScopes() 0 6 3
1
<?php
2
3
/*
4
 * This file is part of OAuth 2.0 Laravel.
5
 *
6
 * (c) Luca Degasperi <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace LucaDegasperi\OAuth2Server\Middleware;
13
14
use Closure;
15
use League\OAuth2\Server\Exception\InvalidScopeException;
16
use LucaDegasperi\OAuth2Server\Authorizer;
17
18
/**
19
 * This is the oauth middleware class.
20
 *
21
 * @author Luca Degasperi <[email protected]>
22
 */
23
class OAuthMiddleware
24
{
25
    /**
26
     * The Authorizer instance.
27
     *
28
     * @var \LucaDegasperi\OAuth2Server\Authorizer
29
     */
30
    protected $authorizer;
31
32
    /**
33
     * Whether or not to check the http headers only for an access token.
34
     *
35
     * @var bool
36
     */
37
    protected $httpHeadersOnly = false;
38
39
    /**
40
     * Create a new oauth middleware instance.
41
     *
42
     * @param \LucaDegasperi\OAuth2Server\Authorizer $authorizer
43
     * @param bool $httpHeadersOnly
44
     */
45
    public function __construct(Authorizer $authorizer, $httpHeadersOnly = false)
46
    {
47
        $this->authorizer = $authorizer;
48
        $this->httpHeadersOnly = $httpHeadersOnly;
49
    }
50
51
    /**
52
     * Handle an incoming request.
53
     *
54
     * @param \Illuminate\Http\Request $request
55
     * @param \Closure $next
56
     * @param string|null $scopesString
57
     *
58
     * @throws \League\OAuth2\Server\Exception\InvalidScopeException
59
     *
60
     * @return mixed
61
     */
62
    public function handle($request, Closure $next, $scopesString = null)
63
    {
64
        $scopes = [];
65
66
        if (!is_null($scopesString)) {
67
            $scopes = explode('+', $scopesString);
68
        }
69
70
        $this->authorizer->setRequest($request);
71
72
        $this->authorizer->validateAccessToken($this->httpHeadersOnly);
73
        $this->validateScopes($scopes);
74
75
        return $next($request);
76
    }
77
78
    /**
79
     * Validate the scopes.
80
     *
81
     * @param $scopes
82
     *
83
     * @throws \League\OAuth2\Server\Exception\InvalidScopeException
84
     */
85
    public function validateScopes($scopes)
86
    {
87
        if (!empty($scopes) && !$this->authorizer->hasScope($scopes)) {
88
            throw new InvalidScopeException(implode(',', $scopes));
89
        }
90
    }
91
}
92