option('force') && User::where('is_admin', true)->exists()) {
$this->error('Admin users already exist! Use --force to create anyway.');
return 1;
}
// Get user input for email and name
$email = $this->option('email') ?: $this->ask('Admin email address', 'admin@authentikate.local');
$name = $this->option('name') ?: $this->ask('Admin name', 'Administrator');
// Validate email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$this->error('Invalid email address format.');
return 1;
}
// Check if email already exists
if (User::where('email', $email)->exists()) {
$this->error("A user with email '{$email}' already exists.");
return 1;
}
// Generate a random password
$password = $this->generateSecurePassword();
// Create the admin user
$user = User::create([
'name' => $name,
'email' => $email,
'password' => Hash::make($password),
'email_verified_at' => now(),
'is_admin' => true,
]);
// Display success message with login credentials
$this->info('✅ Initial admin user created successfully!');
$this->newLine();
$this->line('🔐 Login Credentials:');
$this->line("📧 Email: {$email}>");
$this->line("🔑 Password: {$password}>");
$this->newLine();
$this->warn('⚠️ Please log in and change your password immediately!');
$this->info('💡 You can access the admin panel to manage users and applications.');
return 0;
}
/**
* Generate a secure random password
*/
private function generateSecurePassword(): string
{
// Generate a password with a mix of uppercase, lowercase, numbers, and symbols
$length = 16;
$lowercase = 'abcdefghijklmnopqrstuvwxyz';
$uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$numbers = '0123456789';
$symbols = '!@#$%^&*()_+-=[]{}|;:,.<>?';
$password = '';
// Ensure at least one character from each category
$password .= $lowercase[random_int(0, strlen($lowercase) - 1)];
$password .= $uppercase[random_int(0, strlen($uppercase) - 1)];
$password .= $numbers[random_int(0, strlen($numbers) - 1)];
$password .= $symbols[random_int(0, strlen($symbols) - 1)];
// Fill the rest with random characters from all categories
$allChars = $lowercase . $uppercase . $numbers . $symbols;
for ($i = 4; $i < $length; $i++) {
$password .= $allChars[random_int(0, strlen($allChars) - 1)];
}
// Shuffle the password to randomize the order
return str_shuffle($password);
}
}