UserManagerControllerTest.php 29 KB

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