AccessTokenExpiryTest.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. use App\Models\AccessToken;
  3. use Firebase\JWT\JWT;
  4. use Firebase\JWT\Key;
  5. use Illuminate\Foundation\Testing\RefreshDatabase;
  6. uses(RefreshDatabase::class);
  7. it('signs channel access tokens with an expiry', function () {
  8. $owner = makeStudio('tester');
  9. $channel = makeChannel($owner);
  10. $token = $this->postJson('/api/v2/access-token', [
  11. 'payload' => [[
  12. 'res_type' => 'channel',
  13. 'res_id' => $channel,
  14. 'power' => 'edit',
  15. 'book' => 0,
  16. ]],
  17. ], authHeader($owner))
  18. ->assertOk()
  19. ->assertJsonPath('data.count', 1)
  20. ->json('data.rows.0.token');
  21. $key = AccessToken::where('res_id', $channel)->value('token');
  22. $jwt = JWT::decode($token, new Key($key.$key, 'HS512'));
  23. // 修复前 payload 里没有 exp,签出的 token 永久有效
  24. expect($jwt->exp)->toBeGreaterThan(time());
  25. expect($jwt->exp)->toBeLessThanOrEqual(time() + 60 * 60 * 24 * 7);
  26. expect($jwt->res_id)->toBe($channel);
  27. });
  28. it('returns an empty row set when the user cannot edit the channel', function () {
  29. $owner = makeStudio('owner');
  30. $channel = makeChannel($owner);
  31. $stranger = makeStudio('stranger');
  32. // 无权时该条被静默跳过——客户端必须靠 count 判空,不能当成功
  33. $this->postJson('/api/v2/access-token', [
  34. 'payload' => [[
  35. 'res_type' => 'channel',
  36. 'res_id' => $channel,
  37. 'power' => 'edit',
  38. 'book' => 0,
  39. ]],
  40. ], authHeader($stranger))
  41. ->assertOk()
  42. ->assertJsonPath('data.count', 0);
  43. });