UserManagerControllerTest.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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. public 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. $this->assertEquals($response->getData()[0]->id, $this->user->id);
  500. }
  501. #[Test]
  502. public function test_authentications_returns_expected_resource() : void
  503. {
  504. AuthLog::factory()->for($this->user, 'authenticatable')->create();
  505. $this->actingAs($this->admin, 'api-guard')
  506. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications')
  507. ->assertJsonStructure([
  508. '*' => [
  509. 'id',
  510. 'ip_address',
  511. 'user_agent',
  512. 'browser',
  513. 'platform',
  514. 'device',
  515. 'login_at',
  516. 'logout_at',
  517. 'login_successful',
  518. 'duration',
  519. 'login_method',
  520. ],
  521. ]);
  522. }
  523. #[Test]
  524. public function test_authentications_returns_resource_with_timezoned_dates() : void
  525. {
  526. $timezone = 'Europe/Paris';
  527. $this->admin['preferences->timezone'] = $timezone;
  528. $this->admin->save();
  529. $now = now();
  530. $timezonedNow = now($timezone);
  531. AuthLog::factory()->for($this->user, 'authenticatable')->create([
  532. 'login_at' => $now,
  533. 'logout_at' => $now,
  534. ]);
  535. $response = $this->actingAs($this->admin, 'api-guard')
  536. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications');
  537. $login_at = Carbon::parse($response->getData()[0]->login_at);
  538. $logout_at = Carbon::parse($response->getData()[0]->logout_at);
  539. $this->assertTrue($login_at->isSameHour($timezonedNow));
  540. $this->assertTrue($login_at->isSameMinute($timezonedNow));
  541. $this->assertTrue($logout_at->isSameHour($timezonedNow));
  542. $this->assertTrue($logout_at->isSameMinute($timezonedNow));
  543. }
  544. #[Test]
  545. public function test_authentications_returns_loginless_entries() : void
  546. {
  547. $this->logUserOut();
  548. $this->actingAs($this->admin, 'api-guard')
  549. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications')
  550. ->assertJsonCount(1)
  551. ->assertJsonFragment([
  552. 'login_at' => null,
  553. ]);
  554. }
  555. #[Test]
  556. public function test_authentications_returns_logoutless_entries() : void
  557. {
  558. $this->logUserIn();
  559. $this->actingAs($this->admin, 'api-guard')
  560. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications')
  561. ->assertJsonCount(1)
  562. ->assertJsonFragment([
  563. 'logout_at' => null,
  564. ]);
  565. }
  566. #[Test]
  567. public function test_authentications_returns_failed_entry() : void
  568. {
  569. $this->json('POST', '/user/login', [
  570. 'email' => $this->user->email,
  571. 'password' => 'wrong_password',
  572. ]);
  573. $this->actingAs($this->admin, 'api-guard')
  574. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=1')
  575. ->assertJsonCount(1)
  576. ->assertJsonFragment([
  577. 'login_successful' => false,
  578. ]);
  579. }
  580. #[Test]
  581. public function test_authentications_returns_last_month_entries() : void
  582. {
  583. $this->travel(-2)->months();
  584. $this->logUserInAndOut();
  585. $this->travelBack();
  586. $this->logUserIn();
  587. $response = $this->actingAs($this->admin, 'api-guard')
  588. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=1')
  589. ->assertJsonCount(1);
  590. $this->assertTrue(Carbon::parse($response->getData()[0]->login_at)->isSameDay(now()));
  591. }
  592. #[Test]
  593. public function test_authentications_returns_last_three_months_entries() : void
  594. {
  595. $this->travel(-100)->days();
  596. $this->logUserInAndOut();
  597. $this->travelBack();
  598. $this->travel(-80)->days();
  599. $this->logUserIn();
  600. $this->travelBack();
  601. $response = $this->actingAs($this->admin, 'api-guard')
  602. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=3')
  603. ->assertJsonCount(1);
  604. $this->assertTrue(Carbon::parse($response->getData()[0]->login_at)->isSameDay(now()->subDays(80)));
  605. }
  606. #[Test]
  607. public function test_authentications_returns_last_six_months_entries() : void
  608. {
  609. $this->travel(-7)->months();
  610. $this->logUserInAndOut();
  611. $this->travelBack();
  612. $this->travel(-5)->months();
  613. $this->logUserIn();
  614. $this->travelBack();
  615. $response = $this->actingAs($this->admin, 'api-guard')
  616. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=6')
  617. ->assertJsonCount(1);
  618. $this->assertTrue(Carbon::parse($response->getData()[0]->login_at)->isSameDay(now()->subMonths(5)));
  619. }
  620. #[Test]
  621. public function test_authentications_returns_last_year_entries() : void
  622. {
  623. $this->travel(-13)->months();
  624. $this->logUserInAndOut();
  625. $this->travelBack();
  626. $this->travel(-11)->months();
  627. $this->logUserIn();
  628. $this->travelBack();
  629. $response = $this->actingAs($this->admin, 'api-guard')
  630. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=12')
  631. ->assertJsonCount(1);
  632. $this->assertTrue(Carbon::parse($response->getData()[0]->login_at)->isSameDay(now()->subMonths(11)));
  633. }
  634. #[Test]
  635. #[DataProvider('LimitProvider')]
  636. public function test_authentications_returns_limited_entries($limit) : void
  637. {
  638. AuthLog::factory()->for($this->user, 'authenticatable')->duringLastYear()->create();
  639. AuthLog::factory()->for($this->user, 'authenticatable')->duringLastSixMonth()->create();
  640. AuthLog::factory()->for($this->user, 'authenticatable')->duringLastThreeMonth()->create();
  641. AuthLog::factory()->for($this->user, 'authenticatable')->duringLastMonth()->create();
  642. $this->actingAs($this->admin, 'api-guard')
  643. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?limit=' . $limit)
  644. ->assertOk()
  645. ->assertJsonCount($limit);
  646. }
  647. /**
  648. * Provide various limits
  649. */
  650. public static function LimitProvider()
  651. {
  652. return [
  653. 'limited to 1' => [1],
  654. 'limited to 2' => [2],
  655. 'limited to 3' => [3],
  656. 'limited to 4' => [4],
  657. ];
  658. }
  659. #[Test]
  660. public function test_authentications_returns_expected_ip_and_useragent_chunks() : void
  661. {
  662. AuthLog::factory()->for($this->user, 'authenticatable')->create([
  663. 'ip_address' => '127.0.0.1',
  664. 'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0',
  665. ]);
  666. $this->actingAs($this->admin, 'api-guard')
  667. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=1')
  668. ->assertJsonFragment([
  669. 'ip_address' => '127.0.0.1',
  670. 'browser' => 'Firefox',
  671. 'platform' => 'Windows',
  672. 'device' => 'desktop',
  673. ]);
  674. }
  675. #[Test]
  676. #[DataProvider('invalidQueryParameterProvider')]
  677. public function test_authentications_with_invalid_limit_returns_validation_error($limit) : void
  678. {
  679. $this->actingAs($this->admin, 'api-guard')
  680. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?limit=' . $limit)
  681. ->assertInvalid(['limit']);
  682. }
  683. #[Test]
  684. #[DataProvider('invalidQueryParameterProvider')]
  685. public function test_authentications_with_invalid_period_returns_validation_error($period) : void
  686. {
  687. $this->actingAs($this->admin, 'api-guard')
  688. ->json('GET', '/api/v1/users/' . $this->user->id . '/authentications?period=' . $period)
  689. ->assertInvalid(['period']);
  690. }
  691. /**
  692. * Provide various invalid value to test query parameter
  693. */
  694. public static function invalidQueryParameterProvider()
  695. {
  696. return [
  697. 'empty' => [''],
  698. 'null' => ['null'],
  699. 'boolean' => ['true'],
  700. 'string' => ['string'],
  701. 'array' => ['[]'],
  702. ];
  703. }
  704. /**
  705. * Makes a request to login the user in
  706. */
  707. protected function logUserIn() : void
  708. {
  709. $this->json('POST', '/user/login', [
  710. 'email' => $this->user->email,
  711. 'password' => self::PASSWORD,
  712. ]);
  713. }
  714. /**
  715. * Makes a request to login the user out
  716. */
  717. protected function logUserOut() : void
  718. {
  719. $this->actingAs($this->user, 'web-guard')
  720. ->json('GET', '/user/logout');
  721. }
  722. /**
  723. * Makes a request to login the user out
  724. */
  725. protected function logUserInAndOut() : void
  726. {
  727. $this->logUserIn();
  728. $this->logUserOut();
  729. }
  730. }