AuthController::postLogin()   C
last analyzed

Complexity

Conditions 11
Paths 18

Size

Total Lines 49
Code Lines 23

Duplication

Lines 6
Ratio 12.24 %

Importance

Changes 0
Metric Value
dl 6
loc 49
rs 5.2653
c 0
b 0
f 0
cc 11
eloc 23
nc 18
nop 2

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace App\Http\Controllers\Auth;
4
5
use App\Events\UserCreationRequestSent;
6
use App\Http\Requests\LoginUserRequest;
7
use App\Http\Requests\RegisterUserRequest;
8
use App\Orders\CreateWalletOrder;
9
use App\Repositories\UserRepository;
10
use App\Repositories\WalletRepository;
11
use Auth;
12
use Validator;
13
use Illuminate\Http\Request;
14
use App\Http\Controllers\Controller;
15
use Illuminate\Events\Dispatcher;
16
use Illuminate\Foundation\Auth\ThrottlesLogins;
17
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
18
19
class AuthController extends Controller
20
{
21
    /*
22
    |--------------------------------------------------------------------------
23
    | Registration & Login Controller
24
    |--------------------------------------------------------------------------
25
    |
26
    | This controller handles the registration of new users, as well as the
27
    | authentication of existing users. By default, this controller uses
28
    | a simple trait to add these behaviors. Why don't you explore it?
29
    |
30
    */
31
32
    use AuthenticatesAndRegistersUsers, ThrottlesLogins;
33
34
    /**
35
     * Where to redirect users after login / registration.
36
     *
37
     * @var string
38
     */
39
    protected $redirectTo = '/';
40
41
    /**
42
     * @var UserRepository
43
     */
44
    protected $users;
45
46
    /**
47
     * @var WalletRepository
48
     */
49
    protected $wallets;
50
51
    /**
52
     * Login by email.
53
     * 
54
     * @var string
55
     */
56
    public $username = 'email';
57
58
    /**
59
     * AuthController constructor.
60
     *
61
     * @param UserRepository $userRepository
62
     * @param WalletRepository $walletRepository
63
     */
64
    public function __construct(
65
        UserRepository $userRepository = null,
66
        WalletRepository $walletRepository = null
67
    )
68
    {
69
        $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
70
        $this->users = $userRepository;
71
        $this->wallets = $walletRepository;
72
    }
73
74
    /**
75
     * Get recover password page.
76
     *
77
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
78
     */
79
    public function getRecover()
80
    {
81
        return view('auth.recover');
82
    }
83
84
    public function modalLogin(Request $request)
85
    {   
86
        $validation = Validator::make($request->all(), [
87
            $this->loginUsername() => 'required',
88
            'password' => 'required'
89
        ]);
90
91
        $throttles = $this->isUsingThrottlesLoginsTrait();
92
93
        if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {
94
            $this->fireLockoutEvent($request);
95
96
            return json_encode(['errors' => [
97
                $this->loginUsername() => [$this->getLockoutErrorMessage($this->secondsRemainingOnLockout($request))]
98
            ]]);
99
        }
100
101
        if($validation->fails()) {
102
            if ($throttles && ! $lockedOut)
0 ignored issues
show
Bug introduced by
The variable $lockedOut does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
103
                $this->incrementLoginAttempts($request);
104
105
            return json_encode(['errors' => $validation->errors()]);
106
        }
107
        
108
        $credentials = $this->getCredentials($request);
109
110 View Code Duplication
        if(Auth::validate($credentials))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
111
        {
112
            if(! $this->users->getByEmail($credentials['email'])->active)
113
                return json_encode(['errors' => ['This account has blocked. Please contact the support.']]);
114
        }
115
116
        if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
117
118
            if ($throttles) {
119
                $this->clearLoginAttempts($request);
120
            }
121
122
            $user = Auth::user();
123
124
            (new CreateWalletOrder($user));
125
126
            if(! $user->confirmed)
127
                return json_encode(['redirect' => route('resend_verify_email_form')]);
128
            
129
            return json_encode([]);
130
        }
131
    }
132
133
    public function modalRegister(Request $request, Dispatcher $events)
134
    {
135
        $validation = Validator::make(
136
            $request->all(), RegisterUserRequest::getRules()
137
        );
138
        if($validation->fails())
139
            return json_encode(['errors' => $validation->errors()]);
140
141
        $user = $this->users->createSimpleUser($request->all());
142
        
143
        $events->fire(new UserCreationRequestSent($user));
144
145
        Auth::guard($this->getGuard())->login($user);
146
147
        return json_encode(['redirect' => route('resend_verify_email_form')]); 
148
    }
149
150
    /**
151
     * @param LoginUserRequest $request
152
     * @param Dispatcher $events
153
     * @return $this|\Illuminate\Http\RedirectResponse|\Illuminate\Http\Response
154
     */
155
    public function postLogin(LoginUserRequest $request, Dispatcher $events)
0 ignored issues
show
Unused Code introduced by
The parameter $events 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...
156
    {
157
        $throttles = $this->isUsingThrottlesLoginsTrait();
158
159
        if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {
160
            $this->fireLockoutEvent($request);
161
162
            return $this->sendLockoutResponse($request);
163
        }
164
165
        $credentials = $this->getCredentials($request);
166
167 View Code Duplication
        if(Auth::validate($credentials))
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
168
        {
169
            if(! $this->users->getByEmail($credentials['email'])->active)
170
                return redirect()->back()
171
                    ->withErrors(['account' => 'This account has blocked. Please contact the support.']);
172
        }
173
174
        if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
175
176
            if ($throttles) {
177
                $this->clearLoginAttempts($request);
178
            }
179
180
            if (method_exists($this, 'authenticated')) {
181
                return $this->authenticated($request, Auth::guard($this->getGuard())->user());
0 ignored issues
show
Bug introduced by
The method authenticated() does not exist on App\Http\Controllers\Auth\AuthController. Did you maybe mean handleUserWasAuthenticated()?

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...
182
            }
183
184
            // todo: HIGH. Fix it!!!
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
185
//            if(session()->pull('url.intended', '/') == route('admin_login'))
186
//                return redirect()->to('/');
187
188
            $user = Auth::user();
189
190
            (new CreateWalletOrder($user));
191
192
            if(! $user->confirmed)
193
                return redirect()->route('resend_verify_email_form');
194
            
195
            return redirect()->intended($this->redirectPath());
196
        }
197
198
        if ($throttles && ! $lockedOut) {
0 ignored issues
show
Bug introduced by
The variable $lockedOut does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
199
            $this->incrementLoginAttempts($request);
200
        }
201
202
        return $this->sendFailedLoginResponse($request);
203
    }
204
205
    /**
206
     * Post register.
207
     *
208
     * @param RegisterUserRequest $request
209
     * @param Dispatcher $events
210
     * @return \Illuminate\Http\RedirectResponse
211
     */
212
    public function postRegister(RegisterUserRequest $request, Dispatcher $events)
213
    {
214
        $user = $this->users->createSimpleUser($request->all());
215
        
216
        $events->fire(new UserCreationRequestSent($user));
217
218
        Auth::guard($this->getGuard())->login($user);
219
220
        return redirect()->route('resend_verify_email_form');
221
    }
222
}