UserModelTest.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. <?php
  2. namespace Tests\Feature\Models;
  3. use App\Facades\IconStore;
  4. use App\Models\AuthLog;
  5. use App\Models\Group;
  6. use App\Models\TwoFAccount;
  7. use App\Models\User;
  8. use App\Observers\UserObserver;
  9. use Database\Factories\AuthLogFactory;
  10. use Illuminate\Auth\Events\PasswordReset;
  11. use Illuminate\Support\Facades\Artisan;
  12. use Illuminate\Support\Facades\DB;
  13. use Illuminate\Support\Facades\Event;
  14. use Illuminate\Support\Facades\Password;
  15. use Illuminate\Support\Facades\Storage;
  16. use PHPUnit\Framework\Attributes\CoversClass;
  17. use PHPUnit\Framework\Attributes\Test;
  18. use Tests\Data\OtpTestData;
  19. use Tests\FeatureTestCase;
  20. /**
  21. * UserModelTest test class
  22. */
  23. #[CoversClass(User::class)]
  24. #[CoversClass(UserObserver::class)]
  25. class UserModelTest extends FeatureTestCase
  26. {
  27. #[Test]
  28. public function test_admin_scope_returns_only_admin()
  29. {
  30. User::factory()->count(4)->create();
  31. $firstAdmin = User::factory()->administrator()->create([
  32. 'name' => 'first',
  33. ]);
  34. $secondAdmin = User::factory()->administrator()->create([
  35. 'name' => 'secondAdmin',
  36. ]);
  37. $admins = User::admins()->get();
  38. $this->assertCount(2, $admins);
  39. $this->assertEquals($admins[0]->is_admin, true);
  40. $this->assertEquals($admins[1]->is_admin, true);
  41. $this->assertEquals($admins[0]->name, $firstAdmin->name);
  42. $this->assertEquals($admins[1]->name, $secondAdmin->name);
  43. }
  44. #[Test]
  45. public function test_isAdministrator_returns_correct_state()
  46. {
  47. $user = User::factory()->create();
  48. $admin = User::factory()->administrator()->create();
  49. $this->assertEquals($user->isAdministrator(), false);
  50. $this->assertEquals($admin->isAdministrator(), true);
  51. }
  52. #[Test]
  53. public function test_promoteToAdministrator_sets_administrator_status()
  54. {
  55. $user = User::factory()->create();
  56. $user->promoteToAdministrator();
  57. $this->assertEquals($user->isAdministrator(), true);
  58. }
  59. #[Test]
  60. public function test_promoteToAdministrator_demote_administrator_status()
  61. {
  62. $admin = User::factory()->administrator()->create();
  63. // We need another admin to prevent demoting event returning false
  64. // and blocking the demotion
  65. $another_admin = User::factory()->administrator()->create();
  66. $admin->promoteToAdministrator(false);
  67. $admin->save();
  68. $this->assertFalse($admin->isAdministrator());
  69. }
  70. #[Test]
  71. public function test_resetPassword_resets_password_with_success()
  72. {
  73. $user = User::factory()->create();
  74. $oldPassword = $user->password;
  75. $user->resetPassword();
  76. $this->assertNotEquals($user->password, $oldPassword);
  77. }
  78. #[Test]
  79. public function test_resetPassword_dispatch_event()
  80. {
  81. Event::fake();
  82. $user = User::factory()->create();
  83. Event::assertDispatched(
  84. PasswordReset::class,
  85. $user->resetPassword()
  86. );
  87. }
  88. #[Test]
  89. public function test_delete_removes_user_data()
  90. {
  91. Artisan::call('passport:install', [
  92. '--verbose' => 2,
  93. '--no-interaction' => 1,
  94. ]);
  95. $user = User::factory()->create();
  96. TwoFAccount::factory()->for($user)->create();
  97. AuthLog::factory()->for($user, 'authenticatable')->create();
  98. Group::factory()->for($user)->create();
  99. DB::table('webauthn_credentials')->insert([
  100. 'id' => '-VOLFKPY-_FuMI_sJ7gMllK76L3VoRUINj6lL_Z3qDg',
  101. 'authenticatable_type' => \App\Models\User::class,
  102. 'authenticatable_id' => $user->id,
  103. 'user_id' => 'e8af6f703f8042aa91c30cf72289aa07',
  104. 'counter' => 0,
  105. 'rp_id' => 'http://localhost',
  106. 'origin' => 'http://localhost',
  107. 'aaguid' => '00000000-0000-0000-0000-000000000000',
  108. 'attestation_format' => 'none',
  109. 'public_key' => 'eyJpdiI6Imp0U0NVeFNNbW45KzEvMXpad2p2SUE9PSIsInZhbHVlIjoic0VxZ2I1WnlHM2lJakhkWHVkK2kzMWtibk1IN2ZlaExGT01qOElXMDdRTjhnVlR0TDgwOHk1S0xQUy9BQ1JCWHRLNzRtenNsMml1dVQydWtERjFEU0h0bkJGT2RwUXE1M1JCcVpablE2Y2VGV2YvVEE2RGFIRUE5L0x1K0JIQXhLVE1aNVNmN3AxeHdjRUo2V0hwREZSRTJYaThNNnB1VnozMlVXZEVPajhBL3d3ODlkTVN3bW54RTEwSG0ybzRQZFFNNEFrVytUYThub2IvMFRtUlBZamoyZElWKzR1bStZQ1IwU3FXbkYvSm1FU2FlMTFXYUo0SG9kc1BDME9CNUNKeE9IelE5d2dmNFNJRXBKNUdlVzJ3VHUrQWJZRFluK0hib0xvVTdWQ0ZISjZmOWF3by83aVJES1dxbU9Zd1lhRTlLVmhZSUdlWmlBOUFtcTM2ZVBaRWNKNEFSQUhENk5EaC9hN3REdnVFbm16WkRxekRWOXd4cVcvZFdKa2tlWWJqZWlmZnZLS0F1VEVCZEZQcXJkTExiNWRyQmxsZWtaSDRlT3VVS0ZBSXFBRG1JMjRUMnBKRXZxOUFUa2xxMjg2TEplUzdscVo2UytoVU5SdXk1OE1lcFN6aU05ZkVXTkdIM2tKM3Q5bmx1TGtYb1F5bGxxQVR3K3BVUVlia1VybDFKRm9lZDViNzYraGJRdmtUb2FNTEVGZmZYZ3lYRDRiOUVjRnJpcTVvWVExOHJHSTJpMnVBZ3E0TmljbUlKUUtXY2lSWDh1dE5MVDNRUzVRSkQrTjVJUU8rSGhpeFhRRjJvSEdQYjBoVT0iLCJtYWMiOiI5MTdmNWRkZGE5OTEwNzQ3MjhkYWVhYjRlNjk0MWZlMmI5OTQ4YzlmZWI1M2I4OGVkMjE1MjMxNjUwOWRmZTU2IiwidGFnIjoiIn0=',
  110. 'updated_at' => now(),
  111. 'created_at' => now(),
  112. ]);
  113. $user->createToken('myToken', []);
  114. Password::broker('webauthn')->createToken($user);
  115. Password::broker()->createToken($user);
  116. $user->delete();
  117. $this->assertDatabaseMissing('twofaccounts', [
  118. 'user_id' => $user->id,
  119. ]);
  120. $this->assertDatabaseMissing('groups', [
  121. 'user_id' => $user->id,
  122. ]);
  123. $this->assertDatabaseMissing('webauthn_credentials', [
  124. 'authenticatable_id' => $user->id,
  125. ]);
  126. $this->assertDatabaseMissing(config('auth.passwords.webauthn.table'), [
  127. 'email' => $user->email,
  128. ]);
  129. $this->assertDatabaseMissing('oauth_access_tokens', [
  130. 'user_id' => $user->id,
  131. ]);
  132. $this->assertDatabaseMissing(config('auth.passwords.users.table'), [
  133. 'email' => $user->email,
  134. ]);
  135. $this->assertDatabaseMissing('auth_logs', [
  136. 'authenticatable_id' => $user->id,
  137. ]);
  138. }
  139. #[Test]
  140. public function test_delete_flushes_icons_of_user_twofaccounts()
  141. {
  142. Storage::fake('icons');
  143. $user = User::factory()->create();
  144. $twofaccount = TwoFAccount::factory()->for($user)->create([
  145. 'icon' => OtpTestData::ICON_PNG,
  146. ]);
  147. IconStore::store(OtpTestData::ICON_PNG, base64_decode(OtpTestData::ICON_PNG_DATA));
  148. Storage::disk('icons')->assertExists($twofaccount->icon);
  149. $user->delete();
  150. Storage::disk('icons')->assertMissing($twofaccount->icon);
  151. }
  152. #[Test]
  153. public function test_delete_does_not_delete_the_only_admin()
  154. {
  155. $admin = User::factory()->administrator()->create();
  156. $this->assertEquals(1, User::admins()->count());
  157. $isDeleted = $admin->delete();
  158. $this->assertFalse($isDeleted);
  159. }
  160. #[Test]
  161. public function test_getFromCredentialId_retreives_the_user()
  162. {
  163. $user = User::factory()->create();
  164. DB::table('webauthn_credentials')->insert([
  165. 'id' => '-VOLFKPY-_FuMI_sJ7gMllK76L3VoRUINj6lL_Z3qDg',
  166. 'authenticatable_type' => \App\Models\User::class,
  167. 'authenticatable_id' => $user->id,
  168. 'user_id' => 'e8af6f703f8042aa91c30cf72289aa07',
  169. 'counter' => 0,
  170. 'rp_id' => 'http://localhost',
  171. 'origin' => 'http://localhost',
  172. 'aaguid' => '00000000-0000-0000-0000-000000000000',
  173. 'attestation_format' => 'none',
  174. 'public_key' => 'eyJpdiI6Imp0U0NVeFNNbW45KzEvMXpad2p2SUE9PSIsInZhbHVlIjoic0VxZ2I1WnlHM2lJakhkWHVkK2kzMWtibk1IN2ZlaExGT01qOElXMDdRTjhnVlR0TDgwOHk1S0xQUy9BQ1JCWHRLNzRtenNsMml1dVQydWtERjFEU0h0bkJGT2RwUXE1M1JCcVpablE2Y2VGV2YvVEE2RGFIRUE5L0x1K0JIQXhLVE1aNVNmN3AxeHdjRUo2V0hwREZSRTJYaThNNnB1VnozMlVXZEVPajhBL3d3ODlkTVN3bW54RTEwSG0ybzRQZFFNNEFrVytUYThub2IvMFRtUlBZamoyZElWKzR1bStZQ1IwU3FXbkYvSm1FU2FlMTFXYUo0SG9kc1BDME9CNUNKeE9IelE5d2dmNFNJRXBKNUdlVzJ3VHUrQWJZRFluK0hib0xvVTdWQ0ZISjZmOWF3by83aVJES1dxbU9Zd1lhRTlLVmhZSUdlWmlBOUFtcTM2ZVBaRWNKNEFSQUhENk5EaC9hN3REdnVFbm16WkRxekRWOXd4cVcvZFdKa2tlWWJqZWlmZnZLS0F1VEVCZEZQcXJkTExiNWRyQmxsZWtaSDRlT3VVS0ZBSXFBRG1JMjRUMnBKRXZxOUFUa2xxMjg2TEplUzdscVo2UytoVU5SdXk1OE1lcFN6aU05ZkVXTkdIM2tKM3Q5bmx1TGtYb1F5bGxxQVR3K3BVUVlia1VybDFKRm9lZDViNzYraGJRdmtUb2FNTEVGZmZYZ3lYRDRiOUVjRnJpcTVvWVExOHJHSTJpMnVBZ3E0TmljbUlKUUtXY2lSWDh1dE5MVDNRUzVRSkQrTjVJUU8rSGhpeFhRRjJvSEdQYjBoVT0iLCJtYWMiOiI5MTdmNWRkZGE5OTEwNzQ3MjhkYWVhYjRlNjk0MWZlMmI5OTQ4YzlmZWI1M2I4OGVkMjE1MjMxNjUwOWRmZTU2IiwidGFnIjoiIn0=',
  175. 'updated_at' => now(),
  176. 'created_at' => now(),
  177. ]);
  178. $searched = User::getFromCredentialId('-VOLFKPY-_FuMI_sJ7gMllK76L3VoRUINj6lL_Z3qDg');
  179. $this->assertEquals($user->id, $searched->id);
  180. }
  181. #[Test]
  182. public function test_authentications_returns_user_auth_logs_sorted_by_latest_id()
  183. {
  184. $user = User::factory()->create();
  185. $tenDaysAgoAuthLog = AuthLog::factory()->daysAgo(10)->for($user, 'authenticatable')->create();
  186. $fiveDaysAgoAuthLog = AuthLog::factory()->daysAgo(5)->for($user, 'authenticatable')->create();
  187. $lastAuthLog = AuthLog::factory()->daysAgo(1)->for($user, 'authenticatable')->create();
  188. $authentications = $user->authentications()->get();
  189. $this->assertCount(3, $authentications);
  190. $this->assertEquals($lastAuthLog->id, $authentications[0]->id);
  191. $this->assertEquals($fiveDaysAgoAuthLog->id, $authentications[1]->id);
  192. $this->assertEquals($tenDaysAgoAuthLog->id, $authentications[2]->id);
  193. }
  194. #[Test]
  195. public function test_authentications_returns_user_auth_logs_only()
  196. {
  197. $user = User::factory()->create();
  198. $anotherUser = User::factory()->create();
  199. $userAuthLog = AuthLog::factory()->daysAgo(10)->for($user, 'authenticatable')->create();
  200. AuthLog::factory()->daysAgo(5)->for($anotherUser, 'authenticatable')->create();
  201. $authentications = $user->authentications()->get();
  202. $this->assertCount(1, $authentications);
  203. $this->assertEquals($userAuthLog->id, $authentications[0]->id);
  204. }
  205. #[Test]
  206. public function test_authenticationsByPeriod_returns_last_month_auth_logs()
  207. {
  208. $user = User::factory()->create();
  209. $twoMonthsAgoAuthLog = AuthLog::factory()->duringLastThreeMonth()->for($user, 'authenticatable')->create();
  210. $duringLastMonthAuthLog = AuthLog::factory()->duringLastMonth()->for($user, 'authenticatable')->create();
  211. $authentications = $user->authenticationsByPeriod(1);
  212. $this->assertCount(1, $authentications);
  213. $this->assertEquals($duringLastMonthAuthLog->id, $authentications[0]->id);
  214. }
  215. #[Test]
  216. public function test_authenticationsByPeriod_returns_last_three_months_auth_logs()
  217. {
  218. $user = User::factory()->create();
  219. $sixMonthsAgoAuthLog = AuthLog::factory()->duringLastSixMonth()->for($user, 'authenticatable')->create();
  220. $threeMonthsAgoAuthLog = AuthLog::factory()->duringLastThreeMonth()->for($user, 'authenticatable')->create();
  221. $duringLastMonthAuthLog = AuthLog::factory()->duringLastMonth()->for($user, 'authenticatable')->create();
  222. $authentications = $user->authenticationsByPeriod(3);
  223. $this->assertCount(2, $authentications);
  224. $this->assertEquals($duringLastMonthAuthLog->id, $authentications[0]->id);
  225. $this->assertEquals($threeMonthsAgoAuthLog->id, $authentications[1]->id);
  226. }
  227. #[Test]
  228. public function test_latestAuthentication_returns_user_latest_auth_logs()
  229. {
  230. $user = User::factory()->create();
  231. $twoMonthsAgoAuthLog = AuthLog::factory()->duringLastThreeMonth()->for($user, 'authenticatable')->create();
  232. $duringLastMonthAuthLog = AuthLog::factory()->duringLastMonth()->for($user, 'authenticatable')->create();
  233. $authentications = $user->latestAuthentication()->get();
  234. $this->assertCount(1, $authentications);
  235. $this->assertEquals($duringLastMonthAuthLog->id, $authentications[0]->id);
  236. }
  237. #[Test]
  238. public function test_latestAuthentication_returns_user_latest_auth_logs_only()
  239. {
  240. $user = User::factory()->create();
  241. $anotherUser = User::factory()->create();
  242. $userAuthLog = AuthLog::factory()->duringLastThreeMonth()->for($user, 'authenticatable')->create();
  243. $anotherUserAuthLog = AuthLog::factory()->duringLastMonth()->for($anotherUser, 'authenticatable')->create();
  244. $authentications = $user->latestAuthentication()->get();
  245. $this->assertCount(1, $authentications);
  246. $this->assertEquals($userAuthLog->id, $authentications[0]->id);
  247. }
  248. #[Test]
  249. public function test_lastLoginAt_returns_user_last_auth_date()
  250. {
  251. $user = User::factory()->create();
  252. $now = now();
  253. $tenDaysAgoAuthLog = AuthLog::factory()->daysAgo(10)->for($user, 'authenticatable')->create();
  254. $fiveDaysAgoAuthLog = AuthLog::factory()->daysAgo(5)->for($user, 'authenticatable')->create();
  255. $lastAuthLog = AuthLog::factory()->at($now)->for($user, 'authenticatable')->create();
  256. $lastLoginAt = $user->lastLoginAt();
  257. $this->assertEquals($lastLoginAt->startOfSecond(), $now->startOfSecond());
  258. }
  259. #[Test]
  260. public function test_lastLoginAt_returns_null_if_user_has_no_login()
  261. {
  262. $user = User::factory()->create();
  263. AuthLog::factory()->logoutOnly()->for($user, 'authenticatable')->create();
  264. $lastLoginAt = $user->lastLoginAt();
  265. $this->assertNull($lastLoginAt);
  266. }
  267. #[Test]
  268. public function test_lastSuccessfulLoginAt_returns_user_last_successful_login_date()
  269. {
  270. $user = User::factory()->create();
  271. $now = now();
  272. AuthLog::factory()->at($now)->for($user, 'authenticatable')->create();
  273. $lastSuccessfulLoginAt = $user->lastSuccessfulLoginAt();
  274. $this->assertEquals($lastSuccessfulLoginAt->startOfSecond(), $now->startOfSecond());
  275. }
  276. #[Test]
  277. public function test_lastSuccessfulLoginAt_returns_null_if_user_has_no_successful_login()
  278. {
  279. $user = User::factory()->create();
  280. $now = now();
  281. AuthLog::factory()->at($now)->failedLogin()->for($user, 'authenticatable')->create();
  282. $lastSuccessfulLoginAt = $user->lastSuccessfulLoginAt();
  283. $this->assertNull($lastSuccessfulLoginAt);
  284. }
  285. #[Test]
  286. public function test_lastLoginIp_returns_user_last_login_ip()
  287. {
  288. $user = User::factory()->create();
  289. AuthLog::factory()->for($user, 'authenticatable')->create();
  290. $lastLoginIp = $user->lastLoginIp();
  291. $this->assertEquals(AuthLogFactory::IP, $lastLoginIp);
  292. }
  293. #[Test]
  294. public function test_lastLoginIp_returns_null_if_user_has_no_auth_log()
  295. {
  296. $user = User::factory()->create();
  297. $lastLoginIp = $user->lastLoginIp();
  298. $this->assertNull($lastLoginIp);
  299. }
  300. #[Test]
  301. public function test_lastSuccessfulLoginIp_returns_user_last_successful_login_ip()
  302. {
  303. $user = User::factory()->create();
  304. AuthLog::factory()->for($user, 'authenticatable')->create();
  305. $lastSuccessfulLoginIp = $user->lastSuccessfulLoginIp();
  306. $this->assertEquals(AuthLogFactory::IP, $lastSuccessfulLoginIp);
  307. }
  308. #[Test]
  309. public function test_lastSuccessfulLoginIp_returns_null_if_user_has_no_successful_login()
  310. {
  311. $user = User::factory()->create();
  312. AuthLog::factory()->failedLogin()->for($user, 'authenticatable')->create();
  313. $lastSuccessfulLoginIp = $user->lastSuccessfulLoginIp();
  314. $this->assertNull($lastSuccessfulLoginIp);
  315. }
  316. #[Test]
  317. public function test_previousLoginAt_returns_user_last_auth_date()
  318. {
  319. $user = User::factory()->create();
  320. $now = now();
  321. $yesterday = now()->subDay();
  322. $yesterdayAuthLog = AuthLog::factory()->at($yesterday)->for($user, 'authenticatable')->create();
  323. $lastAuthLog = AuthLog::factory()->at($now)->for($user, 'authenticatable')->create();
  324. $previousLoginAt = $user->previousLoginAt();
  325. $this->assertEquals($previousLoginAt->startOfSecond(), $yesterday->startOfSecond());
  326. }
  327. #[Test]
  328. public function test_previousLoginAt_returns_null_if_user_has_no_auth_log()
  329. {
  330. $user = User::factory()->create();
  331. $previousLoginAt = $user->previousLoginAt();
  332. $this->assertNull($previousLoginAt);
  333. }
  334. #[Test]
  335. public function test_previousLoginIp_returns_user_last_auth_ip()
  336. {
  337. $user = User::factory()->create();
  338. $yesterday = now()->subDay();
  339. AuthLog::factory()->for($user, 'authenticatable')->create();
  340. AuthLog::factory()->at($yesterday)->for($user, 'authenticatable')->create();
  341. $previousLoginIp = $user->previousLoginIp();
  342. $this->assertEquals(AuthLogFactory::IP, $previousLoginIp);
  343. }
  344. #[Test]
  345. public function test_previousLoginIp_returns_null_if_user_has_no_auth_log()
  346. {
  347. $user = User::factory()->create();
  348. $previousLoginIp = $user->previousLoginIp();
  349. $this->assertNull($previousLoginIp);
  350. }
  351. }