簡體   English   中英

CakePHP登錄用戶名/密碼驗證

[英]CakePHP Login Username/Password Validation

我在users_controller中包含以下內容,因為還需要執行登錄的邏輯,但是在CakePHP中完成時,默認驗證將停止,因此,我試圖在進行帳戶檢查之前強制其驗證用戶名和密碼字段。 一切正常,但這。 我嘗試添加兩個if語句(如下)以檢查用戶名/密碼是否為空,但是,一旦頁面加載,它們便為空,並且顯示驗證框。

我對如何實現這一目標感到困惑。 任何幫助將不勝感激。

    function login() {
    if($this->Auth->user()) {
        $this->redirect(array('controller'=>'shows'));
    }
    if(empty($this->data['User']['username'])) {
        $this->User->validationErrors['username'] = "Please enter a username";
    }
    if(empty($this->data['User']['password'])) {
        $this->User->validationErrors['password'] = "Please enter a password";
    }
    if(!empty($this->data['User']['username'])) {
        // unset unrequired validation rules
        unset($this->User->validate['username']['unique']);

        // validate form
        $this->User->set($this->data);
        if($this->User->validates()) {
            // update Last Login date
            $this->User->id = $this->User->_user['User']['id'];
            $this->User->saveField('last_login',date("Y-m-d H:i:s"));

            // save User to Session and redirect
            $this->Session->write('User', $this->User->_user);
            $this->Session->setFlash('You have successfully logged in.','default',array('class'=>'flash_green'));
            //$this->redirect(array('controller'=>'shows', 'admin'=>FALSE));
        } else {
            $this->Session->setFlash('Incorrect username/password combination.','default',array('class'=>'flash_red'));
            $this->redirect(array('controller'=>'users', 'action'=>'login', 'admin'=>FALSE));
        }
    }
}

users_controller beforeFilter()

    function beforeFilter(){
    parent::beforeFilter();
    $this->Auth->allow('register');
}

app_controller beforeFilter和組件

    var $components = array('Session', 'Auth' => array(
    'loginAction' => array('controller'=>'users','action'=>'login', 'admin'=>false),
    //'logoutRedirect' => array('controller'=>'users','action'=>'logout'),
    'loginRedirect' => array('controller'=>'shows', 'action'=>'index'),
    'autoRedirect' => false,
    'authorize' => 'controller')
);

function beforeFilter() {
    $this->Auth->allow('home');
    $this->set('admin', $this->_isAdmin());
    $this->set('logged_in', $this->_loggedIn());
    $this->set('users_username', $this->_usersUsername());
}

如果您的“默認驗證”停止,則那里出了點問題。 如果模型中的before過濾器中包含某些內容,請確保它們返回true。 我建議您為此編寫一個單元測試。

您絕對不必在控制器中執行!empty檢查。 無論如何,整個代碼塊都可以減少到約6行。 其中大多數應納入模型。

檢查此插件或查看其代碼以了解想法。 https://github.com/CakeDC/users/

從user_controller.php文件中刪除以下代碼。

 else {
        $this->Session->setFlash('Incorrect username/password combination.','default',array('class'=>'flash_red'));
        $this->redirect(array('controller'=>'users', 'action'=>'login', 'admin'=>FALSE));
    }

這將頁面循環回登錄操作,沒有數據,因此也沒有驗證。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM