]> BookStack Code Mirror - bookstack/blob - app/Console/Commands/CreateAdmin.php
Abstracted user avatar fetching away from gravatar
[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      * @param UserRepo $userRepo
33      */
34     public function __construct(UserRepo $userRepo)
35     {
36         $this->userRepo = $userRepo;
37         parent::__construct();
38     }
39
40     /**
41      * Execute the console command.
42      *
43      * @return mixed
44      * @throws \BookStack\Exceptions\NotFoundException
45      */
46     public function handle()
47     {
48         $email = trim($this->option('email'));
49         if (empty($email)) {
50             $email = $this->ask('Please specify an email address for the new admin user');
51         }
52         if (strlen($email) < 5 || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
53             return $this->error('Invalid email address provided');
54         }
55
56         if ($this->userRepo->getByEmail($email) !== null) {
57             return $this->error('A user with the provided email already exists!');
58         }
59
60         $name = trim($this->option('name'));
61         if (empty($name)) {
62             $name = $this->ask('Please specify an name for the new admin user');
63         }
64         if (strlen($name) < 2) {
65             return $this->error('Invalid name provided');
66         }
67
68         $password = trim($this->option('password'));
69         if (empty($password)) {
70             $password = $this->secret('Please specify a password for the new admin user');
71         }
72         if (strlen($password) < 5) {
73             return $this->error('Invalid password provided, Must be at least 5 characters');
74         }
75
76
77         $user = $this->userRepo->create(['email' => $email, 'name' => $name, 'password' => $password]);
78         $this->userRepo->attachSystemRole($user, 'admin');
79         $this->userRepo->downloadAndAssignUserAvatar($user);
80         $user->email_confirmed = true;
81         $user->save();
82
83         $this->info("Admin account with email \"{$user->email}\" successfully created!");
84     }
85 }