UsersDesensitize.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\UserInfo;
  4. use Illuminate\Console\Command;
  5. use Illuminate\Support\Facades\App;
  6. use Illuminate\Support\Str;
  7. class UsersDesensitize extends Command
  8. {
  9. /**
  10. * 对用户表进行脱敏,改写password email 两个字段数据.以test & admin开头的不会被改写
  11. * php artisan users:desensitize --test
  12. *
  13. * @var string
  14. */
  15. protected $signature = 'users:desensitize {--test}';
  16. /**
  17. * The console command description.
  18. *
  19. * @var string
  20. */
  21. protected $description = 'desensitize users information';
  22. /**
  23. * Create a new command instance.
  24. *
  25. * @return void
  26. */
  27. public function __construct()
  28. {
  29. parent::__construct();
  30. }
  31. /**
  32. * Execute the console command.
  33. *
  34. * @return int
  35. */
  36. public function handle()
  37. {
  38. if (App::environment('product')) {
  39. $this->error('environment is product');
  40. return 1;
  41. }
  42. $this->info('environment is '.App::environment());
  43. if ($this->option('test')) {
  44. $this->info('test mode');
  45. } else {
  46. $this->error('this is not test mode');
  47. if (! $this->confirm('desensitize all users information?')) {
  48. return 0;
  49. }
  50. }
  51. $users = UserInfo::cursor();
  52. $total = UserInfo::count();
  53. $desensitized = 0;
  54. $jumped = 0;
  55. foreach ($users as $key => $user) {
  56. if (
  57. mb_substr($user->username, 0, 4) === 'test' ||
  58. $user->username === 'admin' ||
  59. $user->username === 'visuddhinanda'
  60. ) {
  61. $this->info('test user jump'.$user->username);
  62. $jumped++;
  63. continue;
  64. }
  65. $desensitized++;
  66. if (! $this->option('test')) {
  67. $curr = UserInfo::find($user->id);
  68. $curr->password = Str::uuid().'*';
  69. $curr->email = Str::uuid().'@email.com';
  70. $curr->username = mb_substr($curr->username, 0, 2).mt_rand(1000, 9999).'****';
  71. $curr->nickname = mb_substr($curr->nickname, 0, 1).'**';
  72. $curr->save();
  73. }
  74. $this->info('desensitized '.$user->username);
  75. }
  76. $this->info("all done total={$total} desensitized={$desensitized} jumped={$jumped}");
  77. return 0;
  78. }
  79. }