Completed
Push — develop ( 5abd4c...dae2aa )
by Abdelrahman
09:07
created

SocialAuthenticationController::createLocalUser()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.3142
c 0
b 0
f 0
cc 1
eloc 12
nc 1
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Cortex\Auth\Http\Controllers\Adminarea;
6
7
use Illuminate\Http\Request;
8
use Illuminate\Auth\Events\Registered;
9
use Laravel\Socialite\Facades\Socialite;
10
use Illuminate\Database\Eloquent\Builder;
11
use Cortex\Foundation\Http\Controllers\AbstractController;
12
13
class SocialAuthenticationController extends AbstractController
14
{
15
    /**
16
     * Redirect the user to the provider authentication page.
17
     *
18
     * @param string $provider
19
     *
20
     * @return \Illuminate\Http\Response
21
     */
22
    public function redirectToProvider(string $provider)
23
    {
24
        return Socialite::driver($provider)->redirect();
25
    }
26
27
    /**
28
     * Obtain the user information from Provider.
29
     *
30
     * @param \Illuminate\Http\Request $request
31
     * @param string                   $provider
32
     *
33
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
34
     */
35
    public function handleProviderCallback(Request $request, string $provider)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
36
    {
37
        $providerUser = Socialite::driver($provider)->user();
38
39
        $attributes = [
40
            'id' => $providerUser->id,
41
            'email' => $providerUser->email,
42
            'username' => $providerUser->nickname ?? trim(mb_strstr($providerUser->email, '@', true)),
43
            'first_name' => str_before($providerUser->name, ' '),
44
            'last_name' => str_after($providerUser->name, ' '),
45
        ];
46
47
        switch ($provider) {
48
            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...
49
                $attributes['title'] = $providerUser->user['description'];
50
                $attributes['profile_picture'] = $providerUser->avatar_original;
51
                break;
52
            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...
53
                $attributes['title'] = $providerUser->user['bio'];
54
                $attributes['profile_picture'] = $providerUser->avatar;
55
                break;
56
            case 'facebook':
57
                $attributes['profile_picture'] = $providerUser->avatar_original;
58
                break;
59
            case 'linkedin':
60
                $attributes['title'] = $providerUser->headline;
61
                $attributes['profile_picture'] = $providerUser->avatar_original;
62
                break;
63
            case 'google':
64
                $attributes['title'] = $providerUser->tagline;
65
                $attributes['profile_picture'] = $providerUser->avatar_original;
66
                break;
67
        }
68
69
        if (! ($localUser = $this->getLocalUser($provider, $providerUser->id))) {
70
            $localUser = $this->createLocalUser($provider, $attributes);
71
        }
72
73
        auth()->guard($this->getGuard())->login($localUser, true);
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...
74
75
        return intend([
76
            'intended' => route('adminarea.home'),
77
            'with' => ['success' => trans('cortex/auth::messages.auth.login')],
78
        ]);
79
    }
80
81
    /**
82
     * Get local user for the given provider.
83
     *
84
     * @param string $provider
85
     * @param string $providerUserId
86
     *
87
     * @return \Illuminate\Database\Eloquent\Model|null
88
     */
89
    protected function getLocalUser(string $provider, string $providerUserId)
90
    {
91
        return app('cortex.auth.admin')->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 126 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...
92
            $builder->where('provider', $provider)->where('provider_uid', $providerUserId);
93
        })->first();
94
    }
95
96
    /**
97
     * Create local user for the given provider.
98
     *
99
     * @param string $provider
100
     * @param array  $attributes
101
     *
102
     * @return \Illuminate\Database\Eloquent\Model|null
103
     */
104
    protected function createLocalUser(string $provider, array $attributes)
105
    {
106
        $localUser = app('cortex.auth.admin');
107
108
        $attributes['password'] = str_random();
109
        $attributes['email_verified'] = true;
110
        $attributes['email_verified_at'] = now();
111
        $attributes['is_active'] = ! config('cortex.auth.registration.moderated');
112
113
        $localUser->fill($attributes)->save();
114
115
        // Fire the register success event
116
        event(new Registered($localUser));
117
118
        $localUser->socialites()->create([
119
            'provider' => $provider,
120
            'provider_uid' => $attributes['id'],
121
        ]);
122
123
        return $localUser;
124
    }
125
}
126