AuthenticatesUsers   A
last analyzed

Complexity

Total Complexity 19

Size/Duplication

Total Lines 131
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 7
Bugs 3 Features 0
Metric Value
wmc 19
c 7
b 3
f 0
lcom 1
cbo 2
dl 0
loc 131
ccs 0
cts 66
cp 0
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
C postLogin() 0 40 7
A getCredentials() 0 7 2
A getFailedLoginMessage() 0 6 2
A loginUsername() 0 4 2
A isUsingThrottlesLoginsTrait() 0 6 1
A customClaims() 0 4 2
A handleUserWasAuthenticated() 0 14 3
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: Claudio Cardinale <[email protected]>
5
 * Date: 18/11/15
6
 * Time: 16.52
7
 * This program is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU General Public License
9
 * as published by the Free Software Foundation; either version 2
10
 * of the License, or (at your option) any later version.
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18
 */
19
20
namespace Tymon\JWTAuth\Support\auth;
21
22
use Illuminate\Http\JsonResponse;
23
use Illuminate\Http\Request;
24
use Illuminate\Support\Facades\Lang;
25
use Tymon\JWTAuth\Facades\JWTAuth;
26
27
/**
28
 * Class AuthenticatesUsers
29
 * @package Tymon\JWTAuth\Support\auth
30
 * @author Claudio Cardinale <[email protected]>
31
 * @copyright 2015 Claudio Cardinale
32
 * @version 1.0.0
33
 */
34
trait AuthenticatesUsers
35
{
36
    /**
37
     * Handle a login request to the application.
38
     *
39
     * @param  \Illuminate\Http\Request  $request
40
     * @return \Illuminate\Http\Response
41
     */
42
    public function postLogin(Request $request)
43
    {
44
        $usernames = $this->loginUsername();
45
        if(!is_array($usernames)) {
46
            $usernames = [$usernames];
47
        }
48
        $usernamesR = [];
49
        foreach($usernames as $username)
50
            $usernamesR[$username] = 'required';
51
52
        $this->validate($request, array_merge($usernamesR, [
0 ignored issues
show
Bug introduced by
It seems like validate() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
53
             'password' => 'required',
54
        ]));
55
56
        // If the class is using the ThrottlesLogins trait, we can automatically throttle
57
        // the login attempts for this application. We'll key this by the username and
58
        // the IP address of the client making these requests into this application.
59
        $throttles = $this->isUsingThrottlesLoginsTrait();
60
61
        if ($throttles && $this->hasTooManyLoginAttempts($request)) {
0 ignored issues
show
Bug introduced by
It seems like hasTooManyLoginAttempts() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
62
            return $this->sendLockoutResponse($request);
0 ignored issues
show
Bug introduced by
It seems like sendLockoutResponse() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
63
        }
64
65
        $credentials = $this->getCredentials($request);
66
67
        if ($token = JWTAuth::attempt($credentials, $this->customClaims())) {
68
            return $this->handleUserWasAuthenticated($request, $throttles, $token);
69
        }
70
71
        // If the login attempt was unsuccessful we will increment the number of attempts
72
        // to login and redirect the user back to the login form. Of course, when this
73
        // user surpasses their maximum number of attempts they will get locked out.
74
        if ($throttles) {
75
            $this->incrementLoginAttempts($request);
0 ignored issues
show
Bug introduced by
It seems like incrementLoginAttempts() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
76
        }
77
78
        return new JsonResponse([
79
            implode('.',$usernames) => [$this->getFailedLoginMessage()],
80
        ], 422);
81
    }
82
83
    /**
84
     * Send the response after the user was authenticated.
85
     *
86
     * @param  \Illuminate\Http\Request  $request
87
     * @param  bool  $throttles
88
     * @param  string  $token
89
     * @return \Illuminate\Http\Response
90
     */
91
    protected function handleUserWasAuthenticated(Request $request, $throttles, $token)
92
    {
93
        if ($throttles) {
94
            $this->clearLoginAttempts($request);
0 ignored issues
show
Bug introduced by
It seems like clearLoginAttempts() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
95
        }
96
97
        if (method_exists($this, 'authenticated')) {
98
            return $this->authenticated($request, $token);
0 ignored issues
show
Bug introduced by
The method authenticated() does not exist on Tymon\JWTAuth\Support\auth\AuthenticatesUsers. 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...
99
        }
100
101
        $response = new JsonResponse(['token' => $token], 200);
102
        $response->header('Authorization', 'Bearer ' . $token);
103
        return $response;
104
    }
105
106
    /**
107
     * Get the needed authorization credentials from the request.
108
     *
109
     * @param  \Illuminate\Http\Request  $request
110
     * @return array
111
     */
112
    protected function getCredentials(Request $request)
113
    {
114
        $usernames = $this->loginUsername();
115
        if(!is_array($usernames))
116
            $usernames = [$usernames];
117
        return $request->only(array_merge($usernames, ['password']));
118
    }
119
120
    /**
121
     * Get the failed login message.
122
     *
123
     * @return string
124
     */
125
    protected function getFailedLoginMessage()
126
    {
127
        return Lang::has('auth.failed')
128
            ? Lang::get('auth.failed')
129
            : 'These credentials do not match our records.';
130
    }
131
132
    /**
133
     * Get the login username to be used by the controller.
134
     * it can be an array for multiple username (for example email and phone number)
135
     *
136
     * @return string|array
137
     */
138
    public function loginUsername()
139
    {
140
        return property_exists($this, 'username') ? $this->username : 'email';
0 ignored issues
show
Bug introduced by
The property username does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
141
    }
142
143
    /**
144
     * Determine if the class is using the ThrottlesLogins trait.
145
     *
146
     * @return bool
147
     */
148
    protected function isUsingThrottlesLoginsTrait()
149
    {
150
        return in_array(
151
            ThrottlesLogins::class, class_uses_recursive(get_class($this))
152
        );
153
    }
154
155
    /**
156
     * Get the custom claims
157
     *
158
     * @return string
159
     */
160
    public function customClaims()
161
    {
162
        return property_exists($this, 'custom') ? $this->custom : [];
0 ignored issues
show
Bug introduced by
The property custom does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
163
    }
164
}