LoginController::loginViaWeb()   C
last analyzed

Complexity

Conditions 7
Paths 8

Size

Total Lines 50
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 50
ccs 0
cts 24
cp 0
rs 6.7272
cc 7
eloc 25
nc 8
nop 1
crap 56
1
<?php namespace App\Http\Controllers\Auth;
2
3
use App\Events\Users\LoggedIn;
4
use App\Events\Users\LoggedOut;
5
use App\Events\Users\Registered;
6
use App\Exceptions\Common\ValidationException;
7
use App\Exceptions\Users\LoginNotValidException;
8
use App\Http\Controllers\Controller;
9
use App\Models\User;
10
use App\Models\UserOAuth;
11
use Illuminate\Foundation\Auth\AuthenticatesUsers;
12
use Illuminate\Http\Request;
13
use Laravel\Socialite\Contracts\Factory as SocialiteContract;
14
use Laravel\Socialite\AbstractUser as SocialiteUser;
15
16
class LoginController extends Controller
17
{
18
    use AuthenticatesUsers;
19
20
    private $redirectTo;
21
22
    /**
23
     * Create a new authentication controller instance.
24
     */
25
    public function __construct()
26
    {
27
        if (!empty($locale = app('translator')->getLocale()) && $locale != app('config')->get('app.locale')) {
28
            $this->redirectTo = '/' . $locale . $this->redirectTo;
29
        }
30
31
        $this->middleware('guest', ['except' => 'logout']);
32
    }
33
34
    /**
35
     * Show the application login form.
36
     *
37
     * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View
38
     */
39
    public function showLoginForm()
40
    {
41
        return view('auth/login');
42
    }
43
44
    /**
45
     * Log the user in.
46
     *
47
     * @param \Illuminate\Http\Request $request
48
     *
49
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
50
     * @throws \App\Exceptions\Common\ValidationException
51
     */
52
    public function loginViaWeb(Request $request)
53
    {
54
        $validator = app('validator')->make($request->all(), [
55
            'email' => 'required|email',
56
            'password' => 'required',
57
        ]);
58
        if ($validator->fails()) {
59
            throw new ValidationException($validator);
60
        }
61
62
        // If the class is using the ThrottlesLogins trait, we can automatically throttle
63
        // the login attempts for this application. We'll key this by the username and
64
        // the IP address of the client making these requests into this application.
65
        if ($lockedOut = $this->hasTooManyLoginAttempts($request)) {
66
            $this->fireLockoutEvent($request);
67
68
            return $this->sendLockoutResponse($request);
69
        }
70
71
        $credentials = $request->only('email', 'password');
72
73
        if (app('auth.driver')->attempt($credentials, $request->has('remember'))) {
74
            $request->session()->regenerate();
0 ignored issues
show
Bug introduced by
The method regenerate() does not seem to exist on object<Symfony\Component...ssion\SessionInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
75
            $this->clearLoginAttempts($request);
76
            event(new LoggedIn($user = app('auth.driver')->user()));
77
78
            if ($request->expectsJson()) {
79
                return response()->json(['data' => $user]);
80
            }
81
82
            return redirect()->intended($this->redirectPath());
83
        }
84
85
        // If the login attempt was unsuccessful we will increment the number of attempts
86
        // to login and redirect the user back to the login form. Of course, when this
87
        // user surpasses their maximum number of attempts they will get locked out.
88
        if (!$lockedOut) {
89
            $this->incrementLoginAttempts($request);
90
        }
91
92
        if ($request->expectsJson()) {
93
            throw new LoginNotValidException();
94
        }
95
96
        return redirect()->back()
97
            ->withInput($request->only('email', 'remember'))
98
            ->withErrors([
99
                'email' => app('translator')->get('auth.failed'),
100
            ]);
101
    }
102
103
    /**
104
     * @param \Laravel\Socialite\Contracts\Factory $socialite
105
     * @param string                               $provider
106
     *
107
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
108
     */
109
    public function handleOAuthRedirect(SocialiteContract $socialite, $provider)
110
    {
111
        return $socialite->driver($provider)->redirect();
112
    }
113
114
    /**
115
     * Handle OAuth login.
116
     *
117
     * @param \Illuminate\Http\Request             $request
118
     * @param \Laravel\Socialite\Contracts\Factory $socialite
119
     * @param string                               $provider
120
     *
121
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
122
     */
123
    public function handleOAuthReturn(Request $request, SocialiteContract $socialite, $provider)
124
    {
125
        switch ($provider) {
126
            case 'google':
127
            case 'facebook':
128
                if (!$request->exists('code')) {
129
                    return redirect('/login')->withErrors(trans('passwords.oauth_failed'));
0 ignored issues
show
Bug introduced by
It seems like trans('passwords.oauth_failed') targeting trans() can also be of type object<Illuminate\Contra...Translation\Translator>; however, Illuminate\Http\RedirectResponse::withErrors() does only seem to accept object<Illuminate\Contra...eProvider>|array|string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
130
                }
131
                break;
132
            case 'twitter':
133
                if (!$request->exists('oauth_token') || !$request->exists('oauth_verifier')) {
134
                    return redirect('/login')->withErrors(trans('passwords.oauth_failed'));
0 ignored issues
show
Bug introduced by
It seems like trans('passwords.oauth_failed') targeting trans() can also be of type object<Illuminate\Contra...Translation\Translator>; however, Illuminate\Http\RedirectResponse::withErrors() does only seem to accept object<Illuminate\Contra...eProvider>|array|string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
135
                }
136
                break;
137
        }
138
139
        /** @var SocialiteUser $userInfo */
140
        $userInfo = $socialite->driver($provider)->user();
141
        if ($this->loginViaOAuth($userInfo, $provider)) {
142
            return redirect()->intended($this->redirectPath());
143
        }
144
145
        return redirect('/login')->withErrors(trans('passwords.oauth_failed'));
0 ignored issues
show
Bug introduced by
It seems like trans('passwords.oauth_failed') targeting trans() can also be of type object<Illuminate\Contra...Translation\Translator>; however, Illuminate\Http\RedirectResponse::withErrors() does only seem to accept object<Illuminate\Contra...eProvider>|array|string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
146
    }
147
148
    /**
149
     * @param SocialiteUser $oauthUserData
150
     * @param string        $provider
151
     *
152
     * @return bool
153
     */
154
    protected function loginViaOAuth(SocialiteUser $oauthUserData, $provider)
155
    {
156
        /** @var UserOAuth $owningOAuthAccount */
157
        if ($owningOAuthAccount = UserOAuth::whereRemoteProvider($provider)->whereRemoteId($oauthUserData->id)->first()) {
158
            $ownerAccount = $owningOAuthAccount->owner;
159
            app('auth.driver')->login($ownerAccount, true);
160
161
            event(new LoggedIn($ownerAccount, $provider));
162
163
            return true;
164
        }
165
166
        return !$this->registerViaOAuth($oauthUserData, $provider) ? false : true;
167
    }
168
169
    /**
170
     * @param SocialiteUser $oauthUserData
171
     * @param string        $provider
172
     *
173
     * @return \Illuminate\Contracts\Auth\Authenticatable|bool
174
     */
175
    protected function registerViaOAuth(SocialiteUser $oauthUserData, $provider)
176
    {
177
        /** @var \App\Models\User $ownerAccount */
178
        if (!($ownerAccount = User::withTrashed()->whereEmail($oauthUserData->email)->first())) {
0 ignored issues
show
Bug introduced by
The method withTrashed() does not exist on App\Models\User. Did you maybe mean trashed()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
179
            $ownerAccount = User::create([
0 ignored issues
show
Bug introduced by
The method create() does not exist on App\Models\User. Did you maybe mean whereCreatedAt()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
180
                'name' => $oauthUserData->name,
181
                'email' => $oauthUserData->email,
182
                'password' => app('hash')->make(uniqid("", true))
183
            ]);
184
            event(new Registered($ownerAccount, $provider));
185
        }
186
187
        # If user account is soft-deleted, restore it.
188
        $ownerAccount->trashed() && $ownerAccount->restore();
189
190
        # Update missing user name.
191
        if (!$ownerAccount->name) {
192
            $ownerAccount->name = $oauthUserData->name;
193
            $ownerAccount->save();
194
        }
195
196
        ($doLinkOAuthAccount = $this->linkOAuthAccount($oauthUserData, $provider, $ownerAccount)) && app('auth.driver')->login($ownerAccount, true);
197
198
        event(new LoggedIn($ownerAccount, $provider));
199
200
        return $doLinkOAuthAccount;
201
    }
202
203
    /**
204
     * @param SocialiteUser $oauthUserData
205
     * @param string        $provider
206
     * @param User          $ownerAccount
207
     *
208
     * @return \App\Models\User|bool
209
     */
210
    protected function linkOAuthAccount(SocialiteUser $oauthUserData, $provider, $ownerAccount)
211
    {
212
        /** @var UserOAuth[] $linkedAccounts */
213
        $linkedAccounts = $ownerAccount->linkedAccounts()->ofProvider($provider)->get();
214
215
        foreach ($linkedAccounts as $linkedAccount) {
216
            if ($linkedAccount->remote_id === $oauthUserData->id || $linkedAccount->email === $oauthUserData->email) {
217
                $linkedAccount->remote_id = $oauthUserData->id;
218
                $linkedAccount->nickname = $oauthUserData->nickname;
219
                $linkedAccount->name = $oauthUserData->name;
220
                $linkedAccount->email = $oauthUserData->email;
221
                $linkedAccount->avatar = $oauthUserData->avatar;
222
223
                return $linkedAccount->save() ? $ownerAccount : false;
224
            }
225
        }
226
227
        $linkedAccount = new UserOAuth();
228
        $linkedAccount->remote_provider = $provider;
229
        $linkedAccount->remote_id = $oauthUserData->id;
230
        $linkedAccount->nickname = $oauthUserData->nickname;
231
        $linkedAccount->name = $oauthUserData->name;
232
        $linkedAccount->email = $oauthUserData->email;
233
        $linkedAccount->avatar = $oauthUserData->avatar;
234
235
        return $ownerAccount->linkedAccounts()->save($linkedAccount) ? $ownerAccount : false;
236
    }
237
238
    /**
239
     * Log the user out of the application.
240
     *
241
     * @param \Illuminate\Http\Request $request
242
     *
243
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
244
     */
245
    public function logout(Request $request)
246
    {
247
        if (app('auth.driver')->check()) {
248
            $user = app('auth.driver')->user();
249
250
            app('auth.driver')->logout();
251
252
            app('events')->fire(new LoggedOut($user));
253
        }
254
255
        $request->session()->flush();
0 ignored issues
show
Bug introduced by
The method flush() does not seem to exist on object<Symfony\Component...ssion\SessionInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
256
        $request->session()->regenerate();
0 ignored issues
show
Bug introduced by
The method regenerate() does not seem to exist on object<Symfony\Component...ssion\SessionInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
257
258
        if ($request->expectsJson()) {
259
            return response()->json([]);
260
        }
261
262
        return redirect('/');
263
    }
264
}
265