Completed
Push — master ( cfcf27...c41e28 )
by Phan
14:15
created

ChangePasswordCommand   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 16%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 8
eloc 25
c 1
b 0
f 0
dl 0
loc 52
ccs 4
cts 25
cp 0.16
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A handle() 0 22 3
A __construct() 0 4 1
A validatePasswords() 0 15 4
1
<?php
2
3
namespace App\Console\Commands\Admin;
4
5
use App\Models\User;
6
use Illuminate\Console\Command;
7
use Illuminate\Contracts\Hashing\Hasher as Hash;
8
9
class ChangePasswordCommand extends Command
10
{
11
    protected $name = 'koel:admin:change-password';
12
    protected $description = "Change the default admin's password";
13
14
    private $hash;
15
16 132
    public function __construct(Hash $hash)
17
    {
18 132
        parent::__construct();
19 132
        $this->hash = $hash;
20 132
    }
21
22
    public function handle(): void
23
    {
24
        /** @var User $user */
25
        $user = User::where('is_admin', true)->first();
26
27
        if (!$user) {
0 ignored issues
show
introduced by
$user is of type App\Models\User, thus it always evaluated to true.
Loading history...
28
            $this->error('An admin account cannot be found. Have you set up Koel yet?');
29
30
            return;
31
        }
32
33
        $this->comment("Changing the default admin's password (ID: {$user->id}, email: {$user->email})");
34
35
        do {
36
            $password = $this->secret('New password');
37
            $confirmedPassword = $this->secret('Again, just to be sure');
38
        } while (!$this->validatePasswords($password, $confirmedPassword));
39
40
        $user->password = $this->hash->make($password);
41
        $user->save();
42
43
        $this->comment('New password saved, enjoy! 👌');
44
    }
45
46
    private function validatePasswords(?string $password, ?string $confirmedPassword): bool
47
    {
48
        if (!$password || !$confirmedPassword) {
49
            $this->error('Passwords cannot be empty. You know that.');
50
51
            return false;
52
        }
53
54
        if (strcmp($password, $confirmedPassword) !== 0) {
55
            $this->error('The passwords do not match. Try again maybe?');
56
57
            return false;
58
        }
59
60
        return true;
61
    }
62
}
63