]> BookStack Code Mirror - bookstack/blob - app/Access/Controllers/ThrottlesLogins.php
Played around with a new app structure
[bookstack] / app / Access / Controllers / ThrottlesLogins.php
1 <?php
2
3 namespace BookStack\Access\Controllers;
4
5 use Illuminate\Cache\RateLimiter;
6 use Illuminate\Http\Request;
7 use Illuminate\Http\Response;
8 use Illuminate\Support\Str;
9 use Illuminate\Validation\ValidationException;
10
11 trait ThrottlesLogins
12 {
13     /**
14      * Determine if the user has too many failed login attempts.
15      */
16     protected function hasTooManyLoginAttempts(Request $request): bool
17     {
18         return $this->limiter()->tooManyAttempts(
19             $this->throttleKey($request),
20             $this->maxAttempts()
21         );
22     }
23
24     /**
25      * Increment the login attempts for the user.
26      */
27     protected function incrementLoginAttempts(Request $request): void
28     {
29         $this->limiter()->hit(
30             $this->throttleKey($request),
31             $this->decayMinutes() * 60
32         );
33     }
34
35     /**
36      * Redirect the user after determining they are locked out.
37      * @throws ValidationException
38      */
39     protected function sendLockoutResponse(Request $request): \Symfony\Component\HttpFoundation\Response
40     {
41         $seconds = $this->limiter()->availableIn(
42             $this->throttleKey($request)
43         );
44
45         throw ValidationException::withMessages([
46             $this->username() => [trans('auth.throttle', [
47                 'seconds' => $seconds,
48                 'minutes' => ceil($seconds / 60),
49             ])],
50         ])->status(Response::HTTP_TOO_MANY_REQUESTS);
51     }
52
53     /**
54      * Clear the login locks for the given user credentials.
55      */
56     protected function clearLoginAttempts(Request $request): void
57     {
58         $this->limiter()->clear($this->throttleKey($request));
59     }
60
61     /**
62      * Get the throttle key for the given request.
63      */
64     protected function throttleKey(Request $request): string
65     {
66         return Str::transliterate(Str::lower($request->input($this->username())) . '|' . $request->ip());
67     }
68
69     /**
70      * Get the rate limiter instance.
71      */
72     protected function limiter(): RateLimiter
73     {
74         return app(RateLimiter::class);
75     }
76
77     /**
78      * Get the maximum number of attempts to allow.
79      */
80     public function maxAttempts(): int
81     {
82         return 5;
83     }
84
85     /**
86      * Get the number of minutes to throttle for.
87      */
88     public function decayMinutes(): int
89     {
90         return 1;
91     }
92 }