Auth0Service::getUserByDecodedJWT()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 9
ccs 0
cts 3
cp 0
crap 2
rs 10
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 Modules\Auth0\Contracts\Auth0ServiceContract;
13
use Modules\Auth0\Drivers\Auth0UserProfileStorageDriver;
14
use Modules\User\Contracts\UserServiceContract;
15
use Modules\User\Entities\User;
16
use Modules\User\Events\UserRegisteredEvent;
17
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
18
19
class Auth0Service extends Auth0UserRepository implements Auth0ServiceContract
20
{
21
    protected $service;
22
23
    /**
24
     * Auth0UserRepository constructor.
25
     *
26
     * @param $service
27
     */
28 43
    public function __construct(UserServiceContract $service)
29
    {
30 43
        $this->service = $service;
31 43
    }
32
33
    /* This class is used on api authN to fetch the user based on the jwt.*/
34
    public function getUserByDecodedJWT($jwt)
35
    {
36
        /*
37
         * The `sub` claim in the token represents the subject of the token
38
         * and it is always the `user_id`
39
         */
40
        $jwt->user_id = $jwt->sub;
41
42
        return $this->upsertUser($jwt);
43
    }
44
45
    public function getUserByUserInfo($userInfo)
46
    {
47
        return $this->upsertUser($userInfo['profile']);
48
    }
49
50
    protected function upsertUser($profile)
51
    {
52
        if (! isset($profile->user_id)) {
53
            throw new BadRequestHttpException('Missing token information: Auth0 user id is not set');
54
        }
55
        $identifier = explode('|', $profile->user_id);
56
        $identityProvider = $identifier[0];
57
        $id = $identifier[1];
58
59
        $user = $this->service->findByIdentityId($id);
60
        if ($user === null) {
61
            $user = $this->service->newUser([
62
                'identity_id' => $id,
63
            ]);
64
        }
65
        $driver = new Auth0UserProfileStorageDriver($user, $profile, $identityProvider);
66
        $user = $driver->run();
67
68
        if ($user->wasRecentlyCreated) {
69
            event(new UserRegisteredEvent($user));
70
        }
71
72
        return $user;
73
    }
74
}
75