Passed
Push — master ( 9643a3...07db06 )
by Arthur
67:34 queued 48:37
created

Auth0Service::upsertUser()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

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