Completed
Push — develop ( ab26e2...62e4bb )
by Abdelrahman
06:01
created

SocialAuthenticationController::createLocalUser()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 14
nc 2
nop 2
dl 0
loc 23
rs 9.0856
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cortex\Fort\Http\Controllers\Tenantarea;
6
7
use Laravel\Socialite\Facades\Socialite;
8
use Illuminate\Database\Eloquent\Builder;
9
10
class SocialAuthenticationController extends AuthenticationController
11
{
12
    /**
13
     * Redirect the user to the provider authentication page.
14
     *
15
     * @param string $provider
16
     *
17
     * @return \Illuminate\Http\Response
18
     */
19
    public function redirectToProvider(string $provider)
20
    {
21
        return Socialite::driver($provider)->redirect();
22
    }
23
24
    /**
25
     * Obtain the user information from Provider.
26
     *
27
     * @param string $provider
28
     *
29
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
30
     */
31
    public function handleProviderCallback(string $provider)
32
    {
33
        $providerUser = Socialite::driver($provider)->user();
34
35
        $attributes = [
36
            'id' => $providerUser->id,
37
            'email' => $providerUser->email,
38
            'username' => $providerUser->nickname ?? trim(mb_strstr($providerUser->email, '@', true)),
39
            'first_name' => str_before($providerUser->name, ' '),
40
            'last_name' => str_after($providerUser->name, ' '),
41
        ];
42
43
        switch ($provider) {
44
            case 'twitter':
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
45
                $attributes['bio'] = $providerUser->user['description'];
46
                $attributes['profile_picture'] = $providerUser->avatar_original;
47
                break;
48
            case 'github':
0 ignored issues
show
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
49
                $attributes['bio'] = $providerUser->user['bio'];
50
                $attributes['profile_picture'] = $providerUser->avatar;
51
                break;
52
            case 'facebook':
53
                $attributes['profile_picture'] = $providerUser->avatar_original;
54
                break;
55
            case 'linkedin':
56
                $attributes['bio'] = $providerUser->headline;
57
                $attributes['profile_picture'] = $providerUser->avatar_original;
58
                break;
59
            case 'google':
60
                $attributes['bio'] = $providerUser->tagline;
61
                $attributes['profile_picture'] = $providerUser->avatar_original;
62
                break;
63
        }
64
65
        if (! ($localUser = $this->getLocalUser($provider, $providerUser->id))) {
66
            $localUser = $this->createLocalUser($provider, $attributes);
67
        }
68
69
        $loginResult = auth()->guard($this->getGuard())->attempt([
0 ignored issues
show
Bug introduced by
The method guard does only exist in Illuminate\Contracts\Auth\Factory, but not in Illuminate\Contracts\Auth\Guard.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
70
            'is_active' => $localUser->is_active,
71
            'email' => $localUser->email,
72
            'social' => true,
73
        ], true);
74
75
        return $this->getLoginResponse(request(), $loginResult);
76
    }
77
78
    /**
79
     * Get local user for the given provider.
80
     *
81
     * @param string $provider
82
     * @param string $providerUserId
83
     *
84
     * @return \Illuminate\Database\Eloquent\Model|null
85
     */
86
    protected function getLocalUser(string $provider, string $providerUserId)
87
    {
88
        return app('rinvex.fort.user')->whereHas('socialites', function (Builder $builder) use ($provider, $providerUserId) {
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 125 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
89
            $builder->where('provider', $provider)->where('provider_uid', $providerUserId);
90
        })->first();
91
    }
92
93
    /**
94
     * Create local user for the given provider.
95
     *
96
     * @param string $provider
97
     * @param array  $attributes
98
     *
99
     * @return \Illuminate\Database\Eloquent\Model|null
100
     */
101
    protected function createLocalUser(string $provider, array $attributes)
102
    {
103
        $localUser = app('rinvex.fort.user');
104
        $defaultRole = app('rinvex.fort.role')->where('slug', config('rinvex.fort.registration.default_role'))->first();
105
106
        $attributes['password'] = str_random();
107
        $attributes['email_verified'] = true;
108
        $attributes['email_verified_at'] = now();
109
        $attributes['is_active'] = ! config('rinvex.fort.registration.moderated');
110
        $attributes['roles'] = $defaultRole ? [$defaultRole->id] : null;
111
112
        $localUser->fill($attributes)->save();
113
114
        // Fire the register success event
115
        event('rinvex.fort.register.success', [$localUser]);
116
117
        $localUser->socialites()->create([
118
            'provider' => $provider,
119
            'provider_uid' => $attributes['id'],
120
        ]);
121
122
        return $localUser;
123
    }
124
}
125