Files
lotteryLaravel/tests/Feature/PlayerNativeAuthTest.php

467 lines
17 KiB
PHP

<?php
use App\Models\Player;
use App\Lottery\ErrorCode;
use Illuminate\Support\Str;
use App\Models\PlayerWallet;
use App\Support\PlayerAuthSource;
use App\Support\PlayerFundingMode;
use Illuminate\Support\Facades\DB;
use Database\Seeders\CurrencySeeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Cache;
use Database\Seeders\LotterySettingsSeeder;
use Illuminate\Support\Facades\RateLimiter;
use App\Services\Player\PlayerNativeAuthService;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function (): void {
config([
'lottery.player_auth.native.secret' => 'test-native-jwt-secret-32bytes!!',
'lottery.player_auth.native.ttl_seconds' => 3600,
'lottery.main_site.wallet_api_url' => null,
]);
$this->seed(CurrencySeeder::class);
$this->seed(LotterySettingsSeeder::class);
});
/**
* @return array{captcha_key: string, captcha_code: string}
*/
function playerLoginCaptcha(string $code = 'xwz2'): array
{
$key = (string) Str::uuid();
Cache::put(
'player_captcha:'.$key,
hash_hmac('sha256', strtolower($code), (string) config('app.key')),
now()->addSeconds(120),
);
return [
'captcha_key' => $key,
'captcha_code' => $code,
];
}
test('native player can login without site code using default site', function (): void {
$site = DB::table('admin_sites')->where('is_default', true)->first();
$rootId = (int) DB::table('agent_nodes')->where('depth', 0)->value('id');
$player = Player::query()->create([
'site_code' => (string) $site->code,
'agent_node_id' => $rootId,
'site_player_id' => 'native:test-no-site',
'auth_source' => PlayerAuthSource::LOTTERY_NATIVE,
'funding_mode' => PlayerFundingMode::CREDIT,
'username' => 'agentplayer0',
'password_hash' => Hash::make('secret-pass'),
'nickname' => null,
'default_currency' => 'NPR',
'status' => 0,
]);
$login = $this->postJson('/api/v1/player/auth/login', array_merge([
'username' => 'agentplayer0',
'password' => 'secret-pass',
], playerLoginCaptcha()));
$login->assertOk()
->assertJsonPath('data.player.id', $player->id);
});
test('native player can login without site code on non-default site when username is unique', function (): void {
$siteId = (int) DB::table('admin_sites')->insertGetId([
'code' => 'kk88',
'name' => 'kk88',
'is_default' => false,
'created_at' => now(),
'updated_at' => now(),
]);
$rootId = (int) DB::table('agent_nodes')->insertGetId([
'admin_site_id' => $siteId,
'parent_id' => null,
'depth' => 0,
'path' => '/kk88',
'code' => 'kk88-root',
'name' => 'Root',
'status' => 1,
'created_at' => now(),
'updated_at' => now(),
]);
$player = Player::query()->create([
'site_code' => 'kk88',
'agent_node_id' => $rootId,
'site_player_id' => 'native:kk88-1',
'auth_source' => PlayerAuthSource::LOTTERY_NATIVE,
'funding_mode' => PlayerFundingMode::CREDIT,
'username' => 'play1',
'password_hash' => Hash::make('secret-pass'),
'nickname' => null,
'default_currency' => 'NPR',
'status' => 0,
]);
$this->postJson('/api/v1/player/auth/login', array_merge([
'username' => 'play1',
'password' => 'secret-pass',
], playerLoginCaptcha()))
->assertOk()
->assertJsonPath('data.player.id', $player->id)
->assertJsonPath('data.player.site_code', 'kk88');
});
test('native player login without site code rejects ambiguous username across sites', function (): void {
$defaultSite = DB::table('admin_sites')->where('is_default', true)->first();
$rootId = (int) DB::table('agent_nodes')->where('depth', 0)->value('id');
$siteId = (int) DB::table('admin_sites')->insertGetId([
'code' => 'other_site',
'name' => 'Other',
'is_default' => false,
'created_at' => now(),
'updated_at' => now(),
]);
$otherRootId = (int) DB::table('agent_nodes')->insertGetId([
'admin_site_id' => $siteId,
'parent_id' => null,
'depth' => 0,
'path' => '/other',
'code' => 'other-root',
'name' => 'Other Root',
'status' => 1,
'created_at' => now(),
'updated_at' => now(),
]);
foreach ([
['site_code' => (string) $defaultSite->code, 'agent_node_id' => $rootId, 'site_player_id' => 'dup-a'],
['site_code' => 'other_site', 'agent_node_id' => $otherRootId, 'site_player_id' => 'dup-b'],
] as $row) {
Player::query()->create([
'site_code' => $row['site_code'],
'agent_node_id' => $row['agent_node_id'],
'site_player_id' => $row['site_player_id'],
'auth_source' => PlayerAuthSource::LOTTERY_NATIVE,
'funding_mode' => PlayerFundingMode::CREDIT,
'username' => 'dup_user',
'password_hash' => Hash::make('secret-pass'),
'nickname' => null,
'default_currency' => 'NPR',
'status' => 0,
]);
}
$this->postJson('/api/v1/player/auth/login', array_merge([
'username' => 'dup_user',
'password' => 'secret-pass',
], playerLoginCaptcha()))->assertJsonPath('code', 8006);
});
test('player auth captcha exposes key and image base64', function (): void {
$resp = $this->getJson('/api/v1/player/auth/captcha');
$resp->assertOk();
$data = $resp->json('data');
expect($data)->toHaveKeys(['captcha_key', 'image_base64'])
->and(Str::isUuid((string) $data['captcha_key']))->toBeTrue()
->and(base64_decode((string) $data['image_base64'], true))->not->toBeFalse();
});
test('native player login rejects invalid captcha', function (): void {
$site = DB::table('admin_sites')->where('is_default', true)->first();
$rootId = (int) DB::table('agent_nodes')->where('depth', 0)->value('id');
Player::query()->create([
'site_code' => (string) $site->code,
'agent_node_id' => $rootId,
'site_player_id' => 'native:captcha-fail',
'auth_source' => PlayerAuthSource::LOTTERY_NATIVE,
'funding_mode' => PlayerFundingMode::CREDIT,
'username' => 'captchafail',
'password_hash' => Hash::make('secret-pass'),
'nickname' => null,
'default_currency' => 'NPR',
'status' => 0,
]);
$captcha = playerLoginCaptcha('xwz2');
$this->postJson('/api/v1/player/auth/login', [
'username' => 'captchafail',
'password' => 'secret-pass',
'captcha_key' => $captcha['captcha_key'],
'captcha_code' => 'aaaa',
])->assertStatus(422)->assertJsonPath('code', 8009);
});
test('native player can login and access me', function (): void {
$site = DB::table('admin_sites')->where('is_default', true)->first();
$rootId = (int) DB::table('agent_nodes')->where('depth', 0)->value('id');
$player = Player::query()->create([
'site_code' => (string) $site->code,
'agent_node_id' => $rootId,
'site_player_id' => 'native:test-1',
'auth_source' => PlayerAuthSource::LOTTERY_NATIVE,
'funding_mode' => PlayerFundingMode::CREDIT,
'username' => 'agentplayer1',
'password_hash' => Hash::make('secret-pass'),
'nickname' => null,
'default_currency' => 'NPR',
'status' => 0,
]);
DB::table('player_credit_accounts')->insert([
'player_id' => $player->id,
'credit_limit' => 50000,
'used_credit' => 0,
'frozen_credit' => 0,
'created_at' => now(),
'updated_at' => now(),
]);
$login = $this->postJson('/api/v1/player/auth/login', array_merge([
'site_code' => $site->code,
'username' => 'agentplayer1',
'password' => 'secret-pass',
], playerLoginCaptcha()));
$login->assertOk();
$token = (string) $login->json('data.access_token');
expect($token)->not->toBe('');
$me = $this->withHeader('Authorization', 'Bearer '.$token)
->getJson('/api/v1/player/me');
$me->assertOk()
->assertJsonPath('data.id', $player->id)
->assertJsonPath('data.funding_mode', PlayerFundingMode::CREDIT)
->assertJsonPath('data.auth_source', PlayerAuthSource::LOTTERY_NATIVE);
});
test('credit player wallet transfer in is rejected', function (): void {
$site = DB::table('admin_sites')->where('is_default', true)->first();
$rootId = (int) DB::table('agent_nodes')->where('depth', 0)->value('id');
$player = Player::query()->create([
'site_code' => (string) $site->code,
'agent_node_id' => $rootId,
'site_player_id' => 'native:test-2',
'auth_source' => PlayerAuthSource::LOTTERY_NATIVE,
'funding_mode' => PlayerFundingMode::CREDIT,
'username' => 'agentplayer2',
'password_hash' => Hash::make('secret-pass'),
'nickname' => null,
'default_currency' => 'NPR',
'status' => 0,
]);
$auth = app(PlayerNativeAuthService::class);
$token = $auth->issueToken($player);
$response = $this->withHeader('Authorization', 'Bearer '.$token)
->postJson('/api/v1/wallet/transfer-in', [
'amount' => 1000,
'idempotent_key' => 'native-ti-1',
'currency' => 'NPR',
]);
$response->assertJsonPath('code', 1011);
});
test('sso wallet player balance does not use credit when site credit mode on', function (): void {
$site = DB::table('admin_sites')->where('is_default', true)->first();
$extra = json_decode((string) ($site->extra_json ?? '{}'), true);
if (! is_array($extra)) {
$extra = [];
}
$extra['credit_line_mode'] = true;
DB::table('admin_sites')->where('id', $site->id)->update([
'extra_json' => json_encode($extra),
'updated_at' => now(),
]);
$player = Player::query()->create([
'site_code' => (string) $site->code,
'site_player_id' => 'sso-wallet-1',
'auth_source' => PlayerAuthSource::MAIN_SITE_SSO,
'funding_mode' => PlayerFundingMode::WALLET,
'username' => 'ssouser',
'nickname' => null,
'default_currency' => 'NPR',
'status' => 0,
]);
PlayerWallet::query()->create([
'player_id' => $player->id,
'wallet_type' => 'lottery',
'currency_code' => 'NPR',
'balance' => 12000,
'frozen_balance' => 0,
'status' => 0,
'version' => 0,
]);
$response = $this->withHeader('Authorization', 'Bearer dev:'.$player->id)
->getJson('/api/v1/wallet/balance?currency=NPR');
$response->assertOk()
->assertJsonPath('data.credit_line_mode', false)
->assertJsonPath('data.funding_mode', PlayerFundingMode::WALLET)
->assertJsonPath('data.available_balance', 12000);
});
test('native player can change password and previous tokens are invalidated', function (): void {
$site = DB::table('admin_sites')->where('is_default', true)->first();
$rootId = (int) DB::table('agent_nodes')->where('depth', 0)->value('id');
$player = Player::query()->create([
'site_code' => (string) $site->code,
'agent_node_id' => $rootId,
'site_player_id' => 'native:password-change',
'auth_source' => PlayerAuthSource::LOTTERY_NATIVE,
'funding_mode' => PlayerFundingMode::CREDIT,
'username' => 'password_change_user',
'password_hash' => Hash::make('old-secret'),
'default_currency' => 'NPR',
'status' => 0,
]);
$oldToken = app(PlayerNativeAuthService::class)->issueToken($player);
$this->withHeader('Authorization', 'Bearer '.$oldToken)
->putJson('/api/v1/player/password', [
'current_password' => 'old-secret',
'password' => 'new-secret',
'password_confirmation' => 'new-secret',
])
->assertOk()
->assertJsonPath('data.password_changed', true);
$player->refresh();
expect(Hash::check('new-secret', (string) $player->password_hash))->toBeTrue()
->and($player->native_token_version)->toBe(1);
$this->withHeader('Authorization', 'Bearer '.$oldToken)
->getJson('/api/v1/player/me')
->assertStatus(401)
->assertJsonPath('code', ErrorCode::PlayerTokenInvalid->value);
$this->postJson('/api/v1/player/auth/login', array_merge([
'username' => 'password_change_user',
'password' => 'old-secret',
], playerLoginCaptcha()))
->assertStatus(401)
->assertJsonPath('code', ErrorCode::PlayerCredentialsInvalid->value);
$this->postJson('/api/v1/player/auth/login', array_merge([
'username' => 'password_change_user',
'password' => 'new-secret',
], playerLoginCaptcha()))
->assertOk()
->assertJsonPath('data.player.id', $player->id);
});
test('native player password change validates current password', function (): void {
$site = DB::table('admin_sites')->where('is_default', true)->first();
$rootId = (int) DB::table('agent_nodes')->where('depth', 0)->value('id');
$player = Player::query()->create([
'site_code' => (string) $site->code,
'agent_node_id' => $rootId,
'site_player_id' => 'native:password-current',
'auth_source' => PlayerAuthSource::LOTTERY_NATIVE,
'funding_mode' => PlayerFundingMode::CREDIT,
'username' => 'password_current_user',
'password_hash' => Hash::make('old-secret'),
'default_currency' => 'NPR',
'status' => 0,
]);
$token = app(PlayerNativeAuthService::class)->issueToken($player);
$this->withHeader('Authorization', 'Bearer '.$token)
->putJson('/api/v1/player/password', [
'current_password' => 'wrong-secret',
'password' => 'new-secret',
'password_confirmation' => 'new-secret',
])
->assertStatus(422)
->assertJsonPath('msg', 'The current password is incorrect.');
expect($player->fresh()->native_token_version)->toBe(0)
->and(Hash::check('old-secret', (string) $player->fresh()->password_hash))->toBeTrue();
});
test('native player password change is rate limited by player and ip', function (): void {
$site = DB::table('admin_sites')->where('is_default', true)->first();
$rootId = (int) DB::table('agent_nodes')->where('depth', 0)->value('id');
$player = Player::query()->create([
'site_code' => (string) $site->code,
'agent_node_id' => $rootId,
'site_player_id' => 'native:password-rate-limit',
'auth_source' => PlayerAuthSource::LOTTERY_NATIVE,
'funding_mode' => PlayerFundingMode::CREDIT,
'username' => 'password_rate_limit_user',
'password_hash' => Hash::make('old-secret'),
'default_currency' => 'NPR',
'status' => 0,
]);
$ip = '198.51.100.25';
$token = app(PlayerNativeAuthService::class)->issueToken($player);
RateLimiter::clear($player->id.'|'.$ip);
for ($attempt = 0; $attempt < 5; $attempt++) {
$this->withServerVariables(['REMOTE_ADDR' => $ip])
->withHeader('Authorization', 'Bearer '.$token)
->putJson('/api/v1/player/password', [
'current_password' => 'wrong-secret',
'password' => 'new-secret',
'password_confirmation' => 'new-secret',
])
->assertStatus(422);
}
$this->withServerVariables(['REMOTE_ADDR' => $ip])
->withHeader('Authorization', 'Bearer '.$token)
->putJson('/api/v1/player/password', [
'current_password' => 'wrong-secret',
'password' => 'new-secret',
'password_confirmation' => 'new-secret',
])
->assertStatus(429)
->assertJsonPath('code', ErrorCode::TooManyRequests->value);
expect(Hash::check('old-secret', (string) $player->fresh()->password_hash))->toBeTrue();
});
test('sso player cannot use native password management', function (): void {
$site = DB::table('admin_sites')->where('is_default', true)->first();
$player = Player::query()->create([
'site_code' => (string) $site->code,
'site_player_id' => 'sso-no-password',
'auth_source' => PlayerAuthSource::MAIN_SITE_SSO,
'funding_mode' => PlayerFundingMode::WALLET,
'username' => 'sso_no_password',
'default_currency' => 'NPR',
'status' => 0,
]);
$this->withHeader('Authorization', 'Bearer dev:'.$player->id)
->putJson('/api/v1/player/password', [
'current_password' => 'old-secret',
'password' => 'new-secret',
'password_confirmation' => 'new-secret',
])
->assertStatus(422)
->assertJsonPath('msg', 'Main-site SSO players do not use a lottery password.');
});