Completed
Push — master ( 0f5e6b...d874fd )
by Conrad
01:54
created

src/Middleware/AuthenticationMiddleware.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
use SilverStripe\ORM\Connect\DatabaseException;
13
use SilverStripe\ORM\DB;
14
use SilverStripe\Security\Member;
15
use SilverStripe\Security\Security;
16
17
/**
18
 * Class ResourceServerMiddleware.
19
 *
20
 * Replacement for @see \League\OAuth2\Server\Middleware\ResourceServerMiddleware
21
 * to make it compatible with SilverStripe.
22
 *
23
 * @package AdvancedLearning\Oauth2Server\Middleware
24
 */
25
class AuthenticationMiddleware implements HTTPMiddleware
26
{
27
    /**
28
     * @var Application
29
     */
30
    protected $application = null;
31
32
    /**
33
     * @var Authenticator
34
     */
35
    protected $authenticator;
36
37
    /**
38
     * Build error control chain for an application
39
     *
40
     * @param Application    $application The SilverStripe Application.
41
     */
42
    public function __construct()
43
    {
44
        $this->authenticator = Injector::inst()->get(Authenticator::class);
45
    }
46
47
    /**
48
     * Process the middleware.
49
     *
50
     * @param HTTPRequest $request The incoming request.
51
     * @param callable    $next    The next middleware.
52
     *
53
     * @return HTTPResponse
54
     */
55
    public function process(HTTPRequest $request, callable $next)
56
    {
57
        try {
58
            $request = $this->authenticator->authenticate($request);
59
60
            // set the current user
61
            if ($userID = $request->getHeader('oauth_user_id')) {
62
                echo 'here';
63
                Security::setCurrentUser(Member::get()->byID($userID));
64
                echo 'wtf';exit;
0 ignored issues
show
It is generally recommended to place each PHP statement on a line by itself.

Let’s take a look at an example:

// Bad
$a = 5; $b = 6; $c = 7;

// Good
$a = 5;
$b = 6;
$c = 7;
Loading history...
65
            }
66
        } catch (AuthenticationException $exception) {
67
            // for middleware do nothing
68
        } catch (DatabaseException $exception) {
69
            // db not ready, ignore
70
        }
71
72
        // Pass the request on to the next responder in the chain
73
        return $next($request);
74
    }
75
}
76