3 namespace BookStack\Console\Commands;
5 use BookStack\Auth\Role;
6 use BookStack\Auth\UserRepo;
7 use BookStack\Exceptions\NotFoundException;
8 use Illuminate\Console\Command;
9 use Illuminate\Support\Facades\Validator;
10 use Illuminate\Support\Str;
11 use Illuminate\Validation\Rules\Password;
12 use Illuminate\Validation\Rules\Unique;
13 use Symfony\Component\Console\Command\Command as SymfonyCommand;
15 class CreateAdmin extends Command
18 * The name and signature of the console command.
22 protected $signature = 'bookstack:create-admin
23 {--email= : The email address for the new admin user}
24 {--name= : The name of the new admin user}
25 {--password= : The password to assign to the new admin user}
26 {--external-auth-id= : The external authentication system id for the new admin user (SAML2/LDAP/OIDC)}';
29 * The console command description.
33 protected $description = 'Add a new admin user to the system';
38 * Create a new command instance.
40 public function __construct(UserRepo $userRepo)
42 $this->userRepo = $userRepo;
43 parent::__construct();
47 * Execute the console command.
49 * @throws NotFoundException
53 public function handle()
55 $details = $this->snakeCaseOptions();
57 if (empty($details['email'])) {
58 $details['email'] = $this->ask('Please specify an email address for the new admin user');
61 if (empty($details['name'])) {
62 $details['name'] = $this->ask('Please specify a name for the new admin user');
65 if (empty($details['password'])) {
66 if (empty($details['external_auth_id'])) {
67 $details['password'] = $this->ask('Please specify a password for the new admin user (8 characters min)');
69 $details['password'] = Str::random(32);
73 $validator = Validator::make($details, [
74 'email' => ['required', 'email', 'min:5', new Unique('users', 'email')],
75 'name' => ['required', 'min:2'],
76 'password' => ['required_without:external_auth_id', Password::default()],
77 'external_auth_id' => ['required_without:password'],
80 if ($validator->fails()) {
81 foreach ($validator->errors()->all() as $error) {
85 return SymfonyCommand::FAILURE;
88 $user = $this->userRepo->createWithoutActivity($validator->validated());
89 $user->attachRole(Role::getSystemRole('admin'));
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;