1<?php
2
3namespace Kanboard\Console;
4
5use Symfony\Component\Console\Input\InputArgument;
6use Symfony\Component\Console\Input\InputInterface;
7use Symfony\Component\Console\Output\OutputInterface;
8use Symfony\Component\Console\Question\Question;
9
10class ResetPasswordCommand extends BaseCommand
11{
12    protected function configure()
13    {
14        $this
15            ->setName('user:reset-password')
16            ->setDescription('Change user password')
17            ->addArgument('username', InputArgument::REQUIRED, 'Username')
18        ;
19    }
20
21    protected function execute(InputInterface $input, OutputInterface $output)
22    {
23        $helper = $this->getHelper('question');
24        $username = $input->getArgument('username');
25
26        $passwordQuestion = new Question('What is the new password for '.$username.'? (characters are not printed)'.PHP_EOL);
27        $passwordQuestion->setHidden(true);
28        $passwordQuestion->setHiddenFallback(false);
29
30        $password = $helper->ask($input, $output, $passwordQuestion);
31
32        $confirmationQuestion = new Question('Confirmation:'.PHP_EOL);
33        $confirmationQuestion->setHidden(true);
34        $confirmationQuestion->setHiddenFallback(false);
35
36        $confirmation = $helper->ask($input, $output, $confirmationQuestion);
37
38        if ($this->validatePassword($output, $password, $confirmation)) {
39            $this->resetPassword($output, $username, $password);
40        }
41    }
42
43    private function validatePassword(OutputInterface $output, $password, $confirmation)
44    {
45        list($valid, $errors) = $this->passwordResetValidator->validateModification(array(
46            'password' => $password,
47            'confirmation' => $confirmation,
48        ));
49
50        if (!$valid) {
51            foreach ($errors as $error_list) {
52                foreach ($error_list as $error) {
53                    $output->writeln('<error>'.$error.'</error>');
54                }
55            }
56        }
57
58        return $valid;
59    }
60
61    private function resetPassword(OutputInterface $output, $username, $password)
62    {
63        $userId = $this->userModel->getIdByUsername($username);
64
65        if (empty($userId)) {
66            $output->writeln('<error>User not found</error>');
67            return false;
68        }
69
70        if (!$this->userModel->update(array('id' => $userId, 'password' => $password))) {
71            $output->writeln('<error>Unable to update password</error>');
72            return false;
73        }
74
75        $output->writeln('<info>Password updated successfully</info>');
76
77        return true;
78    }
79}
80