Auth0Service   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Test Coverage

Coverage 13.03%

Importance

Changes 0
Metric Value
eloc 20
dl 0
loc 54
ccs 3
cts 23
cp 0.1303
rs 10
c 0
b 0
f 0
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getUserByUserInfo() 0 3 1
A __construct() 0 3 1
A upsertUser() 0 23 4
A getUserByDecodedJWT() 0 9 1
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