UserManagerControllerTest.php 28 KB

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