3 namespace BookStack\Console\Commands;
5 use BookStack\Auth\UserRepo;
6 use BookStack\Exceptions\NotFoundException;
7 use Illuminate\Console\Command;
8 use Illuminate\Support\Facades\Validator;
9 use Illuminate\Support\Str;
10 use Illuminate\Validation\Rules\Password;
11 use Illuminate\Validation\Rules\Unique;
12 use Symfony\Component\Console\Command\Command as SymfonyCommand;
14 class CreateAdmin extends Command
17 * The name and signature of the console command.
21 protected $signature = 'bookstack:create-admin
22 {--email= : The email address for the new admin user}
23 {--name= : The name of the new admin user}
24 {--password= : The password to assign to the new admin user}
25 {--external-auth-id= : The external authentication system id for the new admin user (SAML2/LDAP/OIDC)}';
28 * The console command description.
32 protected $description = 'Add a new admin user to the system';
37 * Create a new command instance.
39 public function __construct(UserRepo $userRepo)
41 $this->userRepo = $userRepo;
42 parent::__construct();
46 * Execute the console command.
48 * @throws NotFoundException
52 public function handle()
54 $details = $this->snakeCaseOptions();
56 if (empty($details['email'])) {
57 $details['email'] = $this->ask('Please specify an email address for the new admin user');
60 if (empty($details['name'])) {
61 $details['name'] = $this->ask('Please specify a name for the new admin user');
64 if (empty($details['password'])) {
65 if (empty($details['external_auth_id'])) {
66 $details['password'] = $this->ask('Please specify a password for the new admin user (8 characters min)');
68 $details['password'] = Str::random(32);
72 $validator = Validator::make($details, [
73 'email' => ['required', 'email', 'min:5', new Unique('users', 'email')],
74 'name' => ['required', 'min:2'],
75 'password' => ['required_without:external_auth_id', Password::default()],
76 'external_auth_id' => ['required_without:password'],
79 if ($validator->fails()) {
80 foreach ($validator->errors()->all() as $error) {
84 return SymfonyCommand::FAILURE;
87 $user = $this->userRepo->create($validator->validated());
88 $this->userRepo->attachSystemRole($user, 'admin');
89 $this->userRepo->downloadAndAssignUserAvatar($user);
90 $user->email_confirmed = true;
93 $this->info("Admin account with email \"{$user->email}\" successfully created!");
95 return SymfonyCommand::SUCCESS;
98 protected function snakeCaseOptions(): array
101 foreach ($this->options() as $key => $value) {
102 $returnOpts[str_replace('-', '_', $key)] = $value;