CakePHP - Войти с домашней страницы, используя аутентификацию - PullRequest
0 голосов
/ 30 марта 2011

Я решил поместить свою форму входа в элемент и отобразить ее на моей домашней странице.

Вход с правильными учетными данными работает просто отлично. Проблема возникает, когда указаны неверные учетные данные. После отправки формы я получаю ошибку 404. Однако, если я обновлю страницу, контроллер выполнит действие входа в систему просто отлично.

<?php

class UsersController extends AppController {
var $name = 'Users';
var $components = array('Security');

// set redirect page after being logged out
function beforeFilter() {
        $this->Auth->fields = array(
            'username' => 'email',
            'password' => 'password'
        );
        $this->Auth->allow('register');
        $this->Auth->loginRedirect = array('controller' => 'posts', 'action' => 'map');
        $this->Auth->logoutRedirect = array('controller' => 'posts', 'action' => 'map');
}

function register() {
    $this->set('title_for_layout', 'Register');
    if (!empty($this->data)) {
            if ($this->User->save($this->data)) {
                // after succesfully creating the user, log him in and redirect to map view
                // for some reason, the hashed password is not kept after the save,
                // therefore we must rehash the password
                $this->data['User']['password'] = Security::hash($this->data['User']['tmp_password'], NULL, true);
                $this->Auth->login($this->data);
                $this->redirect(array('controller' => 'posts', 'action' => 'map'));
            }
    }

}

function login() {
    $this->set('title_for_layout', 'Login');
}

function logout() {
    $this->redirect($this->Auth->logout());
}


}

?>

Элемент входа отображается на домашней странице: (Вы можете игнорировать JavaScript)

    echo "<script> $(function() {
    $('#UserDummyEmail').focus(function() {
        $('#UserDummyEmail').hide();
        $('#UserEmail').focus();
    });

    $('#UserEmail').blur(function() {
        if (($('#UserEmail').val()).length == 0) {
            $('#UserDummyEmail').show();
        }
    });

    $('#UserDummyPassword').focus(function() {
        $('#UserDummyPassword').hide();
        $('#UserPassword').focus();
    });

    // fix for tabbing bug
    $('#UserPassword').focus(function() {
        $('#UserDummyPassword').hide();
    });
    $('#UserEmail').focus(function() {
        $('#UserDummyEmail').hide();    
    });

    $('#UserPassword').blur(function() {
        if (($('#UserPassword').val()).length == 0) {
            $('#UserDummyPassword').show();
        }
    });

});</script>";

echo $session->flash('auth');
echo $this->Form->create('User', array('action' => 'login'));

echo $this->Form->input('dummyEmail', array('div'=>false, 'label' => false, 'value' => 'Email', 'tabindex' => '1'));
echo $this->Form->input('dummyPassword', array('div'=>false, 'label' => false, 'value' => 'Password', 'tabindex' => '2'));
echo $this->Form->input('email', array('div'=>false, 'label'=>false, 'tabindex'=> '3'));
echo $this->Form->input('password', array('div'=>false, 'label'=>false, 'tabindex' => '4'));
echo $this->Form->end('Login', array('div'=>false));

Спасибо!

Ответы [ 2 ]

0 голосов
/ 11 апреля 2011

Я удалил компонент Security из моей модели пользователя, и все начало работать ...

Я не знаю, ожидаемая ли это функциональность или ошибка.

Приветствия!

0 голосов
/ 02 апреля 2011

Добавьте компонент Auth и компонент Session в свой контроллер пользователей.

var $components = array('Security','Auth','Session');

На самом деле вы можете удалить компонент Security, так как вы нигде не используете $ this-> Security security.Если все еще не работает, явно укажите действие входа в систему при объявлении компонента:

var $components = array(
                        'Auth' => array(
                                       'loginAction' => array(
                                                         'controller' => 'users',
                                                             'action' => 'login',               
                                                             'plugin' => false,                       
                                                              'admin' => false)))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...