UserManagerControllerTest.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  1. <?php
  2. namespace Tests\Api\v1\Controllers;
  3. use App\Api\v1\Controllers\UserManagerController;
  4. use App\Api\v1\Resources\UserManagerResource;
  5. use App\Models\User;
  6. use App\Policies\UserPolicy;
  7. use Database\Factories\UserFactory;
  8. use Illuminate\Auth\Notifications\ResetPassword;
  9. use Illuminate\Http\Request;
  10. use Illuminate\Support\Arr;
  11. use Illuminate\Support\Carbon;
  12. use Illuminate\Support\Facades\DB;
  13. use Illuminate\Support\Facades\Hash;
  14. use Illuminate\Support\Facades\Notification;
  15. use Illuminate\Support\Facades\Password;
  16. use Illuminate\Support\Facades\Route;
  17. use Illuminate\Support\Str;
  18. use Laravel\Passport\TokenRepository;
  19. use Mockery\MockInterface;
  20. use PHPUnit\Framework\Attributes\CoversClass;
  21. use PHPUnit\Framework\Attributes\DataProvider;
  22. use Tests\Data\AuthenticationLogData;
  23. use Tests\FeatureTestCase;
  24. #[CoversClass(UserManagerController::class)]
  25. #[CoversClass(UserManagerResource::class)]
  26. #[CoversClass(UserPolicy::class)]
  27. #[CoversClass(User::class)]
  28. class UserManagerControllerTest extends FeatureTestCase
  29. {
  30. /**
  31. * @var \App\Models\User|\Illuminate\Contracts\Auth\Authenticatable
  32. */
  33. protected $admin;
  34. protected $user;
  35. protected $anotherUser;
  36. private const USERNAME = 'john doe';
  37. private const EMAIL = 'johndoe@example.org';
  38. private const PASSWORD = 'password';
  39. /**
  40. * @test
  41. */
  42. public function setUp() : void
  43. {
  44. parent::setUp();
  45. $this->admin = User::factory()->administrator()->create();
  46. $this->user = User::factory()->create();
  47. $this->anotherUser = User::factory()->create();
  48. }
  49. /**
  50. * @test
  51. */
  52. public function test_all_controller_routes_are_protected_by_admin_middleware()
  53. {
  54. $routes = Route::getRoutes()->getRoutes();
  55. $controllerRoutes = Arr::where($routes, function (\Illuminate\Routing\Route $route, int $key) {
  56. if (Str::startsWith($route->getActionName(), UserManagerController::class)) {
  57. return $route;
  58. }
  59. });
  60. foreach ($controllerRoutes as $controllerRoute) {
  61. $this->assertContains('admin', $controllerRoute->middleware());
  62. }
  63. }
  64. /**
  65. * @test
  66. */
  67. public function test_index_returns_all_users()
  68. {
  69. $this->actingAs($this->admin, 'api-guard')
  70. ->json('GET', '/api/v1/users')
  71. ->assertOk()
  72. ->assertJsonCount(3)
  73. ->assertJsonFragment([
  74. 'email' => $this->admin->email,
  75. ])
  76. ->assertJsonFragment([
  77. 'email' => $this->user->email,
  78. ])
  79. ->assertJsonFragment([
  80. 'email' => $this->anotherUser->email,
  81. ]);
  82. }
  83. /**
  84. * @test
  85. */
  86. public function test_index_succeeds_and_returns_UserManagerResource() : void
  87. {
  88. $path = '/api/v1/users';
  89. $resources = UserManagerResource::collection(User::all());
  90. $request = Request::create($path, 'GET');
  91. $this->actingAs($this->admin, 'api-guard')
  92. ->json('GET', $path)
  93. ->assertExactJson($resources->response($request)->getData(true));
  94. }
  95. /**
  96. * @test
  97. */
  98. public function test_show_returns_the_correct_user()
  99. {
  100. $this->actingAs($this->admin, 'api-guard')
  101. ->json('GET', '/api/v1/users/' . $this->user->id)
  102. ->assertJsonFragment([
  103. 'email' => $this->user->email,
  104. ]);
  105. }
  106. /**
  107. * @test
  108. */
  109. public function test_show_returns_UserManagerResource() : void
  110. {
  111. $path = '/api/v1/users/' . $this->user->id;
  112. $resources = UserManagerResource::make($this->user);
  113. $request = Request::create($path, 'GET');
  114. $this->actingAs($this->admin, 'api-guard')
  115. ->json('GET', $path)
  116. ->assertExactJson($resources->response($request)->getData(true));
  117. }
  118. /**
  119. * @test
  120. */
  121. public function test_resetPassword_resets_password_and_sends_password_reset_to_user()
  122. {
  123. Notification::fake();
  124. DB::table(config('auth.passwords.users.table'))->delete();
  125. $user = User::factory()->create();
  126. $oldPassword = $user->password;
  127. $this->actingAs($this->admin, 'api-guard')
  128. ->json('PATCH', '/api/v1/users/' . $user->id . '/password/reset')
  129. ->assertOk();
  130. $user->refresh();
  131. $this->assertNotEquals($oldPassword, $user->password);
  132. $resetToken = DB::table(config('auth.passwords.users.table'))->first();
  133. $this->assertNotNull($resetToken);
  134. Notification::assertSentTo($user, ResetPassword::class, function ($notification, $channels) use ($resetToken) {
  135. return Hash::check($notification->token, $resetToken->token) === true;
  136. });
  137. }
  138. /**
  139. * @test
  140. */
  141. public function test_resetPassword_returns_UserManagerResource()
  142. {
  143. Notification::fake();
  144. $user = User::factory()->create();
  145. $path = '/api/v1/users/' . $user->id . '/password/reset';
  146. $request = Request::create($path, 'PATCH');
  147. $response = $this->actingAs($this->admin, 'api-guard')
  148. ->json('PATCH', $path);
  149. $resources = UserManagerResource::make($user);
  150. $response->assertExactJson($resources->response($request)->getData(true));
  151. }
  152. /**
  153. * @test
  154. */
  155. public function test_resetPassword_does_not_notify_when_reset_failed_and_returns_error()
  156. {
  157. Notification::fake();
  158. $broker = $this->partialMock(\Illuminate\Auth\Passwords\PasswordBroker::class, function (MockInterface $broker) {
  159. $broker->shouldReceive('createToken')
  160. ->andReturn('fakeValue');
  161. $broker->shouldReceive('reset')
  162. ->andReturn(false);
  163. });
  164. Password::shouldReceive('broker')->andReturn($broker);
  165. $user = User::factory()->create();
  166. $this->actingAs($this->admin, 'api-guard')
  167. ->json('PATCH', '/api/v1/users/' . $user->id . '/password/reset')
  168. ->assertStatus(400)
  169. ->assertJsonStructure([
  170. 'message',
  171. 'reason',
  172. ]);
  173. Notification::assertNothingSent();
  174. }
  175. /**
  176. * @test
  177. */
  178. public function test_resetPassword_returns_error_when_notify_send_failed()
  179. {
  180. Notification::fake();
  181. $broker = $this->partialMock(\Illuminate\Auth\Passwords\PasswordBroker::class, function (MockInterface $broker) {
  182. $broker->shouldReceive('createToken')
  183. ->andReturn('fakeValue');
  184. $broker->shouldReceive('reset')
  185. ->andReturn(Password::PASSWORD_RESET);
  186. $broker->shouldReceive('sendResetLink')
  187. ->andReturn('badValue');
  188. });
  189. Password::shouldReceive('broker')->andReturn($broker);
  190. $user = User::factory()->create();
  191. $this->actingAs($this->admin, 'api-guard')
  192. ->json('PATCH', '/api/v1/users/' . $user->id . '/password/reset')
  193. ->assertStatus(400)
  194. ->assertJsonStructure([
  195. 'message',
  196. 'reason',
  197. ]);
  198. Notification::assertNothingSent();
  199. }
  200. /**
  201. * @test
  202. */
  203. public function test_store_creates_the_user_and_returns_success()
  204. {
  205. $this->actingAs($this->admin, 'api-guard')
  206. ->json('POST', '/api/v1/users', [
  207. 'name' => self::USERNAME,
  208. 'email' => self::EMAIL,
  209. 'password' => self::PASSWORD,
  210. 'password_confirmation' => self::PASSWORD,
  211. 'is_admin' => false,
  212. ])
  213. ->assertCreated();
  214. $this->assertDatabaseHas('users', [
  215. 'name' => self::USERNAME,
  216. 'email' => self::EMAIL,
  217. ]);
  218. }
  219. /**
  220. * @test
  221. */
  222. public function test_store_returns_UserManagerResource_of_created_user() : void
  223. {
  224. $path = '/api/v1/users';
  225. $userDefinition = (new UserFactory)->definition();
  226. $userDefinition['password_confirmation'] = $userDefinition['password'];
  227. $request = Request::create($path, 'POST');
  228. $response = $this->actingAs($this->admin, 'api-guard')
  229. ->json('POST', $path, $userDefinition)
  230. ->assertCreated();
  231. $user = User::where('email', $userDefinition['email'])->first();
  232. $resource = UserManagerResource::make($user);
  233. $response->assertExactJson($resource->response($request)->getData(true));
  234. }
  235. /**
  236. * @test
  237. */
  238. public function test_store_returns_UserManagerResource_of_created_admin() : void
  239. {
  240. $path = '/api/v1/users';
  241. $userDefinition = (new UserFactory)->definition();
  242. $userDefinition['is_admin'] = true;
  243. $userDefinition['password_confirmation'] = $userDefinition['password'];
  244. $request = Request::create($path, 'POST');
  245. $response = $this->actingAs($this->admin, 'api-guard')
  246. ->json('POST', $path, $userDefinition)
  247. ->assertCreated();
  248. $user = User::where('email', $userDefinition['email'])->first();
  249. $resource = UserManagerResource::make($user);
  250. $response->assertExactJson($resource->response($request)->getData(true));
  251. }
  252. /**
  253. * @test
  254. */
  255. public function test_revokePATs_flushes_pats()
  256. {
  257. $tokenRepository = app(TokenRepository::class);
  258. $this->actingAs($this->user, 'api-guard')
  259. ->json('POST', '/oauth/personal-access-tokens', [
  260. 'name' => 'RandomTokenName',
  261. ])
  262. ->assertOk();
  263. $this->actingAs($this->admin, 'api-guard')
  264. ->json('DELETE', '/api/v1/users/' . $this->user->id . '/pats');
  265. $tokens = $tokenRepository->forUser($this->user->getAuthIdentifier());
  266. $tokens = $tokens->load('client')->filter(function ($token) {
  267. return $token->client->personal_access_client && ! $token->revoked;
  268. });
  269. $this->assertCount(0, $tokens);
  270. }
  271. /**
  272. * @test
  273. */
  274. public function test_revokePATs_returns_no_content()
  275. {
  276. $this->actingAs($this->admin, 'api-guard')
  277. ->json('DELETE', '/api/v1/users/' . $this->user->id . '/pats')
  278. ->assertNoContent();
  279. }
  280. /**
  281. * @test
  282. */
  283. public function test_revokePATs_always_returns_no_content()
  284. {
  285. // a fresh user has no token
  286. $user = User::factory()->create();
  287. $this->actingAs($this->admin, 'api-guard')
  288. ->json('DELETE', '/api/v1/users/' . $user->id . '/pats')
  289. ->assertNoContent();
  290. }
  291. /**
  292. * @test
  293. */
  294. public function test_revokeWebauthnCredentials_flushes_credentials()
  295. {
  296. DB::table('webauthn_credentials')->insert([
  297. 'id' => '-VOLFKPY-_FuMI_sJ7gMllK76L3VoRUINj6lL_Z3qDg',
  298. 'authenticatable_type' => \App\Models\User::class,
  299. 'authenticatable_id' => $this->user->id,
  300. 'user_id' => 'e8af6f703f8042aa91c30cf72289aa07',
  301. 'counter' => 0,
  302. 'rp_id' => 'http://localhost',
  303. 'origin' => 'http://localhost',
  304. 'aaguid' => '00000000-0000-0000-0000-000000000000',
  305. 'attestation_format' => 'none',
  306. 'public_key' => 'eyJpdiI6Imp0U0NVeFNNbW45KzEvMXpad2p2SUE9PSIsInZhbHVlIjoic0VxZ2I1WnlHM2lJakhkWHVkK2kzMWtibk1IN2ZlaExGT01qOElXMDdRTjhnVlR0TDgwOHk1S0xQUy9BQ1JCWHRLNzRtenNsMml1dVQydWtERjFEU0h0bkJGT2RwUXE1M1JCcVpablE2Y2VGV2YvVEE2RGFIRUE5L0x1K0JIQXhLVE1aNVNmN3AxeHdjRUo2V0hwREZSRTJYaThNNnB1VnozMlVXZEVPajhBL3d3ODlkTVN3bW54RTEwSG0ybzRQZFFNNEFrVytUYThub2IvMFRtUlBZamoyZElWKzR1bStZQ1IwU3FXbkYvSm1FU2FlMTFXYUo0SG9kc1BDME9CNUNKeE9IelE5d2dmNFNJRXBKNUdlVzJ3VHUrQWJZRFluK0hib0xvVTdWQ0ZISjZmOWF3by83aVJES1dxbU9Zd1lhRTlLVmhZSUdlWmlBOUFtcTM2ZVBaRWNKNEFSQUhENk5EaC9hN3REdnVFbm16WkRxekRWOXd4cVcvZFdKa2tlWWJqZWlmZnZLS0F1VEVCZEZQcXJkTExiNWRyQmxsZWtaSDRlT3VVS0ZBSXFBRG1JMjRUMnBKRXZxOUFUa2xxMjg2TEplUzdscVo2UytoVU5SdXk1OE1lcFN6aU05ZkVXTkdIM2tKM3Q5bmx1TGtYb1F5bGxxQVR3K3BVUVlia1VybDFKRm9lZDViNzYraGJRdmtUb2FNTEVGZmZYZ3lYRDRiOUVjRnJpcTVvWVExOHJHSTJpMnVBZ3E0TmljbUlKUUtXY2lSWDh1dE5MVDNRUzVRSkQrTjVJUU8rSGhpeFhRRjJvSEdQYjBoVT0iLCJtYWMiOiI5MTdmNWRkZGE5OTEwNzQ3MjhkYWVhYjRlNjk0MWZlMmI5OTQ4YzlmZWI1M2I4OGVkMjE1MjMxNjUwOWRmZTU2IiwidGFnIjoiIn0=',
  307. 'updated_at' => now(),
  308. 'created_at' => now(),
  309. ]);
  310. $this->actingAs($this->admin, 'api-guard')
  311. ->json('DELETE', '/api/v1/users/' . $this->user->id . '/credentials');
  312. $this->assertDatabaseMissing('webauthn_credentials', [
  313. 'authenticatable_id' => $this->user->id,
  314. ]);
  315. }
  316. /**
  317. * @test
  318. */
  319. public function test_revokeWebauthnCredentials_returns_no_content()
  320. {
  321. DB::table('webauthn_credentials')->insert([
  322. 'id' => '-VOLFKPY-_FuMI_sJ7gMllK76L3VoRUINj6lL_Z3qDg',
  323. 'authenticatable_type' => \App\Models\User::class,
  324. 'authenticatable_id' => $this->user->id,
  325. 'user_id' => 'e8af6f703f8042aa91c30cf72289aa07',
  326. 'counter' => 0,
  327. 'rp_id' => 'http://localhost',
  328. 'origin' => 'http://localhost',
  329. 'aaguid' => '00000000-0000-0000-0000-000000000000',
  330. 'attestation_format' => 'none',
  331. 'public_key' => 'eyJpdiI6Imp0U0NVeFNNbW45KzEvMXpad2p2SUE9PSIsInZhbHVlIjoic0VxZ2I1WnlHM2lJakhkWHVkK2kzMWtibk1IN2ZlaExGT01qOElXMDdRTjhnVlR0TDgwOHk1S0xQUy9BQ1JCWHRLNzRtenNsMml1dVQydWtERjFEU0h0bkJGT2RwUXE1M1JCcVpablE2Y2VGV2YvVEE2RGFIRUE5L0x1K0JIQXhLVE1aNVNmN3AxeHdjRUo2V0hwREZSRTJYaThNNnB1VnozMlVXZEVPajhBL3d3ODlkTVN3bW54RTEwSG0ybzRQZFFNNEFrVytUYThub2IvMFRtUlBZamoyZElWKzR1bStZQ1IwU3FXbkYvSm1FU2FlMTFXYUo0SG9kc1BDME9CNUNKeE9IelE5d2dmNFNJRXBKNUdlVzJ3VHUrQWJZRFluK0hib0xvVTdWQ0ZISjZmOWF3by83aVJES1dxbU9Zd1lhRTlLVmhZSUdlWmlBOUFtcTM2ZVBaRWNKNEFSQUhENk5EaC9hN3REdnVFbm16WkRxekRWOXd4cVcvZFdKa2tlWWJqZWlmZnZLS0F1VEVCZEZQcXJkTExiNWRyQmxsZWtaSDRlT3VVS0ZBSXFBRG1JMjRUMnBKRXZxOUFUa2xxMjg2TEplUzdscVo2UytoVU5SdXk1OE1lcFN6aU05ZkVXTkdIM2tKM3Q5bmx1TGtYb1F5bGxxQVR3K3BVUVlia1VybDFKRm9lZDViNzYraGJRdmtUb2FNTEVGZmZYZ3lYRDRiOUVjRnJpcTVvWVExOHJHSTJpMnVBZ3E0TmljbUlKUUtXY2lSWDh1dE5MVDNRUzVRSkQrTjVJUU8rSGhpeFhRRjJvSEdQYjBoVT0iLCJtYWMiOiI5MTdmNWRkZGE5OTEwNzQ3MjhkYWVhYjRlNjk0MWZlMmI5OTQ4YzlmZWI1M2I4OGVkMjE1MjMxNjUwOWRmZTU2IiwidGFnIjoiIn0=',
  332. 'updated_at' => now(),
  333. 'created_at' => now(),
  334. ]);
  335. $this->actingAs($this->admin, 'api-guard')
  336. ->json('DELETE', '/api/v1/users/' . $this->user->id . '/credentials')
  337. ->assertNoContent();
  338. }
  339. /**
  340. * @test
  341. */
  342. public function test_revokeWebauthnCredentials_always_returns_no_content()
  343. {
  344. DB::table('webauthn_credentials')->delete();
  345. $this->actingAs($this->admin, 'api-guard')
  346. ->json('DELETE', '/api/v1/users/' . $this->user->id . '/credentials')
  347. ->assertNoContent();
  348. }
  349. /**
  350. * @test
  351. */
  352. public function test_revokeWebauthnCredentials_resets_useWebauthnOnly_user_preference()
  353. {
  354. $this->user['preferences->useWebauthnOnly'] = true;
  355. $this->user->save();
  356. $this->actingAs($this->admin, 'api-guard')
  357. ->json('DELETE', '/api/v1/users/' . $this->user->id . '/credentials')
  358. ->assertNoContent();
  359. $this->user->refresh();
  360. $this->assertFalse($this->user->preferences['useWebauthnOnly']);
  361. }
  362. /**
  363. * @test
  364. */
  365. public function test_destroy_returns_no_content()
  366. {
  367. $user = User::factory()->create();
  368. $this->actingAs($this->admin, 'api-guard')
  369. ->json('DELETE', '/api/v1/users/' . $user->id)
  370. ->assertNoContent();
  371. }
  372. /**
  373. * @test
  374. */
  375. public function test_destroy_the_only_admin_returns_forbidden()
  376. {
  377. $this->actingAs($this->admin, 'api-guard')
  378. ->json('DELETE', '/api/v1/users/' . $this->admin->id)
  379. ->assertForbidden();
  380. }
  381. /**
  382. * @test
  383. */
  384. public function test_promote_changes_admin_status() : void
  385. {
  386. $this->actingAs($this->admin, 'api-guard')
  387. ->json('PATCH', '/api/v1/users/' . $this->user->id . '/promote', [
  388. 'is_admin' => true,
  389. ])
  390. ->assertOk();
  391. $this->user->refresh();
  392. $this->assertTrue($this->user->isAdministrator());
  393. }
  394. /**
  395. * @test
  396. */
  397. public function test_promote_returns_UserManagerResource() : void
  398. {
  399. $path = '/api/v1/users/' . $this->user->id . '/promote';
  400. $request = Request::create($path, 'PUT');
  401. $response = $this->actingAs($this->admin, 'api-guard')
  402. ->json('PATCH', $path, [
  403. 'is_admin' => true,
  404. ]);
  405. $this->user->refresh();
  406. $resources = UserManagerResource::make($this->user);
  407. $response->assertExactJson($resources->response($request)->getData(true));
  408. }
  409. /**
  410. * @test
  411. */
  412. public function test_demote_returns_UserManagerResource() : void
  413. {
  414. $anotherAdmin = User::factory()->administrator()->create();
  415. $path = '/api/v1/users/' . $anotherAdmin->id . '/promote';
  416. $request = Request::create($path, 'PUT');
  417. $response = $this->actingAs($this->admin, 'api-guard')
  418. ->json('PATCH', $path, [
  419. 'is_admin' => false,
  420. ]);
  421. $anotherAdmin->refresh();
  422. $resources = UserManagerResource::make($anotherAdmin);
  423. $response->assertExactJson($resources->response($request)->getData(true));
  424. }
  425. /**
  426. * @test
  427. */
  428. public function test_demote_the_only_admin_returns_forbidden() : void
  429. {
  430. $this->assertTrue(User::admins()->count() == 1);
  431. $this->actingAs($this->admin, 'api-guard')
  432. ->json('PATCH', '/api/v1/users/' . $this->admin->id . '/promote', [
  433. 'is_admin' => false,
  434. ])
  435. ->assertForbidden();
  436. }
  437. protected function feedAuthenticationLog() : int
  438. {
  439. // Do not change creation order
  440. $this->user->authentications()->create(AuthenticationLogData::beforeLastYear());
  441. $this->user->authentications()->create(AuthenticationLogData::duringLastYear());
  442. $this->user->authentications()->create(AuthenticationLogData::duringLastSixMonth());
  443. $this->user->authentications()->create(AuthenticationLogData::duringLastThreeMonth());
  444. $this->user->authentications()->create(AuthenticationLogData::duringLastMonth());
  445. $this->user->authentications()->create(AuthenticationLogData::noLogin());
  446. $this->user->authentications()->create(AuthenticationLogData::noLogout());
  447. return 7;
  448. }
  449. /**
  450. * @test
  451. */
  452. public function test_authentications_returns_all_entries() : void
  453. {
  454. $created = $this->feedAuthenticationLog();
  455. $this->actingAs($this->admin, 'api-guard')
  456. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications')
  457. ->assertOk()
  458. ->assertJsonCount($created);
  459. }
  460. /**
  461. * @test
  462. */
  463. public function test_authentications_returns_expected_resource() : void
  464. {
  465. $this->user->authentications()->create(AuthenticationLogData::duringLastMonth());
  466. $this->actingAs($this->admin, 'api-guard')
  467. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications')
  468. ->assertJsonStructure([
  469. '*' => [
  470. 'id',
  471. 'ip_address',
  472. 'user_agent',
  473. 'browser',
  474. 'platform',
  475. 'device',
  476. 'login_at',
  477. 'logout_at',
  478. 'login_successful',
  479. 'duration',
  480. ]
  481. ]);
  482. }
  483. /**
  484. * @test
  485. */
  486. public function test_authentications_returns_no_login_entry() : void
  487. {
  488. $this->user->authentications()->create(AuthenticationLogData::noLogin());
  489. $this->actingAs($this->admin, 'api-guard')
  490. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=1')
  491. ->assertJsonCount(1)
  492. ->assertJsonFragment([
  493. 'login_at' => null
  494. ]);
  495. }
  496. /**
  497. * @test
  498. */
  499. public function test_authentications_returns_no_logout_entry() : void
  500. {
  501. $this->user->authentications()->create(AuthenticationLogData::noLogout());
  502. $this->actingAs($this->admin, 'api-guard')
  503. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=1')
  504. ->assertJsonCount(1)
  505. ->assertJsonFragment([
  506. 'logout_at' => null
  507. ]);
  508. }
  509. /**
  510. * @test
  511. */
  512. public function test_authentications_returns_failed_entry() : void
  513. {
  514. $this->user->authentications()->create(AuthenticationLogData::failedLogin());
  515. $expected = Carbon::parse(AuthenticationLogData::failedLogin()['login_at'])->toDayDateTimeString();
  516. $this->actingAs($this->admin, 'api-guard')
  517. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=1')
  518. ->assertJsonCount(1)
  519. ->assertJsonFragment([
  520. 'login_at' => $expected,
  521. 'login_successful' => false,
  522. ]);
  523. }
  524. /**
  525. * @test
  526. */
  527. public function test_authentications_returns_last_month_entries() : void
  528. {
  529. $this->feedAuthenticationLog();
  530. $expected = Carbon::parse(AuthenticationLogData::duringLastMonth()['login_at'])->toDayDateTimeString();
  531. $this->actingAs($this->admin, 'api-guard')
  532. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=1')
  533. ->assertJsonCount(3)
  534. ->assertJsonFragment([
  535. 'login_at' => $expected
  536. ]);
  537. }
  538. /**
  539. * @test
  540. */
  541. public function test_authentications_returns_last_three_months_entries() : void
  542. {
  543. $this->feedAuthenticationLog();
  544. $expectedOneMonth = Carbon::parse(AuthenticationLogData::duringLastMonth()['login_at'])->toDayDateTimeString();
  545. $expectedThreeMonth = Carbon::parse(AuthenticationLogData::duringLastThreeMonth()['login_at'])->toDayDateTimeString();
  546. $this->actingAs($this->admin, 'api-guard')
  547. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=3')
  548. ->assertJsonCount(4)
  549. ->assertJsonFragment([
  550. 'login_at' => $expectedOneMonth
  551. ])
  552. ->assertJsonFragment([
  553. 'login_at' => $expectedThreeMonth
  554. ]);
  555. }
  556. /**
  557. * @test
  558. */
  559. public function test_authentications_returns_last_six_months_entries() : void
  560. {
  561. $this->feedAuthenticationLog();
  562. $expectedOneMonth = Carbon::parse(AuthenticationLogData::duringLastMonth()['login_at'])->toDayDateTimeString();
  563. $expectedThreeMonth = Carbon::parse(AuthenticationLogData::duringLastThreeMonth()['login_at'])->toDayDateTimeString();
  564. $expectedSixMonth = Carbon::parse(AuthenticationLogData::duringLastSixMonth()['login_at'])->toDayDateTimeString();
  565. $this->actingAs($this->admin, 'api-guard')
  566. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=6')
  567. ->assertJsonCount(5)
  568. ->assertJsonFragment([
  569. 'login_at' => $expectedOneMonth
  570. ])
  571. ->assertJsonFragment([
  572. 'login_at' => $expectedThreeMonth
  573. ])
  574. ->assertJsonFragment([
  575. 'login_at' => $expectedSixMonth
  576. ]);
  577. }
  578. /**
  579. * @test
  580. */
  581. public function test_authentications_returns_last_year_entries() : void
  582. {
  583. $this->feedAuthenticationLog();
  584. $expectedOneMonth = Carbon::parse(AuthenticationLogData::duringLastMonth()['login_at'])->toDayDateTimeString();
  585. $expectedThreeMonth = Carbon::parse(AuthenticationLogData::duringLastThreeMonth()['login_at'])->toDayDateTimeString();
  586. $expectedSixMonth = Carbon::parse(AuthenticationLogData::duringLastSixMonth()['login_at'])->toDayDateTimeString();
  587. $expectedYear = Carbon::parse(AuthenticationLogData::duringLastYear()['login_at'])->toDayDateTimeString();
  588. $this->actingAs($this->admin, 'api-guard')
  589. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=12')
  590. ->assertJsonCount(6)
  591. ->assertJsonFragment([
  592. 'login_at' => $expectedOneMonth
  593. ])
  594. ->assertJsonFragment([
  595. 'login_at' => $expectedThreeMonth
  596. ])
  597. ->assertJsonFragment([
  598. 'login_at' => $expectedSixMonth
  599. ])
  600. ->assertJsonFragment([
  601. 'login_at' => $expectedYear
  602. ]);
  603. }
  604. /**
  605. * @test
  606. */
  607. #[DataProvider('LimitProvider')]
  608. public function test_authentications_returns_limited_entries($limit) : void
  609. {
  610. $this->feedAuthenticationLog();
  611. $this->actingAs($this->admin, 'api-guard')
  612. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?limit=' . $limit)
  613. ->assertOk()
  614. ->assertJsonCount($limit);
  615. }
  616. /**
  617. * Provide various limit
  618. */
  619. public static function LimitProvider()
  620. {
  621. return [
  622. 'limited to 1' => [1],
  623. 'limited to 2' => [2],
  624. 'limited to 3' => [3],
  625. ];
  626. }
  627. /**
  628. * @test
  629. */
  630. public function test_authentications_returns_expected_ip_and_useragent_chunks() : void
  631. {
  632. $this->user->authentications()->create([
  633. 'ip_address' => '127.0.0.1',
  634. 'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0',
  635. 'login_at' => now(),
  636. 'login_successful' => true,
  637. 'logout_at' => null,
  638. 'location' => null,
  639. ]);
  640. $this->actingAs($this->admin, 'api-guard')
  641. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=1')
  642. ->assertJsonFragment([
  643. 'ip_address' => '127.0.0.1',
  644. 'browser' => 'Firefox',
  645. 'platform' => 'Windows',
  646. 'device' => 'desktop',
  647. ]);
  648. }
  649. /**
  650. * @test
  651. */
  652. #[DataProvider('invalidQueryParameterProvider')]
  653. public function test_authentications_with_invalid_limit_returns_validation_error($limit) : void
  654. {
  655. $this->actingAs($this->admin, 'api-guard')
  656. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?limit=' . $limit)
  657. ->assertStatus(422);
  658. }
  659. /**
  660. * @test
  661. */
  662. #[DataProvider('invalidQueryParameterProvider')]
  663. public function test_authentications_with_invalid_period_returns_validation_error($period) : void
  664. {
  665. $this->actingAs($this->admin, 'api-guard')
  666. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=' . $period)
  667. ->assertStatus(422);
  668. }
  669. /**
  670. * Provide various invalid value to test query parameter
  671. */
  672. public static function invalidQueryParameterProvider()
  673. {
  674. return [
  675. 'empty' => [''],
  676. 'null' => ['null'],
  677. 'boolean' => ['true'],
  678. 'string' => ['string'],
  679. 'array' => ['[]'],
  680. ];
  681. }
  682. }