Passed
Push — master ( 1dc943...5f0a93 )
by Arthur
08:24 queued 35s
created

Auth0Service::getTestUserToken()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2.0438

Importance

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