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']);
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Mail\Admin;
|
||||
|
||||
use App\Mail\TemplateMailable;
|
||||
use Illuminate\Bus\Queueable;
|
||||
|
||||
class AdminLoginAlertMail extends TemplateMailable
|
||||
{
|
||||
use Queueable;
|
||||
|
||||
/**
|
||||
* @param array{admin_name: string, admin_username: string, login_time: string, client_ip: string, user_agent: string} $data
|
||||
*/
|
||||
public function __construct(public array $data) {}
|
||||
|
||||
protected function scenario(): string
|
||||
{
|
||||
return 'admin_login_alert';
|
||||
}
|
||||
|
||||
protected function variables(): array
|
||||
{
|
||||
return $this->data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class AdminLoginBlock extends Model
|
||||
{
|
||||
protected $guarded = [];
|
||||
|
||||
protected $casts = [
|
||||
'last_failed_at' => 'datetime',
|
||||
'blocked_until' => 'datetime',
|
||||
];
|
||||
|
||||
public function isBlocked(): bool
|
||||
{
|
||||
return $this->blocked_until !== null && $this->blocked_until->isFuture();
|
||||
}
|
||||
|
||||
public function scopeActive(Builder $query): Builder
|
||||
{
|
||||
return $query->where('blocked_until', '>', now());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\Auth;
|
||||
|
||||
use App\Mail\Admin\AdminLoginAlertMail;
|
||||
use App\Models\Setting;
|
||||
use App\Models\User;
|
||||
use App\Support\AutoEmailGate;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
class AdminLoginAlert
|
||||
{
|
||||
public const SETTING_FIELD = 'admin_login_alert_emails';
|
||||
public const DEFAULT_RECIPIENTS = ['web@tgs.com.vn'];
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function recipients(): array
|
||||
{
|
||||
$settings = (array) (json_decode(Setting::where('key', 'email_settings')->value('value') ?? '', true) ?? []);
|
||||
|
||||
return array_key_exists(self::SETTING_FIELD, $settings)
|
||||
? array_values(array_filter((array) $settings[self::SETTING_FIELD]))
|
||||
: self::DEFAULT_RECIPIENTS;
|
||||
}
|
||||
|
||||
public static function send(User $admin, string $ip, ?string $userAgent): void
|
||||
{
|
||||
$recipients = self::recipients();
|
||||
if ($recipients === [] || ! AutoEmailGate::allows('admin_login_alert')) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Mail::to($recipients)->queue(new AdminLoginAlertMail([
|
||||
'admin_name' => (string) ($admin->fullname ?: $admin->username),
|
||||
'admin_username' => (string) ($admin->username ?? $admin->email),
|
||||
'login_time' => now()->format('d/m/Y H:i:s'),
|
||||
'client_ip' => $ip,
|
||||
'user_agent' => (string) ($userAgent ?: 'Không xác định'),
|
||||
]));
|
||||
} catch (\Throwable $e) {
|
||||
Log::warning('Không gửi được email thông báo đăng nhập admin', ['admin_id' => $admin->id, 'error' => $e->getMessage()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support\Auth;
|
||||
|
||||
use App\Models\AdminLoginBlock;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class AdminLoginLockout
|
||||
{
|
||||
public const MAX_FAILURES = 4;
|
||||
public const BLOCK_MINUTES = 20;
|
||||
|
||||
public static function blockedUntil(string $ip): ?\DateTimeInterface
|
||||
{
|
||||
$block = AdminLoginBlock::where('ip', $ip)->first();
|
||||
|
||||
return $block?->isBlocked() ? $block->blocked_until : null;
|
||||
}
|
||||
|
||||
public static function recordFailure(string $ip, string $username, ?string $userAgent): AdminLoginBlock
|
||||
{
|
||||
return DB::transaction(function () use ($ip, $username, $userAgent) {
|
||||
AdminLoginBlock::query()->insertOrIgnore(['ip' => $ip, 'created_at' => now(), 'updated_at' => now()]);
|
||||
$block = AdminLoginBlock::where('ip', $ip)->lockForUpdate()->firstOrFail();
|
||||
|
||||
$windowExpired = $block->last_failed_at === null
|
||||
|| $block->last_failed_at->lt(now()->subMinutes(self::BLOCK_MINUTES));
|
||||
$attempts = ($windowExpired && ! $block->isBlocked() ? 0 : $block->failed_attempts) + 1;
|
||||
|
||||
$block->update([
|
||||
'failed_attempts' => $attempts,
|
||||
'last_username' => mb_substr($username, 0, 191),
|
||||
'user_agent' => $userAgent ? mb_substr($userAgent, 0, 500) : null,
|
||||
'last_failed_at' => now(),
|
||||
'blocked_until' => $attempts > self::MAX_FAILURES
|
||||
? now()->addMinutes(self::BLOCK_MINUTES)
|
||||
: $block->blocked_until,
|
||||
]);
|
||||
|
||||
return $block;
|
||||
});
|
||||
}
|
||||
|
||||
public static function remainingAttempts(AdminLoginBlock $block): int
|
||||
{
|
||||
return max(0, self::MAX_FAILURES + 1 - $block->failed_attempts);
|
||||
}
|
||||
|
||||
public static function clear(string $ip): void
|
||||
{
|
||||
AdminLoginBlock::where('ip', $ip)->delete();
|
||||
}
|
||||
}
|
||||
@@ -189,6 +189,10 @@ final class EmailScenarioRegistry
|
||||
'label' => '[Admin] Ticket hỗ trợ mới', 'category' => self::INTERNAL, 'group' => 'SUPPORT',
|
||||
'required_variables' => ['ticket_num'],
|
||||
],
|
||||
'admin_login_alert' => [
|
||||
'label' => '[Admin] Có người đăng nhập trang quản trị', 'category' => self::INTERNAL, 'group' => 'SECURITY',
|
||||
'required_variables' => ['admin_username', 'client_ip', 'login_time'],
|
||||
],
|
||||
];
|
||||
|
||||
public static function find(?string ...$identifiers): ?string
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration {
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('admin_login_blocks', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('ip', 45)->unique();
|
||||
$table->unsignedInteger('failed_attempts')->default(0);
|
||||
$table->string('last_username', 191)->nullable();
|
||||
$table->string('user_agent', 500)->nullable();
|
||||
$table->timestamp('last_failed_at')->nullable();
|
||||
$table->timestamp('blocked_until')->nullable()->index();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('admin_login_blocks');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
use Database\Seeders\TemplateSeeder;
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
return new class extends Migration {
|
||||
public function up(): void
|
||||
{
|
||||
(new TemplateSeeder())->seedScenarioIfMissing('admin_login_alert');
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
DB::table('template')->where('scenario', 'admin_login_alert')->delete();
|
||||
}
|
||||
};
|
||||
@@ -166,6 +166,21 @@ final class AdminTemplates
|
||||
. T::note('{{description}}', 'Nội dung:')
|
||||
. T::button('{{ticket_url}}', 'XEM TICKET'),
|
||||
],
|
||||
[
|
||||
'scenario' => 'admin_login_alert',
|
||||
'name' => '[Admin] Có người đăng nhập trang quản trị',
|
||||
'subject' => '[ADMIN] {{admin_username}} đăng nhập trang quản trị từ IP {{client_ip}}',
|
||||
'body' => T::title('Có người vừa đăng nhập trang quản trị')
|
||||
. T::paragraph('Tài khoản quản trị trên hệ thống <strong>{{company_name}}</strong> vừa đăng nhập thành công.')
|
||||
. T::infoTable([
|
||||
'Nhân viên' => '{{admin_name}}',
|
||||
'Tài khoản' => '{{admin_username}}',
|
||||
'Thời gian' => '{{login_time}}',
|
||||
'Địa chỉ IP' => '{{client_ip}}',
|
||||
'Trình duyệt' => '{{user_agent}}',
|
||||
])
|
||||
. T::note('Nếu đây không phải nhân sự của công ty, hãy đổi mật khẩu tài khoản này và khoá tài khoản ngay trong mục Nhân sự.', 'Lưu ý:'),
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -39,6 +39,7 @@ final class SubjectFormat
|
||||
'admin_trial_registration_request' => ['[ADMIN] yêu cầu dùng thử Cloud VPS', null, 'customer_name'],
|
||||
'admin_manual_deposit_pending' => ['[ADMIN] yêu cầu nạp tiền chờ duyệt {{transaction_code}}', null, 'customer_name'],
|
||||
'admin_ticket_notification' => ['[ADMIN] ticket mới #{{ticket_num}}', null, 'customer_name'],
|
||||
'admin_login_alert' => ['[ADMIN] {{admin_username}} đăng nhập trang quản trị từ IP {{client_ip}}', null, null],
|
||||
'admin_payment_received' => ['[ADMIN] khách hàng thanh toán {{payment_type}} #{{reference}}', null, 'customer_name'],
|
||||
'admin_service_renewed' => ['[ADMIN] {{admin_name}} gia hạn dịch vụ', 'product_name', 'customer_name'],
|
||||
'customer_signup_verify' => ['[ADMIN] đơn hàng mới #{{order_num}}', null, 'customer_name'],
|
||||
|
||||
@@ -112,6 +112,10 @@ final class TemplateVariables
|
||||
'status_line' => ['Tình trạng hạn thanh toán', 'string', 'Hoá đơn sẽ đến hạn sau 3 ngày.'],
|
||||
'paid_row' => ['[Tự động] Dòng đã thanh toán', 'html', ''],
|
||||
'transaction_code' => ['Mã giao dịch', 'string', 'NAP20261008001'],
|
||||
'admin_username' => ['Tài khoản quản trị', 'string', 'admin'],
|
||||
'login_time' => ['Thời gian đăng nhập', 'string', '23/10/2026 08:30:00'],
|
||||
'client_ip' => ['Địa chỉ IP', 'string', '203.113.10.20'],
|
||||
'user_agent' => ['Trình duyệt / thiết bị', 'string', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/141.0'],
|
||||
'amount_formatted' => ['Số tiền', 'string', '500,000'],
|
||||
'payment_type' => ['Loại thanh toán', 'string', 'Hóa đơn'],
|
||||
'reference' => ['Mã tham chiếu', 'string', 'DH20261017001'],
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<?php
|
||||
|
||||
use App\Http\Controllers\Api\Admin\ActivityLog\ActivityLogController;
|
||||
use App\Http\Controllers\Api\Admin\Auth\AdminLoginBlockController;
|
||||
use App\Http\Controllers\Api\Admin\EmailLog\EmailLogController;
|
||||
use App\Http\Controllers\Api\Admin\EmailTemplate\EmailHealthController;
|
||||
use App\Http\Controllers\Api\Admin\EmailTemplate\EmailTemplateController;
|
||||
@@ -27,6 +28,14 @@ Route::prefix('settings')
|
||||
Route::post('test-smtp', 'testSmtp')->middleware('throttle:10,1');
|
||||
});
|
||||
|
||||
Route::prefix('login-blocks')
|
||||
->controller(AdminLoginBlockController::class)
|
||||
->middleware('perm:setting.manager')
|
||||
->group(function () {
|
||||
Route::get('/', 'index');
|
||||
Route::delete('{id}', 'destroy')->whereNumber('id');
|
||||
});
|
||||
|
||||
Route::prefix('client-menu')
|
||||
->controller(ClientMenuController::class)
|
||||
->middleware('perm:setting.manager')
|
||||
|
||||
@@ -4,8 +4,17 @@ declare(strict_types=1);
|
||||
|
||||
namespace Tests\Feature\Api\Admin;
|
||||
|
||||
use App\Mail\Admin\AdminLoginAlertMail;
|
||||
use App\Models\AdminLoginBlock;
|
||||
use App\Models\Setting;
|
||||
use App\Models\User;
|
||||
use App\Support\Auth\AdminLoginAlert;
|
||||
use Database\Seeders\TemplateSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Spatie\Permission\Models\Role;
|
||||
use Tests\TestCase;
|
||||
|
||||
class LoginThrottleTest extends TestCase
|
||||
@@ -15,26 +24,79 @@ class LoginThrottleTest extends TestCase
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
// Đảm bảo state rate-limit sạch, không bị ảnh hưởng bởi request từ test khác
|
||||
// chạy cùng tiến trình PHPUnit (cache 'array' không tự reset giữa các test file).
|
||||
Cache::flush();
|
||||
Mail::fake();
|
||||
(new TemplateSeeder())->seedScenarioIfMissing('admin_login_alert');
|
||||
}
|
||||
|
||||
public function test_admin_login_is_throttled_after_5_attempts_per_minute(): void
|
||||
private function login(string $username, string $password)
|
||||
{
|
||||
for ($i = 0; $i < 5; $i++) {
|
||||
$response = $this->postJson('/api/v1/administrator/login', [
|
||||
'username' => 'nobody',
|
||||
'password' => 'wrong-password',
|
||||
]);
|
||||
$this->assertNotSame(429, $response->status());
|
||||
return $this->postJson('/api/v1/administrator/login', ['username' => $username, 'password' => $password]);
|
||||
}
|
||||
|
||||
private function staff(): User
|
||||
{
|
||||
return User::factory()->create(['username' => 'staff', 'password' => Hash::make('correct-password-123')]);
|
||||
}
|
||||
|
||||
public function test_ip_is_blocked_for_20_minutes_after_more_than_4_failures(): void
|
||||
{
|
||||
$this->staff();
|
||||
|
||||
for ($i = 4; $i >= 1; $i--) {
|
||||
$this->login('staff', 'wrong')->assertUnauthorized()->assertJsonPath('remaining_attempts', $i);
|
||||
}
|
||||
|
||||
$response = $this->postJson('/api/v1/administrator/login', [
|
||||
'username' => 'nobody',
|
||||
'password' => 'wrong-password',
|
||||
]);
|
||||
$this->login('staff', 'wrong')->assertStatus(429);
|
||||
$this->login('staff', 'correct-password-123')->assertStatus(429);
|
||||
$this->login('someone-else', 'whatever')->assertStatus(429);
|
||||
|
||||
$response->assertStatus(429);
|
||||
$this->travel(21)->minutes();
|
||||
$this->login('staff', 'correct-password-123')->assertOk();
|
||||
$this->assertSame(0, AdminLoginBlock::count());
|
||||
}
|
||||
|
||||
public function test_successful_login_alerts_configured_recipients(): void
|
||||
{
|
||||
$this->staff();
|
||||
|
||||
$this->login('staff', 'correct-password-123')->assertOk();
|
||||
Mail::assertQueued(AdminLoginAlertMail::class, fn ($mail) => $mail->hasTo('web@tgs.com.vn'));
|
||||
|
||||
Setting::updateOrCreate(['key' => 'email_settings'], ['value' => json_encode([AdminLoginAlert::SETTING_FIELD => ['it@tgs.com.vn']])]);
|
||||
$this->login('staff', 'correct-password-123')->assertOk();
|
||||
Mail::assertQueued(AdminLoginAlertMail::class, fn ($mail) => $mail->hasTo('it@tgs.com.vn'));
|
||||
}
|
||||
|
||||
public function test_empty_recipient_list_disables_alert(): void
|
||||
{
|
||||
$this->staff();
|
||||
Setting::updateOrCreate(['key' => 'email_settings'], ['value' => json_encode([AdminLoginAlert::SETTING_FIELD => []])]);
|
||||
|
||||
$this->login('staff', 'correct-password-123')->assertOk();
|
||||
Mail::assertNothingQueued();
|
||||
}
|
||||
|
||||
public function test_admin_can_list_and_unblock_ip(): void
|
||||
{
|
||||
$this->staff();
|
||||
for ($i = 0; $i < 5; $i++) {
|
||||
$this->login('staff', 'wrong');
|
||||
}
|
||||
|
||||
Role::firstOrCreate(['name' => 'Full Administrator', 'guard_name' => 'admin']);
|
||||
$admin = User::factory()->create();
|
||||
$admin->assignRole('Full Administrator');
|
||||
|
||||
$id = $this->actingAs($admin, 'admin')->getJson('/api/v1/administrator/login-blocks')
|
||||
->assertOk()
|
||||
->assertJsonPath('data.items.0.ip', '127.0.0.1')
|
||||
->assertJsonPath('data.items.0.last_username', 'staff')
|
||||
->json('data.items.0.id');
|
||||
|
||||
$this->actingAs($admin, 'admin')->deleteJson("/api/v1/administrator/login-blocks/{$id}")->assertOk();
|
||||
$this->app['auth']->forgetGuards();
|
||||
|
||||
$this->login('staff', 'correct-password-123')->assertOk();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,6 +57,7 @@ class PermissionGatingTest extends TestCase
|
||||
return [
|
||||
'settings index' => ['GET', '/api/v1/administrator/settings', 'setting.manager'],
|
||||
'client-menu index' => ['GET', '/api/v1/administrator/client-menu', 'setting.manager'],
|
||||
'login-blocks index' => ['GET', '/api/v1/administrator/login-blocks', 'setting.manager'],
|
||||
'banks index' => ['GET', '/api/v1/administrator/banks', 'setting.manager'],
|
||||
'domain-pricing index' => ['GET', '/api/v1/administrator/domain-pricing', 'setting.manager'],
|
||||
'email-templates index' => ['GET', '/api/v1/administrator/email-templates', 'email-template.manager'],
|
||||
|
||||
Reference in New Issue
Block a user