Passed
Push — master ( 7bc374...cf39f3 )
by Arthur
05:05
created

Auth0Service::getPredefinedUserTokenData()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2.024

Importance

Changes 0
Metric Value
cc 2
eloc 13
nc 1
nop 0
dl 0
loc 18
ccs 9
cts 11
cp 0.8182
crap 2.024
rs 9.8333
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: arthur
5
 * Date: 13.10.18
6
 * Time: 20:50.
7
 */
8
9
namespace Modules\Auth0\Services;
10
11
use Auth0\Login\Repository\Auth0UserRepository;
0 ignored issues
show
Bug introduced by
The type Auth0\Login\Repository\Auth0UserRepository was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
use Cache;
13
use Foundation\Exceptions\Exception;
14
use GuzzleHttp\Client;
0 ignored issues
show
Bug introduced by
The type GuzzleHttp\Client was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
15
use GuzzleHttp\Exception\ClientException;
0 ignored issues
show
Bug introduced by
The type GuzzleHttp\Exception\ClientException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
16
use Modules\Auth0\Drivers\Auth0UserProfileStorageDriver;
17
use Modules\User\Contracts\UserServiceContract;
18
use Modules\User\Events\UserRegisteredEvent;
19
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
20
21
class Auth0Service extends Auth0UserRepository
22
{
23
    protected $service;
24
25
    /**
26
     * Auth0UserRepository constructor.
27
     *
28
     * @param $service
29
     */
30 30
    public function __construct(UserServiceContract $service)
31
    {
32 30
        $this->service = $service;
33 30
    }
34
35
    /* This class is used on api authN to fetch the user based on the jwt.*/
36 30
    public function getUserByDecodedJWT($jwt)
37
    {
38
        /*
39
         * The `sub` claim in the token represents the subject of the token
40
         * and it is always the `user_id`
41
         */
42 30
        $jwt->user_id = $jwt->sub;
43
44 30
        return $this->upsertUser($jwt);
45
    }
46
47
    public function getUserByUserInfo($userInfo)
48
    {
49
        return $this->upsertUser($userInfo['profile']);
50
    }
51
52 30
    protected function upsertUser($profile)
53
    {
54 30
        if (!isset($profile->user_id)) {
55
            throw new BadRequestHttpException('Missing token information: Auth0 user id is not set');
56
        }
57 30
        $identifier = explode('|', $profile->user_id);
58 30
        $identityProvider = $identifier[0];
59 30
        $id = $identifier[1];
60
61 30
        $user = $this->service->find($id);
62 30
        $newUser = false;
63 30
        if ($user === null) {
64 30
            $user = $this->service->newUser([
65 30
                'identity_id' => $id,
66
            ]);
67 30
            $newUser = true;
68
        }
69 30
        $driver = new Auth0UserProfileStorageDriver($user, $profile, $identityProvider);
70 30
        $user = $driver->run();
71
72 30
        if ($newUser) {
73 30
            event(new UserRegisteredEvent($user));
74
        }
75
76 30
        return $user;
77
    }
78
79 30
    public function getPredefinedUser()
80
    {
81 30
        $auth0 = \App::make('auth0');
82 30
        $tokenInfo = $auth0->decodeJWT($this->getPredefinedUserTokenData()->id_token);
83
84 30
        return $this->getUserByDecodedJWT($tokenInfo);
85
    }
86
87 30
    public function getPredefinedUserTokenData(): \stdClass
88
    {
89
        return Cache::remember('testing:http_access_token', 60, function () {
90
            try {
91 1
                $httpClient = new Client();
92 1
                $response = $httpClient->post(env('AUTH0_DOMAIN').'oauth/token', [
93
                    'form_params' => [
94 1
                        'grant_type' => 'password',
95 1
                        'client_id'  => env('AUTH0_CLIENT_ID'),
96 1
                        'username'   => env('AUTH0_TEST_USER_NAME'),
97 1
                        'password'   => env('AUTH0_TEST_USER_PASS'),
98 1
                        'scope'      => 'openid profile email offline_access',
99
                    ],
100
                ]);
101
102 1
                return json_decode($response->getBody()->getContents());
103
            } catch (ClientException $exception) {
104
                throw new Exception('Could not obtain token from Auth0 at '.env('AUTH0_DOMAIN').' for testing.');
105
            }
106 30
        });
107
    }
108
}
109