79 lines
2.6 KiB
PHP
79 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use App\Models\User;
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Support\Facades\Hash;
|
|
use Illuminate\Support\Facades\Validator;
|
|
|
|
class CreateInitialAdmin extends Command
|
|
{
|
|
protected $signature = 'app:create-initial-admin
|
|
{--name= : Admin full name}
|
|
{--email= : Admin email}
|
|
{--password= : Admin password}
|
|
{--from-env : Read credentials from INITIAL_ADMIN_* environment variables}';
|
|
|
|
protected $description = 'Create the initial administrator account when no users exist';
|
|
|
|
public function handle(): int
|
|
{
|
|
if (User::count() > 0) {
|
|
$this->info('Users already exist. Skipping initial admin creation.');
|
|
return self::SUCCESS;
|
|
}
|
|
|
|
$name = (string) ($this->option('name') ?? '');
|
|
$email = (string) ($this->option('email') ?? '');
|
|
$password = (string) ($this->option('password') ?? '');
|
|
|
|
if ($this->option('from-env')) {
|
|
$name = (string) env('INITIAL_ADMIN_NAME', $name);
|
|
$email = (string) env('INITIAL_ADMIN_EMAIL', $email);
|
|
$password = (string) env('INITIAL_ADMIN_PASSWORD', $password);
|
|
}
|
|
|
|
if ($name === '' || $email === '' || $password === '') {
|
|
if (! $this->input->isInteractive()) {
|
|
$this->error('Missing initial admin credentials. Set INITIAL_ADMIN_NAME, INITIAL_ADMIN_EMAIL and INITIAL_ADMIN_PASSWORD.');
|
|
return self::FAILURE;
|
|
}
|
|
|
|
$name = $name !== '' ? $name : $this->ask('Nome amministratore');
|
|
$email = $email !== '' ? $email : $this->ask('Email amministratore');
|
|
$password = $password !== '' ? $password : (string) $this->secret('Password amministratore (min 8 caratteri)');
|
|
}
|
|
|
|
$validator = Validator::make([
|
|
'name' => $name,
|
|
'email' => $email,
|
|
'password' => $password,
|
|
], [
|
|
'name' => ['required', 'string', 'max:255'],
|
|
'email' => ['required', 'email', 'max:255', 'unique:users,email'],
|
|
'password' => ['required', 'string', 'min:8'],
|
|
]);
|
|
|
|
if ($validator->fails()) {
|
|
foreach ($validator->errors()->all() as $error) {
|
|
$this->error($error);
|
|
}
|
|
|
|
return self::FAILURE;
|
|
}
|
|
|
|
$admin = User::create([
|
|
'name' => $name,
|
|
'email' => $email,
|
|
'password' => Hash::make($password),
|
|
]);
|
|
|
|
$admin->assignRole('amministratore');
|
|
|
|
$this->info("Initial admin created: {$admin->email}");
|
|
|
|
return self::SUCCESS;
|
|
}
|
|
}
|