Completed
Push — master ( 8763c1...14778d )
by Conrad
03:00
created

AuthenticationMiddleware::process()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 11
rs 9.4285
cc 2
eloc 6
nc 2
nop 2
1
<?php
2
3
namespace AdvancedLearning\Oauth2Server\Middleware;
4
5
use AdvancedLearning\Oauth2Server\Exceptions\AuthenticationException;
6
use AdvancedLearning\Oauth2Server\Services\Authenticator;
7
use SilverStripe\Control\HTTPRequest;
8
use SilverStripe\Control\HTTPResponse;
9
use SilverStripe\Control\Middleware\HTTPMiddleware;
10
use SilverStripe\Core\Application;
11
use SilverStripe\Core\Injector\Injector;
12
13
/**
14
 * Class ResourceServerMiddleware.
15
 *
16
 * Replacement for @see \League\OAuth2\Server\Middleware\ResourceServerMiddleware
17
 * to make it compatible with SilverStripe.
18
 *
19
 * @package AdvancedLearning\Oauth2Server\Middleware
20
 */
21
class AuthenticationMiddleware implements HTTPMiddleware
22
{
23
    /**
24
     * @var Application
25
     */
26
    protected $application = null;
27
28
    /**
29
     * @var Authenticator
30
     */
31
    protected $authenticator;
32
33
    /**
34
     * Build error control chain for an application
35
     *
36
     * @param Application    $application The SilverStripe Application.
37
     */
38
    public function __construct(Application $application)
39
    {
40
        $this->application = $application;
41
        $this->authenticator = Injector::inst()->get(Authenticator::class);
42
    }
43
44
    /**
45
     * Process the middleware.
46
     *
47
     * @param HTTPRequest $request The incoming request.
48
     * @param callable    $next    The next middleware.
49
     *
50
     * @return HTTPResponse
51
     */
52
    public function process(HTTPRequest $request, callable $next)
53
    {
54
        try {
55
            $request = $this->authenticator->authenticate($request);
56
        } catch (AuthenticationException $exception) {
57
            return $exception->getResponse();
58
        }
59
60
        // Pass the request on to the next responder in the chain
61
        return $next($request);
62
    }
63
}
64