UserManagerControllerTest.php 31 KB

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