Skip to content

Add an artisan command to change password #5596

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: development
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions app/Console/Commands/ChangePasswordCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<?php

namespace BookStack\Console\Commands;

use BookStack\Users\Models\Role;
use BookStack\Users\UserRepo;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules\Password;
use Illuminate\Validation\Rules\Unique;

class CreateAdminCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'bookstack:change-password
{--email= : The email address of the account}
{--password= : The password to assign}';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Change the password of a user';

/**
* Execute the console command.
*/
public function handle(UserRepo $userRepo): int
{
$details = $this->snakeCaseOptions();

if (empty($details['email'])) {
$details['email'] = $this->ask('Please specify an email address');
}

if (empty($details['password'])) {
$details['password'] = $this->ask('Please specify a password (8 characters minimum)');
}

$validator = Validator::make($details, [
'email' => ['required', 'email', 'min:5'],
'password' => [Password::default()],
]);

if ($validator->fails()) {
foreach ($validator->errors()->all() as $error) {
$this->error($error);
}

return 1;
}

$user = $userRepo->getByEmail($details['email']);

if (empty($user)) {
$this->error("Could not find user!");
return 1;
}

$user->password = Hash::make($details['password']);
$user->save();

$this->info("Password for account with email \"{$user->email}\" successfully updated!");

return 0;
}

protected function snakeCaseOptions(): array
{
$returnOpts = [];
foreach ($this->options() as $key => $value) {
$returnOpts[str_replace('-', '_', $key)] = $value;
}

return $returnOpts;
}
}