LoginRequest::ensureIsNotRateLimited()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3.1852

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 8
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 14
ccs 3
cts 9
cp 0.3333
crap 3.1852
rs 10
1
<?php
2
3
namespace App\Http\Requests\Auth;
4
5
use Illuminate\Auth\Events\Lockout;
6
use Illuminate\Foundation\Http\FormRequest;
7
use Illuminate\Support\Facades\Auth;
8
use Illuminate\Support\Facades\Event;
9
use Illuminate\Support\Facades\RateLimiter;
10
use Illuminate\Support\Str;
11
use Illuminate\Validation\ValidationException;
12
13
class LoginRequest extends FormRequest
14
{
15
    /**
16
     * Get the validation rules that apply to the request.
17
     *
18
     * @return array
19
     */
20 2
    public function rules()
21
    {
22
        return [
23 2
            'email' => ['required', 'string', 'email'],
24
            'password' => ['required', 'string'],
25
        ];
26
    }
27
28
    /**
29
     * {@inheritDoc}
30
     */
31 2
    public function attributes()
32
    {
33
        return [
34 2
            'email' => trans('Email Address'),
35 2
            'password' => trans('Password'),
36
        ];
37
    }
38
39
    /**
40
     * Attempt to authenticate the request's credentials.
41
     *
42
     * @return void
43
     *
44
     * @throws \Illuminate\Validation\ValidationException
45
     */
46 2
    public function authenticate()
47
    {
48 2
        $this->ensureIsNotRateLimited();
49
50 2
        if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
51 1
            RateLimiter::hit($this->throttleKey());
52
53 1
            throw ValidationException::withMessages([
54 1
                'email' => __('auth.failed'),
55
            ]);
56
        }
57
58 1
        RateLimiter::clear($this->throttleKey());
59 1
    }
60
61
    /**
62
     * Ensure the login request is not rate limited.
63
     *
64
     * @return void
65
     *
66
     * @throws \Illuminate\Validation\ValidationException
67
     */
68 2
    public function ensureIsNotRateLimited()
69
    {
70 2
        if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
71 2
            return;
72
        }
73
74
        Event::dispatch(new Lockout($this));
75
76
        $seconds = RateLimiter::availableIn($this->throttleKey());
77
78
        throw ValidationException::withMessages([
79
            'email' => trans('auth.throttle', [
80
                'seconds' => $seconds,
81
                'minutes' => ceil($seconds / 60),
82
            ]),
83
        ]);
84
    }
85
86
    /**
87
     * Get the rate limiting throttle key for the request.
88
     *
89
     * @return string
90
     */
91 2
    public function throttleKey()
92
    {
93 2
        return Str::lower($this->input('email')).'|'.$this->ip();
94
    }
95
}
96