Skip to content

Commit

Permalink
updated user login
Browse files Browse the repository at this point in the history
  • Loading branch information
Kim-the-Diamond committed Sep 9, 2024
1 parent 853e0b4 commit 7f4ea40
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 4 deletions.
5 changes: 1 addition & 4 deletions packages/user/src/Services/Login.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
namespace Moox\User\Services;

use DanHarrin\LivewireRateLimiting\Exceptions\TooManyRequestsException;
use DanHarrin\LivewireRateLimiting\WithRateLimiting;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Facades\Filament;
use Filament\Forms\Components\Checkbox;
Expand Down Expand Up @@ -79,7 +77,7 @@ public function form(Form $form): Form
protected function getLoginFormComponent(): Component
{
return
TextInput::make('login')
TextInput::make('login')
->label('Login')
->required()
->autocomplete()
Expand Down Expand Up @@ -145,7 +143,6 @@ public function authenticate(): Redirector|RedirectResponse|LoginResponse|null
}

return app(LoginResponse::class);

}

protected function getCredentialsFromFormData(array $data): array
Expand Down
60 changes: 60 additions & 0 deletions packages/user/src/Services/WithRateLimiting.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

namespace Moox\User\Services;

use DanHarrin\LivewireRateLimiting\Exceptions\TooManyRequestsException;
use Illuminate\Support\Facades\RateLimiter;

trait WithRateLimiting
{
protected function clearRateLimiter($method = null, $component = null)
{
$method ??= debug_backtrace(limit: 2)[1]['function'];

$component ??= static::class;

$key = $this->getRateLimitKey($method, $component);

RateLimiter::clear($key);
}

protected function getRateLimitKey($method, $component = null)
{
$method ??= debug_backtrace(limit: 2)[1]['function'];

$component ??= static::class;

$identifier = session()->getId() . request()->ip();

return sha1($component . '|' . $method . '|' . $identifier);
}

protected function hitRateLimiter($method = null, $decaySeconds = 60, $component = null)
{
$method ??= debug_backtrace(limit: 2)[1]['function'];

$component ??= static::class;

$key = $this->getRateLimitKey($method, $component);

RateLimiter::hit($key, $decaySeconds);
}

protected function rateLimit($maxAttempts, $decaySeconds = 60, $method = null, $component = null)
{
$method ??= debug_backtrace(limit: 2)[1]['function'];

$component ??= static::class;

$key = $this->getRateLimitKey($method, $component);

if (RateLimiter::tooManyAttempts($key, $maxAttempts)) {
$ip = request()->ip();
$secondsUntilAvailable = RateLimiter::availableIn($key);

throw new TooManyRequestsException($component, $method, $ip, $secondsUntilAvailable);
}

$this->hitRateLimiter($method, $decaySeconds, $component);
}
}

0 comments on commit 7f4ea40

Please sign in to comment.