]> BookStack Code Mirror - bookstack/blob - app/Console/Commands/CreateAdmin.php
Apply fixes from StyleCI
[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      * @throws \BookStack\Exceptions\NotFoundException
42      *
43      * @return mixed
44      */
45     public function handle()
46     {
47         $email = trim($this->option('email'));
48         if (empty($email)) {
49             $email = $this->ask('Please specify an email address for the new admin user');
50         }
51         if (mb_strlen($email) < 5 || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
52             return $this->error('Invalid email address provided');
53         }
54
55         if ($this->userRepo->getByEmail($email) !== null) {
56             return $this->error('A user with the provided email already exists!');
57         }
58
59         $name = trim($this->option('name'));
60         if (empty($name)) {
61             $name = $this->ask('Please specify an name for the new admin user');
62         }
63         if (mb_strlen($name) < 2) {
64             return $this->error('Invalid name provided');
65         }
66
67         $password = trim($this->option('password'));
68         if (empty($password)) {
69             $password = $this->secret('Please specify a password for the new admin user');
70         }
71         if (mb_strlen($password) < 5) {
72             return $this->error('Invalid password provided, Must be at least 5 characters');
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 }