3 namespace BookStack\Console\Commands;
5 use BookStack\Users\Models\Role;
6 use BookStack\Users\UserRepo;
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;
13 class CreateAdminCommand extends Command
16 * The name and signature of the console command.
20 protected $signature = 'bookstack:create-admin
21 {--email= : The email address for the new admin user}
22 {--name= : The name of the new admin user}
23 {--password= : The password to assign to the new admin user}
24 {--external-auth-id= : The external authentication system id for the new admin user (SAML2/LDAP/OIDC)}';
27 * The console command description.
31 protected $description = 'Add a new admin user to the system';
34 * Execute the console command.
36 public function handle(UserRepo $userRepo): int
38 $details = $this->snakeCaseOptions();
40 if (empty($details['email'])) {
41 $details['email'] = $this->ask('Please specify an email address for the new admin user');
44 if (empty($details['name'])) {
45 $details['name'] = $this->ask('Please specify a name for the new admin user');
48 if (empty($details['password'])) {
49 if (empty($details['external_auth_id'])) {
50 $details['password'] = $this->ask('Please specify a password for the new admin user (8 characters min)');
52 $details['password'] = Str::random(32);
56 $validator = Validator::make($details, [
57 'email' => ['required', 'email', 'min:5', new Unique('users', 'email')],
58 'name' => ['required', 'min:2'],
59 'password' => ['required_without:external_auth_id', Password::default()],
60 'external_auth_id' => ['required_without:password'],
63 if ($validator->fails()) {
64 foreach ($validator->errors()->all() as $error) {
71 $user = $userRepo->createWithoutActivity($validator->validated());
72 $user->attachRole(Role::getSystemRole('admin'));
73 $user->email_confirmed = true;
76 $this->info("Admin account with email \"{$user->email}\" successfully created!");
81 protected function snakeCaseOptions(): array
84 foreach ($this->options() as $key => $value) {
85 $returnOpts[str_replace('-', '_', $key)] = $value;