UserManagerControllerTest.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  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. * @test
  440. */
  441. public function test_authLog_events_are_listened_by_authLog_listeners()
  442. {
  443. Event::fake();
  444. foreach (config('authentication-log.listeners') as $type => $listenerClass) {
  445. Event::assertListening(
  446. config('authentication-log.events.' . $type),
  447. $listenerClass
  448. );
  449. }
  450. }
  451. /**
  452. * Local feeder because Factory cannot be used here
  453. */
  454. protected function feedAuthenticationLog() : int
  455. {
  456. // Do not change creation order
  457. $this->user->authentications()->create(AuthenticationLogData::beforeLastYear());
  458. $this->user->authentications()->create(AuthenticationLogData::duringLastYear());
  459. $this->user->authentications()->create(AuthenticationLogData::duringLastSixMonth());
  460. $this->user->authentications()->create(AuthenticationLogData::duringLastThreeMonth());
  461. $this->user->authentications()->create(AuthenticationLogData::duringLastMonth());
  462. $this->user->authentications()->create(AuthenticationLogData::noLogin());
  463. $this->user->authentications()->create(AuthenticationLogData::noLogout());
  464. return 7;
  465. }
  466. /**
  467. * @test
  468. */
  469. public function test_authentications_returns_all_entries() : void
  470. {
  471. $created = $this->feedAuthenticationLog();
  472. $this->actingAs($this->admin, 'api-guard')
  473. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications')
  474. ->assertOk()
  475. ->assertJsonCount($created);
  476. }
  477. /**
  478. * @test
  479. */
  480. public function test_authentications_returns_expected_resource() : void
  481. {
  482. $this->user->authentications()->create(AuthenticationLogData::duringLastMonth());
  483. $this->actingAs($this->admin, 'api-guard')
  484. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications')
  485. ->assertJsonStructure([
  486. '*' => [
  487. 'id',
  488. 'ip_address',
  489. 'user_agent',
  490. 'browser',
  491. 'platform',
  492. 'device',
  493. 'login_at',
  494. 'logout_at',
  495. 'login_successful',
  496. 'duration',
  497. ],
  498. ]);
  499. }
  500. /**
  501. * @test
  502. */
  503. public function test_authentications_returns_no_login_entry() : void
  504. {
  505. $this->user->authentications()->create(AuthenticationLogData::noLogin());
  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. 'login_at' => null,
  511. ]);
  512. }
  513. /**
  514. * @test
  515. */
  516. public function test_authentications_returns_no_logout_entry() : void
  517. {
  518. $this->user->authentications()->create(AuthenticationLogData::noLogout());
  519. $this->actingAs($this->admin, 'api-guard')
  520. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=1')
  521. ->assertJsonCount(1)
  522. ->assertJsonFragment([
  523. 'logout_at' => null,
  524. ]);
  525. }
  526. /**
  527. * @test
  528. */
  529. public function test_authentications_returns_failed_entry() : void
  530. {
  531. $this->user->authentications()->create(AuthenticationLogData::failedLogin());
  532. $expected = Carbon::parse(AuthenticationLogData::failedLogin()['login_at'])->toDayDateTimeString();
  533. $this->actingAs($this->admin, 'api-guard')
  534. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=1')
  535. ->assertJsonCount(1)
  536. ->assertJsonFragment([
  537. 'login_at' => $expected,
  538. 'login_successful' => false,
  539. ]);
  540. }
  541. /**
  542. * @test
  543. */
  544. public function test_authentications_returns_last_month_entries() : void
  545. {
  546. $this->feedAuthenticationLog();
  547. $expected = Carbon::parse(AuthenticationLogData::duringLastMonth()['login_at'])->toDayDateTimeString();
  548. $this->actingAs($this->admin, 'api-guard')
  549. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=1')
  550. ->assertJsonCount(3)
  551. ->assertJsonFragment([
  552. 'login_at' => $expected,
  553. ]);
  554. }
  555. /**
  556. * @test
  557. */
  558. public function test_authentications_returns_last_three_months_entries() : void
  559. {
  560. $this->feedAuthenticationLog();
  561. $expectedOneMonth = Carbon::parse(AuthenticationLogData::duringLastMonth()['login_at'])->toDayDateTimeString();
  562. $expectedThreeMonth = Carbon::parse(AuthenticationLogData::duringLastThreeMonth()['login_at'])->toDayDateTimeString();
  563. $this->actingAs($this->admin, 'api-guard')
  564. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=3')
  565. ->assertJsonCount(4)
  566. ->assertJsonFragment([
  567. 'login_at' => $expectedOneMonth,
  568. ])
  569. ->assertJsonFragment([
  570. 'login_at' => $expectedThreeMonth,
  571. ]);
  572. }
  573. /**
  574. * @test
  575. */
  576. public function test_authentications_returns_last_six_months_entries() : void
  577. {
  578. $this->feedAuthenticationLog();
  579. $expectedOneMonth = Carbon::parse(AuthenticationLogData::duringLastMonth()['login_at'])->toDayDateTimeString();
  580. $expectedThreeMonth = Carbon::parse(AuthenticationLogData::duringLastThreeMonth()['login_at'])->toDayDateTimeString();
  581. $expectedSixMonth = Carbon::parse(AuthenticationLogData::duringLastSixMonth()['login_at'])->toDayDateTimeString();
  582. $this->actingAs($this->admin, 'api-guard')
  583. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=6')
  584. ->assertJsonCount(5)
  585. ->assertJsonFragment([
  586. 'login_at' => $expectedOneMonth,
  587. ])
  588. ->assertJsonFragment([
  589. 'login_at' => $expectedThreeMonth,
  590. ])
  591. ->assertJsonFragment([
  592. 'login_at' => $expectedSixMonth,
  593. ]);
  594. }
  595. /**
  596. * @test
  597. */
  598. public function test_authentications_returns_last_year_entries() : void
  599. {
  600. $this->feedAuthenticationLog();
  601. $expectedOneMonth = Carbon::parse(AuthenticationLogData::duringLastMonth()['login_at'])->toDayDateTimeString();
  602. $expectedThreeMonth = Carbon::parse(AuthenticationLogData::duringLastThreeMonth()['login_at'])->toDayDateTimeString();
  603. $expectedSixMonth = Carbon::parse(AuthenticationLogData::duringLastSixMonth()['login_at'])->toDayDateTimeString();
  604. $expectedYear = Carbon::parse(AuthenticationLogData::duringLastYear()['login_at'])->toDayDateTimeString();
  605. $this->actingAs($this->admin, 'api-guard')
  606. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=12')
  607. ->assertJsonCount(6)
  608. ->assertJsonFragment([
  609. 'login_at' => $expectedOneMonth,
  610. ])
  611. ->assertJsonFragment([
  612. 'login_at' => $expectedThreeMonth,
  613. ])
  614. ->assertJsonFragment([
  615. 'login_at' => $expectedSixMonth,
  616. ])
  617. ->assertJsonFragment([
  618. 'login_at' => $expectedYear,
  619. ]);
  620. }
  621. /**
  622. * @test
  623. */
  624. #[DataProvider('LimitProvider')]
  625. public function test_authentications_returns_limited_entries($limit) : void
  626. {
  627. $this->feedAuthenticationLog();
  628. $this->actingAs($this->admin, 'api-guard')
  629. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?limit=' . $limit)
  630. ->assertOk()
  631. ->assertJsonCount($limit);
  632. }
  633. /**
  634. * Provide various limit
  635. */
  636. public static function LimitProvider()
  637. {
  638. return [
  639. 'limited to 1' => [1],
  640. 'limited to 2' => [2],
  641. 'limited to 3' => [3],
  642. ];
  643. }
  644. /**
  645. * @test
  646. */
  647. public function test_authentications_returns_expected_ip_and_useragent_chunks() : void
  648. {
  649. $this->user->authentications()->create([
  650. 'ip_address' => '127.0.0.1',
  651. 'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0',
  652. 'login_at' => now(),
  653. 'login_successful' => true,
  654. 'logout_at' => null,
  655. 'location' => null,
  656. ]);
  657. $this->actingAs($this->admin, 'api-guard')
  658. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=1')
  659. ->assertJsonFragment([
  660. 'ip_address' => '127.0.0.1',
  661. 'browser' => 'Firefox',
  662. 'platform' => 'Windows',
  663. 'device' => 'desktop',
  664. ]);
  665. }
  666. /**
  667. * @test
  668. */
  669. #[DataProvider('invalidQueryParameterProvider')]
  670. public function test_authentications_with_invalid_limit_returns_validation_error($limit) : void
  671. {
  672. $this->actingAs($this->admin, 'api-guard')
  673. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?limit=' . $limit)
  674. ->assertStatus(422);
  675. }
  676. /**
  677. * @test
  678. */
  679. #[DataProvider('invalidQueryParameterProvider')]
  680. public function test_authentications_with_invalid_period_returns_validation_error($period) : void
  681. {
  682. $this->actingAs($this->admin, 'api-guard')
  683. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=' . $period)
  684. ->assertStatus(422);
  685. }
  686. /**
  687. * Provide various invalid value to test query parameter
  688. */
  689. public static function invalidQueryParameterProvider()
  690. {
  691. return [
  692. 'empty' => [''],
  693. 'null' => ['null'],
  694. 'boolean' => ['true'],
  695. 'string' => ['string'],
  696. 'array' => ['[]'],
  697. ];
  698. }
  699. }