Skip to content

Commit 8bae692

Browse files
committed
Add an artisan command to change password
1 parent fa566f1 commit 8bae692

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
<?php
2+
3+
namespace BookStack\Console\Commands;
4+
5+
use BookStack\Users\Models\Role;
6+
use BookStack\Users\UserRepo;
7+
use Illuminate\Console\Command;
8+
use Illuminate\Support\Facades\Hash;
9+
use Illuminate\Support\Facades\Validator;
10+
use Illuminate\Support\Str;
11+
use Illuminate\Validation\Rules\Password;
12+
use Illuminate\Validation\Rules\Unique;
13+
14+
class ChangePasswordCommand extends Command
15+
{
16+
/**
17+
* The name and signature of the console command.
18+
*
19+
* @var string
20+
*/
21+
protected $signature = 'bookstack:change-password
22+
{--email= : The email address of the account}
23+
{--password= : The password to assign}';
24+
25+
/**
26+
* The console command description.
27+
*
28+
* @var string
29+
*/
30+
protected $description = 'Change the password of a user';
31+
32+
/**
33+
* Execute the console command.
34+
*/
35+
public function handle(UserRepo $userRepo): int
36+
{
37+
$details = $this->snakeCaseOptions();
38+
39+
if (empty($details['email'])) {
40+
$details['email'] = $this->ask('Please specify an email address');
41+
}
42+
43+
if (empty($details['password'])) {
44+
$details['password'] = $this->ask('Please specify a password (8 characters minimum)');
45+
}
46+
47+
$validator = Validator::make($details, [
48+
'email' => ['required', 'email', 'min:5'],
49+
'password' => [Password::default()],
50+
]);
51+
52+
if ($validator->fails()) {
53+
foreach ($validator->errors()->all() as $error) {
54+
$this->error($error);
55+
}
56+
57+
return 1;
58+
}
59+
60+
$user = $userRepo->getByEmail($details['email']);
61+
62+
if (empty($user)) {
63+
$this->error("Could not find user!");
64+
return 1;
65+
}
66+
67+
$user->password = Hash::make($details['password']);
68+
$user->save();
69+
70+
$this->info("Password for account with email \"{$user->email}\" successfully updated!");
71+
72+
return 0;
73+
}
74+
75+
protected function snakeCaseOptions(): array
76+
{
77+
$returnOpts = [];
78+
foreach ($this->options() as $key => $value) {
79+
$returnOpts[str_replace('-', '_', $key)] = $value;
80+
}
81+
82+
return $returnOpts;
83+
}
84+
}

0 commit comments

Comments
 (0)