|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* BEdita, API-first content management framework |
|
4
|
|
|
* Copyright 2018 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
|
|
|
|
|
14
|
|
|
namespace App\Auth; |
|
15
|
|
|
|
|
16
|
|
|
use BEdita\WebTools\ApiClientProvider; |
|
17
|
|
|
use Cake\Auth\BaseAuthenticate; |
|
18
|
|
|
use Cake\Http\Response; |
|
19
|
|
|
use Cake\Http\ServerRequest; |
|
20
|
|
|
use Cake\Utility\Hash; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* An authentication adapter for authenticating using BEdita 4 API /auth endpoint. |
|
24
|
|
|
* |
|
25
|
|
|
* @see https://docs.bedita.net/en/latest/authorization.html#authentication |
|
26
|
|
|
*/ |
|
27
|
|
|
class ApiAuthenticate extends BaseAuthenticate |
|
28
|
|
|
{ |
|
29
|
|
|
/** |
|
30
|
|
|
* Default config for this object. |
|
31
|
|
|
* |
|
32
|
|
|
* - `fields` The fields to use to perform classic authentication. |
|
33
|
|
|
* |
|
34
|
|
|
* @var array |
|
35
|
|
|
*/ |
|
36
|
|
|
protected $_defaultConfig = [ |
|
37
|
|
|
'fields' => [ |
|
38
|
|
|
'username' => 'username', |
|
39
|
|
|
'password' => 'password', |
|
40
|
|
|
], |
|
41
|
|
|
]; |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* {@inheritDoc} |
|
45
|
|
|
* |
|
46
|
|
|
* Perform authentication via /auth |
|
47
|
|
|
*/ |
|
48
|
|
|
public function authenticate(ServerRequest $request, Response $response) |
|
49
|
|
|
{ |
|
50
|
|
|
/** @var \BEdita\SDK\BEditaClient $apiClient */ |
|
51
|
|
|
$apiClient = ApiClientProvider::getApiClient(); |
|
52
|
|
|
|
|
53
|
|
|
$usernameField = (string)$this->getConfig('fields.username', 'username'); |
|
54
|
|
|
$passwordField = (string)$this->getConfig('fields.password', 'password'); |
|
55
|
|
|
|
|
56
|
|
|
$result = $apiClient->authenticate((string)$request->getData($usernameField), (string)$request->getData($passwordField)); |
|
57
|
|
|
if (empty($result['meta'])) { |
|
58
|
|
|
return false; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
$tokens = $result['meta']; |
|
62
|
|
|
$result = $apiClient->get('/auth/user', null, ['Authorization' => sprintf('Bearer %s', $tokens['jwt'])]); |
|
63
|
|
|
$roles = Hash::extract($result, 'included.{n}.attributes.name'); |
|
64
|
|
|
|
|
65
|
|
|
return $result['data'] + compact('tokens') + compact('roles'); |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|