feat(auth): block admin login IP after 4 failures for 20 min, email login alerts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
fe68171aa7
commit
e34362b9bd
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\Admin\Auth;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Models\AdminLoginBlock;
|
||||
use App\Services\ActivityLogger;
|
||||
use App\Support\Auth\AdminLoginLockout;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class AdminLoginBlockController extends Controller
|
||||
{
|
||||
public function __construct(private readonly ActivityLogger $activityLogger) {}
|
||||
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
$blocks = AdminLoginBlock::where('blocked_until', '>', now())
|
||||
->orWhere('last_failed_at', '>', now()->subMinutes(AdminLoginLockout::BLOCK_MINUTES))
|
||||
->latest('last_failed_at')
|
||||
->get()
|
||||
->map(fn (AdminLoginBlock $block) => [
|
||||
'id' => $block->id,
|
||||
'ip' => $block->ip,
|
||||
'failed_attempts' => $block->failed_attempts,
|
||||
'last_username' => $block->last_username,
|
||||
'user_agent' => $block->user_agent,
|
||||
'last_failed_at' => $block->last_failed_at,
|
||||
'blocked_until' => $block->isBlocked() ? $block->blocked_until : null,
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'error' => false,
|
||||
'data' => [
|
||||
'items' => $blocks,
|
||||
'max_failures' => AdminLoginLockout::MAX_FAILURES,
|
||||
'block_minutes' => AdminLoginLockout::BLOCK_MINUTES,
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public function destroy(Request $request, int $id): JsonResponse
|
||||
{
|
||||
$block = AdminLoginBlock::findOrFail($id);
|
||||
$block->delete();
|
||||
|
||||
$this->activityLogger->log(
|
||||
event: 'login_unblocked',
|
||||
logName: 'auth',
|
||||
description: sprintf('[admin] %s gỡ chặn đăng nhập cho IP %s (tài khoản thử gần nhất: %s)', $request->user('admin')?->username, $block->ip, $block->last_username ?? '—'),
|
||||
);
|
||||
|
||||
return response()->json(['error' => false, 'message' => 'Đã gỡ chặn IP ' . $block->ip]);
|
||||
}
|
||||
}
|
||||
@@ -8,19 +8,19 @@ use App\Http\Requests\UpdateAdminPasswordRequest;
|
||||
use App\Http\Resources\Api\Admin\AdminUserResource;
|
||||
use App\Services\Api\Admin\AdminRefreshTokenService;
|
||||
use App\Services\ActivityLogger;
|
||||
use App\Support\Auth\AdminLoginAlert;
|
||||
use App\Support\Auth\AdminLoginLockout;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpFoundation\Cookie;
|
||||
use Tymon\JWTAuth\Facades\JWTAuth;
|
||||
|
||||
class AuthController extends Controller
|
||||
{
|
||||
private const LOGIN_MAX_ATTEMPTS = 5;
|
||||
private const LOGIN_DECAY_SECONDS = 60;
|
||||
private const REMEMBER_TTL_SECONDS = 2592000;
|
||||
private const REFRESH_COOKIE = 'admin_refresh_token';
|
||||
private const REFRESH_COOKIE_PATH = '/api/v1/administrator';
|
||||
@@ -38,13 +38,10 @@ class AuthController extends Controller
|
||||
'remember' => 'sometimes|boolean',
|
||||
]);
|
||||
|
||||
$throttleKey = 'admin-login:' . strtolower($request->string('username')->toString()) . '|' . $request->ip();
|
||||
$ip = (string) $request->ip();
|
||||
|
||||
if (RateLimiter::tooManyAttempts($throttleKey, self::LOGIN_MAX_ATTEMPTS)) {
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => 'Bạn đã đăng nhập sai quá nhiều lần. Vui lòng thử lại sau ít phút.',
|
||||
], 429);
|
||||
if ($blockedUntil = AdminLoginLockout::blockedUntil($ip)) {
|
||||
return $this->blockedResponse($blockedUntil);
|
||||
}
|
||||
|
||||
$guard = Auth::guard('admin');
|
||||
@@ -53,25 +50,38 @@ class AuthController extends Controller
|
||||
$token = $guard->attempt($credentials);
|
||||
|
||||
if (!$token) {
|
||||
RateLimiter::hit($throttleKey, self::LOGIN_DECAY_SECONDS);
|
||||
$block = AdminLoginLockout::recordFailure($ip, $request->string('username')->toString(), $request->userAgent());
|
||||
|
||||
$this->activityLogger->log(
|
||||
event: 'login_failed',
|
||||
logName: 'auth',
|
||||
description: '[admin] Đăng nhập thất bại với username: ' . $request->username,
|
||||
description: '[admin] Đăng nhập thất bại với username: ' . $request->username . ' từ IP ' . $ip,
|
||||
);
|
||||
|
||||
if ($block->isBlocked()) {
|
||||
return $this->blockedResponse($block->blocked_until);
|
||||
}
|
||||
|
||||
$remaining = AdminLoginLockout::remainingAttempts($block);
|
||||
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => 'Thông tin đăng nhập không chính xác.',
|
||||
'message' => sprintf(
|
||||
'Thông tin đăng nhập không chính xác. Còn %d lần thử trước khi IP bị chặn %d phút.',
|
||||
$remaining,
|
||||
AdminLoginLockout::BLOCK_MINUTES,
|
||||
),
|
||||
'remaining_attempts' => $remaining,
|
||||
], 401);
|
||||
}
|
||||
|
||||
RateLimiter::clear($throttleKey);
|
||||
AdminLoginLockout::clear($ip);
|
||||
|
||||
$user = Auth::guard('admin')->user();
|
||||
Auth::guard('admin')->getProvider()->rehashPasswordIfRequired($user, $request->only('password'));
|
||||
|
||||
$this->activityLogger->logAuth('login', 'admin', $user->id, $user->username ?? $user->email);
|
||||
AdminLoginAlert::send($user, $ip, $request->userAgent());
|
||||
|
||||
$data = [
|
||||
'token' => $token,
|
||||
@@ -95,6 +105,21 @@ class AuthController extends Controller
|
||||
: $response->withCookie($this->forgetRefreshCookie());
|
||||
}
|
||||
|
||||
private function blockedResponse(\DateTimeInterface $blockedUntil): JsonResponse
|
||||
{
|
||||
$minutes = max(1, (int) ceil((Carbon::instance($blockedUntil)->getTimestamp() - now()->getTimestamp()) / 60));
|
||||
|
||||
return response()->json([
|
||||
'error' => true,
|
||||
'message' => sprintf(
|
||||
'IP của bạn bị chặn đăng nhập do nhập sai quá %d lần. Thử lại sau %d phút hoặc liên hệ quản trị viên để gỡ chặn.',
|
||||
AdminLoginLockout::MAX_FAILURES,
|
||||
$minutes,
|
||||
),
|
||||
'blocked_until' => Carbon::instance($blockedUntil)->toIso8601String(),
|
||||
], 429);
|
||||
}
|
||||
|
||||
public function me(): JsonResponse
|
||||
{
|
||||
$user = Auth::guard('admin')->user();
|
||||
|
||||
@@ -12,6 +12,7 @@ use App\Models\Setting;
|
||||
use App\Models\Template;
|
||||
use App\Services\Email\EmailTemplateRenderer;
|
||||
use App\Services\Email\TemplateGuard;
|
||||
use App\Support\Auth\AdminLoginAlert;
|
||||
use App\Support\EmailScenarioRegistry;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -226,6 +227,7 @@ class EmailTemplateController extends Controller
|
||||
if (!isset($value['mail_enabled'])) {
|
||||
$value['mail_enabled'] = true;
|
||||
}
|
||||
$value[AdminLoginAlert::SETTING_FIELD] = AdminLoginAlert::recipients();
|
||||
|
||||
return response()->json(['error' => false, 'data' => $value]);
|
||||
}
|
||||
@@ -240,6 +242,8 @@ class EmailTemplateController extends Controller
|
||||
'mail_enabled' => 'sometimes|boolean',
|
||||
'auto_disabled' => 'sometimes|array',
|
||||
'auto_disabled.*' => ['string', Rule::in(array_keys(EmailScenarioRegistry::SCENARIOS))],
|
||||
AdminLoginAlert::SETTING_FIELD => 'sometimes|array|max:10',
|
||||
AdminLoginAlert::SETTING_FIELD . '.*' => 'email:rfc|max:191',
|
||||
]);
|
||||
|
||||
$setting = Setting::firstOrNew(['key' => 'email_settings']);
|
||||
|
||||
Reference in New Issue
Block a user