UserManagerControllerTest.php 30 KB

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