Passed
Push — master ( 139939...b4b8e8 )
by Arthur
21:54 queued 17s
created

Auth0Service::getTestUserToken()   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
eloc 13
dl 0
loc 18
ccs 9
cts 11
cp 0.8182
rs 9.8333
c 0
b 0
f 0
cc 2
nc 1
nop 0
crap 2.024
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 62
    public function __construct(UserServiceContract $service)
34
    {
35 62
        $this->service = $service;
36 62
    }
37
38
    /* This class is used on api authN to fetch the user based on the jwt.*/
39 33
    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 33
        $jwt->user_id = $jwt->sub;
46
47 33
        return $this->upsertUser($jwt);
48
    }
49
50
    public function getUserByUserInfo($userInfo)
51
    {
52
        return $this->upsertUser($userInfo['profile']);
53
    }
54
55 33
    protected function upsertUser($profile)
56
    {
57 33
        if (! isset($profile->user_id)) {
58
            throw new BadRequestHttpException('Missing token information: Auth0 user id is not set');
59
        }
60 33
        $identifier = explode('|', $profile->user_id);
61 33
        $identityProvider = $identifier[0];
62 33
        $id = $identifier[1];
63
64 33
        $user = $this->service->findByIdentityId($id);
65 33
        if ($user === null) {
66 33
            $user = $this->service->newUser([
67 33
                'identity_id' => $id,
68
            ]);
69
        }
70 33
        $driver = new Auth0UserProfileStorageDriver($user, $profile, $identityProvider);
71 33
        $user = $driver->run();
72
73 33
        if ($user->wasRecentlyCreated) {
74 33
            event(new UserRegisteredEvent($user));
75
        }
76
77 33
        return $user;
78
    }
79
80 33
81
}
82