Completed
Push — master ( a1f855...f552ba )
by Conrad
09:23
created

Authenticator::oauthAuthenticate()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 31
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 8.439
c 0
b 0
f 0
cc 6
eloc 14
nc 8
nop 2
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: Conrad
5
 * Date: 23/01/2018
6
 * Time: 9:35 AM
7
 */
8
9
namespace AdvancedLearning\Oauth2Server\Utilities;
10
11
12
use function min;
13
use SilverStripe\Control\HTTPRequest;
14
15
trait Authenticator
16
{
17
    /**
18
     * Check request has oauth headers, and optionally check for scopes.
19
     *
20
     * @param HTTPRequest $request
21
     * @param array       $scopes
22
     *
23
     * @return bool
24
     */
25
    public function oauthAuthenticate(HTTPRequest $request, $scopes = [])
26
    {
27
        $headers = $request->getHeaders();
28
29
        // must have a client
30
        if (empty($headers['oauth_client_id'])) {
31
            return false;
32
        }
33
34
        // if scopes passed, check request contains all the scopes
35
        if (!empty($scopes)) {
36
            $matchedScopes = [];
37
38
            $requestScopes = !empty($headers['oauth_scopes']) ?
39
                explode(',', $headers['oauth_scopes']) :
40
                [];
41
42
            // if request has no scopes then authentication failed
43
            if (empty($requestScopes)) {
44
                return false;
45
            }
46
47
            foreach ($scopes as $scope) {
48
                $matchedScopes[] = in_array($scope, $requestScopes);
49
            }
50
51
            return (bool)min($matchedScopes);
52
        }
53
54
        return true;
55
    }
56
}