UserManagerControllerTest.php 30 KB

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