2
0

UsersDesensitize.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use App\Models\UserInfo;
  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. * @var string
  13. */
  14. protected $signature = 'users:desensitize {--test}';
  15. /**
  16. * The console command description.
  17. *
  18. * @var string
  19. */
  20. protected $description = 'desensitize users information';
  21. /**
  22. * Create a new command instance.
  23. *
  24. * @return void
  25. */
  26. public function __construct()
  27. {
  28. parent::__construct();
  29. }
  30. /**
  31. * Execute the console command.
  32. *
  33. * @return int
  34. */
  35. public function handle()
  36. {
  37. if (App::environment('product')) {
  38. $this->error('environment is product');
  39. return 1;
  40. }
  41. $this->info('environment is ' . App::environment());
  42. if ($this->option('test')) {
  43. $this->info('test mode');
  44. } else {
  45. $this->error('this is not test mode');
  46. }
  47. if (!$this->confirm("desensitize all users information?")) {
  48. return 0;
  49. }
  50. $users = UserInfo::cursor();
  51. $total = UserInfo::count();
  52. $desensitized = 0;
  53. $jumped = 0;
  54. foreach ($users as $key => $user) {
  55. if (
  56. mb_substr($user->username, 0, 4) === 'test' ||
  57. $user->username === 'admin'
  58. ) {
  59. $this->info('test user jump' . $user->username);
  60. $jumped++;
  61. continue;
  62. }
  63. $desensitized++;
  64. if (!$this->option('test')) {
  65. $curr = UserInfo::find($user->id);
  66. $curr->password = Str::uuid() . '*';
  67. $curr->email = Str::uuid() . '@email.com';
  68. $curr->username = mb_substr($curr->username, 0, 2) . mt_rand(1000, 9999) . '****';
  69. $curr->nickname = mb_substr($curr->nickname, 0, 1) . '**';
  70. $curr->save();
  71. }
  72. $this->info('desensitized ' . $user->username);
  73. }
  74. $this->info("all done total={$total} desensitized={$desensitized} jumped={$jumped}");
  75. return 0;
  76. }
  77. }