UserController   B
last analyzed

Complexity

Total Complexity 41

Size/Duplication

Total Lines 228
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 41
c 2
b 0
f 0
lcom 1
cbo 6
dl 0
loc 228
rs 8.2769

20 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A unban() 0 4 1
A isBanned() 0 14 3
A ban() 0 4 1
A addAttempt() 0 17 3
A showLogin() 0 6 2
B login() 0 26 4
A successLoginRedirect() 0 3 1
A failedLoginRedirect() 0 4 1
A attempt() 0 3 2
A getClosureAttempt() 0 3 1
A getClosureCheckAuth() 0 3 1
A checkAuth() 0 3 2
A check() 0 3 1
A onFailValidation() 0 8 1
A getUser() 0 5 1
A attemptLogin() 0 18 3
A isValidUser() 0 10 3
A logout() 0 6 1
C authFilter() 0 23 8

How to fix   Complexity   

Complex Class

Complex classes like UserController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use UserController, and based on these observations, apply Extract Interface, too.

1
<?php namespace Mascame\Artificer\Http\Controllers;
2
3
use Auth;
4
use Carbon\Carbon;
5
use Illuminate\Auth\EloquentUserProvider;
6
use Input;
7
use Mascame\Artificer\Options\AdminOption;
8
use Redirect;
9
use Session;
10
use Validator;
11
use View;
12
13
class UserController extends BaseController
14
{
15
16
    public $tries_key = 'artificer.user.login.tries';
17
    public $ban_key = 'artificer.user.login.banned';
18
    public $authProvider;
19
20
    public function __construct() {
21
        parent::__construct();
22
23
        $this->authProvider = new EloquentUserProvider(app('hash'), 'ArtificerUser');
24
    }
25
26
    /**
27
     * Unban user
28
     */
29
    private function unban()
30
    {
31
        Session::forget($this->ban_key);
32
    }
33
34
    /**
35
     * @return bool
36
     */
37
    private function isBanned()
38
    {
39
        if (Session::has($this->ban_key)) {
40
            $ban = Carbon::parse(Session::get($this->ban_key));
41
42
            if (! $ban->isPast()) {
43
                return true;
44
            }
45
        }
46
47
        $this->unban();
48
49
        return false;
50
    }
51
52
    /**
53
     * Ban user
54
     */
55
    private function ban()
56
    {
57
        Session::set($this->ban_key, Carbon::now()->addMinutes(AdminOption::get('auth.ban_time')));
58
    }
59
60
    /**
61
     *
62
     */
63
    private function addAttempt()
64
    {
65
        $tries = Session::get($this->tries_key);
66
67
        if (! $tries) {
68
            $tries = 1;
69
        } else {
70
            $tries++;
71
        }
72
73
        Session::set($this->tries_key, $tries);
74
75
        if ($tries >= AdminOption::get('auth.max_login_attempts')) {
76
            $this->ban();
77
            Session::forget($this->tries_key);
78
        }
79
    }
80
81
    /**
82
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View
83
     */
84
    public function showLogin()
85
    {
86
        if (Auth::check()) return Redirect::route('admin.home');
0 ignored issues
show
Bug introduced by
The method route() does not seem to exist on object<redirect>.

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...
87
88
        return View::make($this->getView('pages.login'));
89
    }
90
91
    /**
92
     * @return $this|\Illuminate\Http\RedirectResponse
93
     */
94
    public function login()
95
    {
96
        if ($this->isBanned()) {
97
            return Redirect::route('admin.showlogin')->withErrors(array("You are banned for too many login attempts"));
0 ignored issues
show
Bug introduced by
The method route() does not seem to exist on object<redirect>.

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...
98
        }
99
100
        $rules = array(
101
            'username' => 'required|email',
102
            'password' => 'required|min:3'
103
        );
104
105
        $validator = Validator::make(Input::all(), $rules);
106
107
        if ($validator->fails()) {
108
            return $this->onFailValidation($validator);
109
        }
110
111
        /*
112
         * Todo: add also to banning in case of fail auth attempt
113
         */
114
        if ($this->isValidUser($this->getUser())) {
0 ignored issues
show
Bug introduced by
It seems like $this->getUser() targeting Mascame\Artificer\Http\C...erController::getUser() can also be of type object<Mascame\Artificer...rollers\UserController>; however, Mascame\Artificer\Http\C...ntroller::isValidUser() does only seem to accept object<Illuminate\Database\Eloquent\Model>|null, 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...
115
            return $this->successLoginRedirect();
116
        }
117
118
        return $this->failedLoginRedirect();
119
    }
120
121
    protected function successLoginRedirect() {
122
        return Redirect::route('admin.home');
0 ignored issues
show
Bug introduced by
The method route() does not seem to exist on object<redirect>.

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...
123
    }
124
125
    protected function failedLoginRedirect() {
126
        return Redirect::route('admin.login')
0 ignored issues
show
Bug introduced by
The method route() does not seem to exist on object<redirect>.

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...
127
            ->withInput(Input::except('password'))->withErrors(array('The user credentials are not correct or does not have access'));
128
    }
129
130
    protected static function attempt($attemptClosure, $credentials) {
131
        return is_callable($attemptClosure) ? $attemptClosure($credentials) : false;
132
    }
133
134
    protected static function getClosureAttempt() {
135
        return AdminOption::get('auth.attempt');
136
    }
137
138
    protected static function getClosureCheckAuth() {
139
        return AdminOption::get('auth.check');
140
    }
141
142
    protected static function checkAuth($checkClosure) {
143
        return is_callable($checkClosure) ? $checkClosure() : false;
144
    }
145
146
    public static function check() {
147
        return self::checkAuth(self::getClosureCheckAuth());
148
    }
149
150
    protected function onFailValidation($validator)
151
    {
152
        $this->addAttempt();
153
154
        return Redirect::route('admin.login')
0 ignored issues
show
Bug introduced by
The method route() does not seem to exist on object<redirect>.

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...
155
            ->withErrors($validator)
156
            ->withInput();
157
    }
158
159
    /**
160
     * @return \Illuminate\Database\Eloquent\Model|null|static
161
     */
162
    protected function getUser()
163
    {
164
        return \Mascame\Artificer\Auth\ArtificerUser::where('email', '=', Input::get('username'))
165
            ->OrWhere('username', '=', Input::get('username'))->first();
166
    }
167
168
    /**
169
     * @param $user
170
     * @return bool
171
     */
172
    protected function attemptLogin($user)
173
    {
174
        $role_colum = AdminOption::get('auth.role_column');
175
        if (in_array($user->$role_colum, AdminOption::get('auth.roles'))) {
176
177
            $credentials = array(
178
                'email' => Input::get('username'),
179
                'password' => Input::get('password')
180
            );
181
182
            if (self::attempt(self::getClosureAttempt(), $credentials)) {
183
                return true;
184
            }
185
186
        }
187
188
        return false;
189
    }
190
191
    /**
192
     * @param \Illuminate\Database\Eloquent\Model|null $user
193
     * @return bool
194
     */
195
    protected function isValidUser($user)
196
    {
197
        if ($user) {
198
            if ($this->attemptLogin($user)) {
199
                return true;
200
            }
201
        }
202
203
        return false;
204
    }
205
206
    /**
207
     * @return \Illuminate\Http\RedirectResponse
208
     */
209
    public function logout()
210
    {
211
        Auth::logout();
212
213
        return Redirect::route('admin.showlogin');
0 ignored issues
show
Bug introduced by
The method route() does not seem to exist on object<redirect>.

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...
214
    }
215
216
217
    public function authFilter() {
218
        $roles = AdminOption::get('auth.roles');
219
        $role_column = AdminOption::get('auth.role_column');
220
221
        if (Auth::guest()
222
            && \Route::currentRouteName() != 'admin.showlogin'
223
            && \Route::currentRouteName() != 'admin.login'
224
        ) {
225
            if (\Request::ajax()) {
226
                return \Response::make('Unauthorized', 401);
227
            } else {
228
                return Redirect::route('admin.showlogin');
0 ignored issues
show
Bug introduced by
The method route() does not seem to exist on object<redirect>.

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...
229
            }
230
        } else {
231
            if (Auth::check()
232
                && \Route::currentRouteName() != 'admin.logout'
233
            ) {
234
                if (!in_array(Auth::user()->$role_column, $roles)) {
235
                    return Redirect::route('admin.logout');
0 ignored issues
show
Bug introduced by
The method route() does not seem to exist on object<redirect>.

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...
236
                }
237
            }
238
        }
239
    }
240
}