Passed
Pull Request — master (#822)
by Stefano
02:47
created

OAuth2Identifier::identify()   A

Complexity

Conditions 2
Paths 4

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 16
rs 9.9
cc 2
nc 4
nop 1
1
<?php
2
/**
3
 * BEdita, API-first content management framework
4
 * Copyright 2022 ChannelWeb Srl, Chialab Srl
5
 *
6
 * This file is part of BEdita: you can redistribute it and/or modify
7
 * it under the terms of the GNU Lesser General Public License as published
8
 * by the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * See LICENSE.LGPL or <http://gnu.org/licenses/lgpl-3.0.html> for more details.
12
 */
13
namespace App\Identifier;
14
15
use ArrayObject;
16
use Authentication\Identifier\AbstractIdentifier;
17
use BEdita\SDK\BEditaClientException;
18
use BEdita\WebTools\ApiClientProvider;
19
use Cake\Log\LogTrait;
20
use Cake\Utility\Hash;
21
22
/**
23
 * Identifies authentication credentials through an OAuth2 external provider.
24
 */
25
class OAuth2Identifier extends AbstractIdentifier
26
{
27
    use LogTrait;
28
29
    protected $_defaultConfig = [
30
        'fields' => [
31
            'auth_provider' => 'auth_provider',
32
            'provider_username' => 'provider_username',
33
            'access_token' => 'access_token',
34
        ],
35
    ];
36
37
    /**
38
     * @inheritDoc
39
     */
40
    public function identify(array $credentials)
41
    {
42
        $apiClient = ApiClientProvider::getApiClient();
43
        try {
44
            $result = $apiClient->post('/auth', json_encode($credentials), ['Content-Type' => 'application/json']);
45
            $tokens = $result['meta'];
46
            $result = $apiClient->get('/auth/user', null, ['Authorization' => sprintf('Bearer %s', $tokens['jwt'])]);
47
        } catch (BEditaClientException $ex) {
48
            $this->log($ex->getMessage(), 'debug');
49
50
            return null;
51
        }
52
53
        return new ArrayObject($result['data']
54
            + compact('tokens')
55
            + Hash::combine($result, 'included.{n}.attributes.name', 'included.{n}.id', 'included.{n}.type'));
56
    }
57
}
58