Плагин для пользователей CakeDC: ошибка перенаправления после смены пароля

Мое приложение разработано в CakePHP 3.x.

Я использую плагин CakedDC Users, и он отлично работает, за исключением случаев, когда пользователь хочет изменить свой пароль и нажимает «Отправить».

Допустим, у нас есть ID профиля = 52606b3f-c72d-4485-9c76-3b0f8.

Страница редактирования имеет такой URL-адрес:

локальный/мое_приложение/профиль/52606b3f-c72d-4485-9c76-3b0f8

Страница changePassword имеет такой URL-адрес:

localhost/my_app/users/users/change-password/52606b3f-c72d-4485-9c76-3b0f8

Когда я нажимаю «Отправить», он перенаправляет на страницу профиля, но идентификатор теряется:

локальный/мое_приложение/профиль

и я получаю это сообщение об ошибке:

Запись не найдена в таблице «users» с первичным ключом [NULL]

Я думаю, причина в том, что ID не передается. И не нахожу где и как исправить.

Любая помощь, пожалуйста?


person mbenjemaa    schedule 02.11.2017    source источник


Ответы (2)


Если идентификатор не передан, идентификатор берется у вошедшего в систему пользователя. Вы можете взглянуть на src/Controller/Traits/ProfileTrait.php. Не могли бы вы отладить $this->Auth->user('id')?

Кроме того, вы можете настроить URL-адрес перенаправления после смены пароля. Configure::write('Users.Profile.route', [{url}]), см. src/Controller/Traits/PasswordManagementTrait.php Ln44.

person yeliparra    schedule 09.11.2017

Я не помню свой первоначальный код, но спустя несколько месяцев я нашел решение.

в src/Controller/Traits/ProfileTrait.php установите $redirect = Configure::read('Users.Profile.route');

public function changePassword()
{
    $user = $this->getUsersTable()->newEntity();
    $id = $this->Auth->user('id');
    if (!empty($id)) {
        $user->id = $this->Auth->user('id');
        $validatePassword = true;
        //@todo add to the documentation: list of routes used
        $redirect = Configure::read('Users.Profile.route');
    } else {
        $user->id = $this->request->session()->read(Configure::read('Users.Key.Session.resetPasswordUserId'));
        $validatePassword = false;
        if (!$user->id) {
            $this->Flash->error(__d('CakeDC/Users', 'User was not found'));
            $this->redirect($this->Auth->config('loginAction'));

            return;
        }
        //@todo add to the documentation: list of routes used
        $redirect = $this->Auth->config('loginAction');
    }
    $this->set('validatePassword', $validatePassword);
    if ($this->request->is('post')) {
        try {
            $validator = $this->getUsersTable()->validationPasswordConfirm(new Validator());
            if (!empty($id)) {
                $validator = $this->getUsersTable()->validationCurrentPassword($validator);
            }
            $user = $this->getUsersTable()->patchEntity($user, $this->request->data(), ['validate' => $validator]);
            if ($user->errors()) {
                $this->Flash->error(__d('CakeDC/Users', 'Password could not be changed'));
            } else {
                $user = $this->getUsersTable()->changePassword($user);
                if ($user) {
                    $this->Flash->success(__d('CakeDC/Users', 'Password has been changed successfully'));

                    return $this->redirect($redirect);
                } else {
                    $this->Flash->error(__d('CakeDC/Users', 'Password could not be changed'));
                }
            }
        } catch (UserNotFoundException $exception) {
            $this->Flash->error(__d('CakeDC/Users', 'User was not found'));
        } catch (WrongPasswordException $wpe) {
            $this->Flash->error(__d('CakeDC/Users', '{0}', $wpe->getMessage()));
        } catch (Exception $exception) {
            $this->Flash->error(__d('CakeDC/Users', 'Password could not be changed'));
        }
    }
    $this->set(compact('user'));
    $this->set('_serialize', ['user']);
}
person mbenjemaa    schedule 08.06.2018