]> BookStack Code Mirror - bookstack/blob - app/Console/Commands/CreateAdmin.php
3d1a3dca08db4045e528bfcab92c13984cbdeff9
[bookstack] / app / Console / Commands / CreateAdmin.php
1 <?php
2
3 namespace BookStack\Console\Commands;
4
5 use BookStack\Auth\UserRepo;
6 use Illuminate\Console\Command;
7
8 class CreateAdmin extends Command
9 {
10     /**
11      * The name and signature of the console command.
12      *
13      * @var string
14      */
15     protected $signature = 'bookstack:create-admin
16                             {--email= : The email address for the new admin user}
17                             {--name= : The name of the new admin user}
18                             {--password= : The password to assign to the new admin user}';
19
20     /**
21      * The console command description.
22      *
23      * @var string
24      */
25     protected $description = 'Add a new admin user to the system';
26
27     protected $userRepo;
28
29     /**
30      * Create a new command instance.
31      */
32     public function __construct(UserRepo $userRepo)
33     {
34         $this->userRepo = $userRepo;
35         parent::__construct();
36     }
37
38     /**
39      * Execute the console command.
40      *
41      * @return mixed
42      * @throws \BookStack\Exceptions\NotFoundException
43      */
44     public function handle()
45     {
46         $email = trim($this->option('email'));
47         if (empty($email)) {
48             $email = $this->ask('Please specify an email address for the new admin user');
49         }
50         if (mb_strlen($email) < 5 || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
51             return $this->error('Invalid email address provided');
52         }
53
54         if ($this->userRepo->getByEmail($email) !== null) {
55             return $this->error('A user with the provided email already exists!');
56         }
57
58         $name = trim($this->option('name'));
59         if (empty($name)) {
60             $name = $this->ask('Please specify an name for the new admin user');
61         }
62         if (mb_strlen($name) < 2) {
63             return $this->error('Invalid name provided');
64         }
65
66         $password = trim($this->option('password'));
67         if (empty($password)) {
68             $password = $this->secret('Please specify a password for the new admin user');
69         }
70         if (mb_strlen($password) < 5) {
71             return $this->error('Invalid password provided, Must be at least 5 characters');
72         }
73
74
75         $user = $this->userRepo->create(['email' => $email, 'name' => $name, 'password' => $password]);
76         $this->userRepo->attachSystemRole($user, 'admin');
77         $this->userRepo->downloadAndAssignUserAvatar($user);
78         $user->email_confirmed = true;
79         $user->save();
80
81         $this->info("Admin account with email \"{$user->email}\" successfully created!");
82     }
83 }