refactor: 更新权限管理与请求验证逻辑

- 在多个控制器中将权限检查从 hasAdminPermission 更新为 hasPermissionCode,以增强权限管理的灵活性。
- 引入 AdminScopePolicy,优化基于代理节点的权限和数据过滤逻辑,确保管理员能够更精确地控制访问权限。
- 在请求验证中添加 agent_node_id 字段,确保 API 接口支持代理节点的相关操作。
- 更新 AdminUser 模型,新增 hasPermissionCode 方法,以支持更细粒度的权限检查。
- 优化审计日志记录逻辑,确保在处理请求时能够准确记录管理员的操作。
This commit is contained in:
2026-06-03 10:07:38 +08:00
parent 0841fbed32
commit 1dcd4716c5
64 changed files with 2054 additions and 344 deletions

View File

@@ -188,5 +188,5 @@ test('auth me includes delegation ceiling for agent user', function (): void {
$this->withHeader('Authorization', 'Bearer '.$token)
->getJson('/api/v1/admin/auth/me')
->assertOk()
->assertJsonStructure(['data' => ['admin' => ['delegation_ceiling']]]);
->assertJsonStructure(['data' => ['admin' => ['delegation_ceiling', 'operational_permissions']]]);
});

View File

@@ -0,0 +1,135 @@
<?php
use App\Models\AuditLog;
use App\Models\AdminUser;
use App\Support\AuditLogApiPresenter;
use App\Lottery\ErrorCode;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use App\Services\AuditLogger;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function (): void {
$this->artisan('lottery:admin-auth-sync')->assertExitCode(0);
});
test('audit log presenter maps business action and entity target', function (): void {
$row = new AuditLog([
'operator_type' => 'admin',
'operator_id' => 1,
'module_code' => 'agent',
'action_code' => 'agent_role.sync_permissions',
'target_type' => 'admin_role',
'target_id' => '5',
]);
$row->id = 1;
$payload = AuditLogApiPresenter::row($row);
expect($payload['module_label'])->toBe('代理')
->and($payload['action_label'])->toBe('同步代理角色权限')
->and($payload['target_label'])->toBe('角色 #5');
});
test('audit log presenter uses admin api resource name for middleware style rows', function (): void {
$resourceName = (string) DB::table('admin_api_resources')
->where('code', 'admin.agent-roles.permissions.sync')
->value('name');
expect($resourceName)->not->toBe('');
$row = new AuditLog([
'operator_type' => 'admin',
'operator_id' => 1,
'module_code' => 'agent',
'action_code' => 'sync',
'target_type' => 'admin.agent-roles.permissions.sync',
'target_id' => '5',
]);
$row->id = 2;
$resourceNames = ['admin.agent-roles.permissions.sync' => $resourceName];
$payload = AuditLogApiPresenter::row($row, $resourceNames);
expect($payload['action_label'])->toBe($resourceName)
->and($payload['target_label'])->toBe($resourceName.' #5');
});
test('agent role permission sync records one business audit and skips middleware duplicate', function (): void {
$siteId = (int) DB::table('admin_sites')->where('is_default', true)->value('id');
$rootId = (int) DB::table('agent_nodes')->where('admin_site_id', $siteId)->where('depth', 0)->value('id');
$service = app(\App\Services\Agent\AgentNodeService::class);
$super = AdminUser::query()->create([
'username' => 'audit_dedup_super',
'name' => 'Super',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($super);
$token = $super->createToken('test', ['*'], now()->addDay())->plainTextToken;
$branch = $service->createChild($super, [
'parent_id' => $rootId,
'code' => 'audit-branch',
'name' => 'Audit Branch',
]);
$create = $this->withHeader('Authorization', 'Bearer '.$token)
->postJson('/api/v1/admin/agent-nodes/'.$branch->id.'/roles', [
'slug' => 'audit_role',
'name' => 'Audit Role',
'permission_slugs' => ['prd.agent.view'],
])
->assertOk();
$roleId = (int) $create->json('data.id');
$maxIdBeforeSync = (int) AuditLog::query()->max('id');
$this->withHeader('Authorization', 'Bearer '.$token)
->putJson('/api/v1/admin/agent-roles/'.$roleId.'/permissions', [
'permission_slugs' => ['prd.agent.view', 'prd.agent.role.view'],
])
->assertOk();
$newRows = AuditLog::query()
->where('id', '>', $maxIdBeforeSync)
->orderBy('id')
->get();
expect($newRows)->toHaveCount(1)
->and($newRows[0]->action_code)->toBe('agent_role.sync_permissions')
->and($newRows[0]->target_type)->toBe('admin_role')
->and($newRows[0]->target_id)->toBe((string) $roleId);
});
test('audit log index returns chinese display labels', function (): void {
AuditLogger::record(
AuditLogger::OPERATOR_ADMIN,
1,
'agent',
'agent_role.sync_permissions',
'admin_role',
'9',
);
$admin = AdminUser::query()->create([
'username' => 'audit_list_super',
'name' => 'Super',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
grantSuperAdminRole($admin);
$token = $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;
$this->withHeader('Authorization', 'Bearer '.$token)
->getJson('/api/v1/admin/audit-logs?per_page=5')
->assertOk()
->assertJsonPath('code', ErrorCode::Success->value)
->assertJsonPath('data.items.0.module_label', '代理')
->assertJsonPath('data.items.0.action_label', '同步代理角色权限')
->assertJsonPath('data.items.0.target_label', '角色 #9');
});

View File

@@ -57,7 +57,8 @@ test('admin auth me returns current admin profile', function () {
->assertOk()
->assertJsonPath('code', ErrorCode::Success->value)
->assertJsonPath('data.admin.username', 'admin_me')
->assertJsonPath('data.admin.navigation.0.segment', 'dashboard');
->assertJsonPath('data.admin.navigation.0.segment', 'dashboard')
->assertJsonStructure(['data' => ['admin' => ['permissions', 'operational_permissions']]]);
});
test('admin login returns bearer token when captcha passes validation', function () {
@@ -95,7 +96,7 @@ test('admin login returns bearer token when captcha passes validation', function
->assertJsonPath('data.admin.navigation.1.segment', 'agents')
->assertJsonPath('data.admin.navigation.1.nav_group', 'agent')
->assertJsonPath('data.admin.navigation.2.segment', 'draws')
->assertJsonStructure(['data' => ['token', 'token_type', 'admin' => ['id', 'username', 'nickname', 'email', 'permissions', 'navigation']]]);
->assertJsonStructure(['data' => ['token', 'token_type', 'admin' => ['id', 'username', 'nickname', 'email', 'permissions', 'operational_permissions', 'navigation']]]);
$token = $resp->json('data.token');
expect($token)->not->toBeNull();

View File

@@ -35,6 +35,32 @@ function settingsAdminToken(): string
return $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;
}
function settingsReadOnlyToken(): string
{
$admin = AdminUser::query()->create([
'username' => 'settings_readonly',
'name' => 'Settings Readonly',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
$role = AdminRole::query()->create([
'slug' => 'settings_readonly_role',
'name' => 'Settings Readonly Role',
]);
$role->syncLegacyPermissionSlugs(['prd.rebate.manage']);
$admin->roles()->sync([
(int) $role->id => [
'site_id' => AdminUser::defaultAdminSiteId(),
'granted_at' => now(),
],
]);
return $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;
}
test('admin can batch update settings in one request', function (): void {
LotterySettings::put('draw.interval_minutes', 5, 'draw');
LotterySettings::put('draw.cooldown_minutes', 15, 'draw');
@@ -101,3 +127,33 @@ test('admin can update single setting with false value', function (): void {
expect(LotterySetting::query()->where('setting_key', 'settlement.apply_rebate_to_payout')->value('value_json'))->toBeFalse();
});
test('non payout manager cannot batch update settlement settings', function (): void {
LotterySettings::put('settlement.auto_payout_on_tick', true, 'settlement');
$token = settingsReadOnlyToken();
$this->withHeader('Authorization', 'Bearer '.$token)
->putJson('/api/v1/admin/settings/batch', [
'items' => [
['key' => 'settlement.auto_payout_on_tick', 'value' => false],
],
])
->assertForbidden();
expect(LotterySetting::query()->where('setting_key', 'settlement.auto_payout_on_tick')->value('value_json'))->toBeTrue();
});
test('non payout manager cannot update single settlement setting', function (): void {
LotterySettings::put('settlement.auto_approve_on_tick', true, 'settlement');
$token = settingsReadOnlyToken();
$this->withHeader('Authorization', 'Bearer '.$token)
->putJson('/api/v1/admin/settings/settlement.auto_approve_on_tick', [
'value' => false,
])
->assertForbidden();
expect(LotterySetting::query()->where('setting_key', 'settlement.auto_approve_on_tick')->value('value_json'))->toBeTrue();
});

View File

@@ -0,0 +1,252 @@
<?php
use App\Models\Draw;
use App\Models\Player;
use App\Models\AdminRole;
use App\Models\AdminUser;
use App\Models\AuditLog;
use App\Models\WalletTxn;
use App\Models\TicketItem;
use App\Models\TicketOrder;
use App\Models\DrawResultBatch;
use App\Models\PlayerWallet;
use App\Models\SettlementBatch;
use App\Models\TicketSettlementDetail;
use App\Lottery\DrawStatus;
use Illuminate\Support\Facades\Hash;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
function settlementPayoutManagerToken(): string
{
$admin = AdminUser::query()->create([
'username' => 'settlement_manager',
'name' => 'Settlement Manager',
'email' => null,
'password' => Hash::make('secret-strong'),
'status' => 0,
]);
$role = AdminRole::query()->create([
'slug' => 'settlement_manager_role',
'name' => 'Settlement Manager Role',
]);
$role->syncLegacyPermissionSlugs(['prd.payout.manage']);
$admin->roles()->sync([
(int) $role->id => [
'site_id' => AdminUser::defaultAdminSiteId(),
'granted_at' => now(),
],
]);
return $admin->createToken('test', ['*'], now()->addDay())->plainTextToken;
}
test('admin can apply settlement payout adjustment for paid batch and audit it', function (): void {
$token = settlementPayoutManagerToken();
$managerId = (int) AdminUser::query()->where('username', 'settlement_manager')->value('id');
$draw = Draw::query()->create([
'draw_no' => '20260603-001',
'business_date' => '2026-06-03',
'sequence_no' => 1,
'status' => DrawStatus::Settled->value,
'start_time' => now()->subHour(),
'close_time' => now()->subMinutes(30),
'draw_time' => now()->subMinutes(20),
'cooling_end_time' => now()->subMinutes(10),
'result_source' => 'manual',
'current_result_version' => 1,
'settle_version' => 1,
'is_reopened' => false,
]);
$player = Player::query()->create([
'site_code' => 'main',
'site_player_id' => 'settlement-adjust-player',
'username' => 'settle_player',
'nickname' => null,
'default_currency' => 'NPR',
'status' => 0,
]);
$wallet = PlayerWallet::query()->create([
'player_id' => $player->id,
'wallet_type' => 'lottery',
'currency_code' => 'NPR',
'balance' => 1_000,
'frozen_balance' => 0,
'status' => 0,
'version' => 0,
]);
$order = TicketOrder::query()->create([
'order_no' => 'TO-SETTLE-ADJUST-1',
'player_id' => $player->id,
'draw_id' => $draw->id,
'currency_code' => 'NPR',
'total_bet_amount' => 100,
'total_rebate_amount' => 0,
'total_actual_deduct' => 100,
'total_estimated_payout' => 500,
'status' => 'settled',
'submit_source' => 'h5',
'client_trace_id' => 'settlement-adjust-trace',
]);
$item = TicketItem::query()->create([
'ticket_no' => 'TK-SETTLE-ADJUST-1',
'order_id' => $order->id,
'player_id' => $player->id,
'draw_id' => $draw->id,
'original_number' => '1234',
'normalized_number' => '1234',
'play_code' => 'big',
'dimension' => 4,
'digit_slot' => null,
'bet_mode' => 'straight',
'unit_bet_amount' => 100,
'total_bet_amount' => 100,
'rebate_rate_snapshot' => 0,
'commission_rate_snapshot' => 0,
'actual_deduct_amount' => 100,
'odds_snapshot_json' => [],
'rule_snapshot_json' => [],
'combination_count' => 1,
'estimated_max_payout' => 500,
'risk_locked_amount' => 0,
'status' => 'settled_win',
'fail_reason_code' => null,
'fail_reason_text' => null,
'win_amount' => 500,
'jackpot_win_amount' => 0,
'settled_at' => now()->subMinutes(5),
]);
$resultBatch = DrawResultBatch::query()->create([
'draw_id' => $draw->id,
'result_version' => 1,
'source_type' => 'manual',
'rng_seed_hash' => null,
'raw_seed_encrypted' => null,
'status' => 'published',
'created_by' => $managerId,
'confirmed_by' => $managerId,
'confirmed_at' => now()->subMinutes(9),
]);
$batch = SettlementBatch::query()->create([
'draw_id' => $draw->id,
'result_batch_id' => $resultBatch->id,
'settle_version' => 1,
'status' => 'paid',
'total_ticket_count' => 1,
'total_win_count' => 1,
'total_payout_amount' => 500,
'total_jackpot_payout_amount' => 0,
'review_status' => 'approved',
'reviewed_by' => $managerId,
'reviewed_at' => now()->subMinutes(6),
'review_remark' => 'approved',
'paid_at' => now()->subMinutes(5),
'started_at' => now()->subMinutes(8),
'finished_at' => now()->subMinutes(7),
]);
TicketSettlementDetail::query()->create([
'settlement_batch_id' => $batch->id,
'ticket_item_id' => $item->id,
'matched_prize_tier' => '1st',
'win_amount' => 500,
'jackpot_allocation_amount' => 0,
'match_detail_json' => ['numbers' => ['1234']],
]);
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson("/api/v1/admin/settlement-batches/{$batch->id}/adjustments", [
'player_id' => $player->id,
'amount_delta' => 120,
'reason' => 'manual payout correction',
])
->assertOk()
->assertJsonPath('data.batch_id', $batch->id)
->assertJsonPath('data.player_id', $player->id)
->assertJsonPath('data.amount_delta', 120)
->assertJsonPath('data.direction', 'credit');
$wallet->refresh();
expect((int) $wallet->balance)->toBe(1_120)
->and(WalletTxn::query()->where('biz_type', 'settlement_adjustment')->count())->toBe(1)
->and(AuditLog::query()->where('module_code', 'settlement')->where('action_code', 'payout_adjustment')->count())->toBe(1);
});
test('admin settlement payout adjustment rejects player outside batch', function (): void {
$token = settlementPayoutManagerToken();
$managerId = (int) AdminUser::query()->where('username', 'settlement_manager')->value('id');
$draw = Draw::query()->create([
'draw_no' => '20260603-002',
'business_date' => '2026-06-03',
'sequence_no' => 2,
'status' => DrawStatus::Settled->value,
'start_time' => now()->subHour(),
'close_time' => now()->subMinutes(30),
'draw_time' => now()->subMinutes(20),
'cooling_end_time' => now()->subMinutes(10),
'result_source' => 'manual',
'current_result_version' => 1,
'settle_version' => 1,
'is_reopened' => false,
]);
$resultBatch = DrawResultBatch::query()->create([
'draw_id' => $draw->id,
'result_version' => 1,
'source_type' => 'manual',
'rng_seed_hash' => null,
'raw_seed_encrypted' => null,
'status' => 'published',
'created_by' => $managerId,
'confirmed_by' => $managerId,
'confirmed_at' => now()->subMinutes(9),
]);
$batch = SettlementBatch::query()->create([
'draw_id' => $draw->id,
'result_batch_id' => $resultBatch->id,
'settle_version' => 1,
'status' => 'paid',
'total_ticket_count' => 0,
'total_win_count' => 0,
'total_payout_amount' => 0,
'total_jackpot_payout_amount' => 0,
'review_status' => 'approved',
'reviewed_by' => $managerId,
'reviewed_at' => now()->subMinutes(6),
'review_remark' => 'approved',
'paid_at' => now()->subMinutes(5),
'started_at' => now()->subMinutes(8),
'finished_at' => now()->subMinutes(7),
]);
$player = Player::query()->create([
'site_code' => 'main',
'site_player_id' => 'not-in-batch',
'username' => null,
'nickname' => null,
'default_currency' => 'NPR',
'status' => 0,
]);
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson("/api/v1/admin/settlement-batches/{$batch->id}/adjustments", [
'player_id' => $player->id,
'amount_delta' => 80,
'reason' => 'should reject',
])
->assertStatus(422);
expect(WalletTxn::query()->where('biz_type', 'settlement_adjustment')->count())->toBe(0);
});

View File

@@ -6,6 +6,8 @@ use App\Models\WalletTxn;
use App\Lottery\ErrorCode;
use App\Models\PlayerWallet;
use App\Models\TransferOrder;
use App\Services\Wallet\MainSiteWalletResult;
use App\Services\Wallet\MainSiteWalletGateway;
use App\Services\Wallet\LotteryTransferService;
use Illuminate\Support\Facades\Hash;
use Illuminate\Foundation\Testing\RefreshDatabase;
@@ -127,6 +129,7 @@ test('admin transfer order list exposes available reconcile actions by status',
['TI_processing', 'processing'],
['TI_failed', 'failed'],
['TI_wait', 'pending_reconcile'],
['TI_credit_failed', 'pending_reconcile'],
['TI_done', 'success'],
] as [$no, $st]
) {
@@ -140,8 +143,8 @@ test('admin transfer order list exposes available reconcile actions by status',
'status' => $st,
'external_request_payload' => null,
'external_response_payload' => null,
'external_ref_no' => null,
'fail_reason' => null,
'external_ref_no' => $no === 'TI_credit_failed' ? 'main-ref-credit-failed' : null,
'fail_reason' => $no === 'TI_credit_failed' ? 'lottery_credit_failed' : null,
'finished_at' => $st === 'success' ? now() : null,
]);
}
@@ -157,9 +160,12 @@ test('admin transfer order list exposes available reconcile actions by status',
->and($byNo['TI_processing']['can_manually_process'])->toBeTrue()
->and($byNo['TI_failed']['can_reverse'])->toBeFalse()
->and($byNo['TI_failed']['can_manually_process'])->toBeTrue()
->and($byNo['TI_wait']['can_reverse'])->toBeTrue()
->and($byNo['TI_wait']['can_reverse'])->toBeFalse()
->and($byNo['TI_wait']['can_manually_process'])->toBeTrue()
->and($byNo['TI_wait']['can_complete_credit'])->toBeFalse()
->and($byNo['TI_credit_failed']['can_reverse'])->toBeTrue()
->and($byNo['TI_credit_failed']['can_manually_process'])->toBeFalse()
->and($byNo['TI_credit_failed']['can_complete_credit'])->toBeTrue()
->and($byNo['TI_done']['can_reverse'])->toBeFalse()
->and($byNo['TI_done']['can_manually_process'])->toBeFalse();
});
@@ -194,7 +200,7 @@ test('admin can manually process abnormal transfer orders except completed ones'
'external_request_payload' => null,
'external_response_payload' => null,
'external_ref_no' => null,
'fail_reason' => null,
'fail_reason' => $no === 'TI_failed_manual' ? 'lottery_credit_failed' : null,
'finished_at' => $st === 'success' ? now() : null,
]);
}
@@ -206,14 +212,80 @@ test('admin can manually process abnormal transfer orders except completed ones'
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson('/api/v1/admin/wallet/transfer-orders/TI_failed_manual/manually-process')
->assertOk()
->assertJsonPath('data.status', 'manually_processed');
->assertStatus(422)
->assertJsonPath('code', ErrorCode::WalletExternalRejected->value);
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson('/api/v1/admin/wallet/transfer-orders/TI_success_manual/manually-process')
->assertStatus(422);
});
test('admin can reverse transfer in credit-failed pending reconcile order and refund main site once', function (): void {
$token = makeAdminToken();
$this->app->instance(MainSiteWalletGateway::class, new class implements MainSiteWalletGateway
{
public function debitMainForLotteryDeposit(Player $player, string $currencyCode, int $amountMinor, string $idempotentKey): MainSiteWalletResult
{
return MainSiteWalletResult::failure('not_used');
}
public function creditMainForLotteryWithdraw(Player $player, string $currencyCode, int $amountMinor, string $idempotentKey): MainSiteWalletResult
{
return MainSiteWalletResult::failure('not_used');
}
public function refundMainForFailedLotteryDeposit(Player $player, string $currencyCode, int $amountMinor, string $idempotentKey): MainSiteWalletResult
{
return MainSiteWalletResult::success(
'main-refund-ref-1',
['success' => true, 'mock' => true],
['mock' => true, 'idempotent_key' => $idempotentKey],
);
}
});
$player = Player::query()->create([
'site_code' => 'stub-refund-site',
'site_player_id' => 'reverse-credit-failed-player',
'username' => null,
'nickname' => null,
'default_currency' => 'NPR',
'status' => 0,
]);
TransferOrder::query()->create([
'transfer_no' => 'TI_reverse_credit_failed',
'player_id' => $player->id,
'direction' => 'in',
'currency_code' => 'NPR',
'amount' => 350,
'idempotent_key' => 'reverse-credit-failed-key',
'status' => 'pending_reconcile',
'external_request_payload' => ['kind' => 'deposit'],
'external_response_payload' => ['kind' => 'timeout'],
'external_ref_no' => 'main-debit-ref-1',
'fail_reason' => 'lottery_credit_failed',
'finished_at' => null,
]);
$path = '/api/v1/admin/wallet/transfer-orders/TI_reverse_credit_failed/reverse';
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson($path, ['remark' => 'refund main site'])
->assertOk()
->assertJsonPath('data.status', 'reversed');
$this->withHeader('Authorization', 'Bearer '.$token)
->postJson($path, ['remark' => 'refund main site again'])
->assertOk()
->assertJsonPath('data.status', 'reversed');
$order = TransferOrder::query()->where('transfer_no', 'TI_reverse_credit_failed')->firstOrFail();
expect($order->status)->toBe('reversed')
->and($order->external_ref_no)->toBe('main-refund-ref-1')
->and(data_get($order->external_request_payload, 'mock'))->toBeTrue();
});
test('admin lists wallet transactions and filters abnormal', function (): void {
$token = makeAdminToken();

View File

@@ -3,6 +3,7 @@
use App\Models\AuditLog;
use Illuminate\Http\Request;
use App\Services\AuditLogger;
use App\Http\Middleware\RecordAdminApiAudit;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
@@ -65,6 +66,8 @@ test('audit logger record from request fills ip', function (): void {
expect($row)
->ip->toContain('198.51.100.2')
->user_agent->toBe('TestAgent');
expect($request->attributes->get(RecordAdminApiAudit::ATTRIBUTE_AUDIT_RECORDED))->toBeTrue();
});
test('record for system uses operator zero', function (): void {

View File

@@ -69,7 +69,7 @@ test('draw results index returns published draws with PRD shaped results', funct
]);
}
$this->getJson('/api/v1/draw/results?per_page=5')
$this->getJson('/api/v1/draw/results?size=5')
->assertOk()
->assertJsonPath('code', 0)
->assertJsonPath('data.items.0.draw_no', '20260509-111')