CreateUser.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\Recipient;
  4. use App\Models\User;
  5. use App\Models\Username;
  6. use App\Rules\NotDeletedUsername;
  7. use App\Rules\NotLocalRecipient;
  8. use App\Rules\RegisterUniqueRecipient;
  9. use Illuminate\Auth\Events\Registered;
  10. use Illuminate\Console\Command;
  11. use Illuminate\Support\Facades\Hash;
  12. use Illuminate\Support\Facades\Validator;
  13. use Ramsey\Uuid\Uuid;
  14. class CreateUser extends Command
  15. {
  16. /**
  17. * The name and signature of the console command.
  18. *
  19. * @var string
  20. */
  21. protected $signature = 'anonaddy:create-user {username} {email}';
  22. /**
  23. * The console command description.
  24. *
  25. * @var string
  26. */
  27. protected $description = 'Creates a new user';
  28. /**
  29. * Create a new command instance.
  30. *
  31. * @return void
  32. */
  33. public function __construct()
  34. {
  35. parent::__construct();
  36. }
  37. /**
  38. * Execute the console command.
  39. *
  40. * @return int
  41. */
  42. public function handle()
  43. {
  44. $validator = Validator::make([
  45. 'username' => $this->argument('username'),
  46. 'email' => $this->argument('email'), ], [
  47. 'username' => [
  48. 'required',
  49. 'regex:/^[a-zA-Z0-9]*$/',
  50. 'max:20',
  51. 'unique:usernames,username',
  52. new NotDeletedUsername(),
  53. ],
  54. 'email' => [
  55. 'required',
  56. 'email:rfc,dns',
  57. 'max:254',
  58. new RegisterUniqueRecipient(),
  59. new NotLocalRecipient(),
  60. ],
  61. ]);
  62. if ($validator->fails()) {
  63. $errors = $validator->errors();
  64. foreach ($errors->all() as $message) {
  65. $this->error($message);
  66. }
  67. return 1;
  68. }
  69. $userId = Uuid::uuid4();
  70. $recipient = Recipient::create([
  71. 'email' => $this->argument('email'),
  72. 'user_id' => $userId,
  73. ]);
  74. $username = Username::create([
  75. 'username' => $this->argument('username'),
  76. 'user_id' => $userId,
  77. ]);
  78. $twoFactor = app('pragmarx.google2fa');
  79. $user = User::create([
  80. 'id' => $userId,
  81. 'default_username_id' => $username->id,
  82. 'default_recipient_id' => $recipient->id,
  83. 'password' => Hash::make($userId),
  84. 'two_factor_secret' => $twoFactor->generateSecretKey(),
  85. ]);
  86. event(new Registered($user));
  87. $this->info('Created user: "'.$user->username.'" with user_id: "'.$user->id.'"');
  88. $this->info('This user can now reset their password (the default password is their user_id)');
  89. return 0;
  90. }
  91. }