CakePHP的认证/注册用的,而不是'用户''员工' [英] CakePHP Authentication/login with 'Employee' instead of 'User'

查看:285
本文介绍了CakePHP的认证/注册用的,而不是'用户''员工'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让我的登录工作,但我似乎遇到了问题。可能有人请帮忙吗?我使用的是员工作为数据库的用户。下面是我的code代表的AppController,EmployeeController,员工和login.ctp:

应用程序控制器:

 类AppController的扩展控制器{    公共$组件=阵列(
    DebugKit.Toolbar',
    会话,
    '验证'=>阵列(
        loginRedirect'=>阵列('控制'=>'员工','行动'=>'指数'),
        logoutRedirect'=>阵列('控制'=>'员工','行动'=>'登录'),
        authError'=> 你必须先登录才能查看此页。,
        loginError'=> 无效的用户名或密码进入,请重试。    ));//只只允许登录控制器
公共职能beforeFilter(){
    $这个 - > Auth->允许('密码');
}
}

员工控制器:

 类EmployeesController扩展的AppController {
//..other code
/ **
 * 组件
 *
 * @var阵列
 * /
    //公共$组分=阵列('分页程序');
    公共$ PAGINATE =阵列(
        '限制'=> 25,
        '条件'=>阵列('状态'=>'1'),
        秩序= GT;阵列('Employee.employee_username'=>ASC)
    );    公共职能beforeFilter(){
        父:: beforeFilter();
        $这个 - > Auth->允许('登录','加');    }    公共职能登录(){        //如果已经登录的,重定向
        如果($这个 - >会话级>检查('Auth.Employee')){
            $这个 - >重定向(阵列('行动'=>'指数'));
        }        //如果我们得到的信息后,尝试验证
        如果($这个 - >请求 - '是('后')){
            如果(这 - $> Auth->登录()){
                $这个 - >会话级> setFlash(__('欢迎'$这个 - 方式>&Auth- GT;用户(用户名)));
                $这个 - >重定向($这个 - > Auth->的redirectUrl());
            }其他{
                $这个 - >会话级> setFlash(__(无效的用户名或密码'));
            }
        }
    }    公共职能注销(){
        $这个 - >重定向($这个 - > Auth->注销());
    }/ **
 *指数法
 *
 * @返回无效
 * /
    公共功能指数(){
        $这个 - > =分页阵列(
            '限制'=> 6,
            秩序= GT;阵列('Employee.employee_username'=>ASC)
        );
        $员工= $这个 - >分页('员工');
        $这个 - >集(紧凑型('雇员'));
    }

员工型号:

  Employee类扩展AppModel {
//..other code
功能isUniqueUsername($检查){        $ USERNAME = $这个 - >找到(
            '第一',
            阵列(
                '域'=>阵列(
                    '员工ID',
                    Employee.employee_username
                )
                '条件'=>阵列(
                    Employee.employee_username'=> $检查[用户名]
                )
            )
        );        如果(!空($用户名)){
            如果(这 - $>数据[$这个 - >别名] ['身份证'] == $用户名['雇员'] ['身份证']){
                返回true;
            }其他{
                返回false;
            }
        }其他{
            返回true;
        }
    }    / **
     * isUniqueEmail前
     * @参数数组$选项
     * @返回布尔
     * /
    功能isUniqueEmail($检查){        $电子邮件= $这个 - >找到(
            '第一',
            阵列(
                '域'=>阵列(
                    '员工ID'
                )
                '条件'=>阵列(
                    Employee.employee_email'=> $检查[电子邮件]
                )
            )
        );        如果(!空($电子邮件)){
            如果(这 - $>数据[$这个 - >别名] ['身份证'] == $电子邮件['雇员'] ['身份证']){
                返回true;
            }其他{
                返回false;
            }
        }其他{
            返回true;
        }
    }    公共职能alphaNumericDashUnderscore($检查){
        // $ data数组使用表单字段名传入的键
        //要提取的值以使该函数通用
        $值= array_values​​($检查);
        $价值= $值[0];        返回preg_match('/ ^ [A-ZA-Z0-9 _ \\ - ] * $ /',$值);
    }    公共职能equaltofield($支票,$ otherfield)
    {
        //获取字段的名称
        $ FNAME ='';
        的foreach($支票$关键=> $值){
            $ FNAME = $关键;
            打破;
        }
        返回$这个 - >数据[$这个 - >名称] [$ otherfield] === $这个 - >数据[$这个 - >名称] [$ FNAME];
    }    / **
     *保存前
     * @参数数组$选项
     * @返回布尔
     * /
     公共职能beforeSave($选项=阵列()){
        如果(使用isset($这个 - >数据[$这个 - >别名] ['密码'])){
        $这个 - >数据[$这个 - >别名] ['密码'] = $ passwordHasher->哈希(
            $这个 - >数据[$这个 - >别名] ['密码']
        );
    }
    //如果我们得到一个新的密码,它哈希        如果(使用isset($这个 - >数据[$这个 - >别名] ['password_update'])){            $这个 - >数据[$这个 - >别名] ['密码'] = AuthComponent ::密码($这个 - >数据[$这个 - >别名] ['password_update']);        }
    //回退到我们的父        回报父母:: beforeSave($选项);
    //返回true;
    }}

登录页面:

 < D​​IV CLASS =员工形成>
<?PHP的echo $这个 - >会话级>闪光('权威性'); ?>
<?PHP的echo $这个 - >&形式 - GT;创建('雇员'); ?>
    <&字段集GT;
        <传奇>
            < PHP的echo __('请输入您的用户名和密码'); ?>
        < /传说>
        <?PHP的echo $这个 - >&形式 - GT;输入(用户名);
        回声$这个 - >&形式 - GT;输入('密码');
    ?>
    < /字段集>
<?PHP的echo $这个 - >&形式 - GT;结束(__('登录')); ?>
< / DIV>


解决方案

1.Adapt关于的usermodel 字段中输入您验证组件的配置 passwordHasher

 公共$组件=阵列(
    DebugKit.Toolbar',
    会话,
    '验证'=>阵列(
        loginRedirect'=>阵列('控制'=>'员工','行动'=>'指数'),
        logoutRedirect'=>阵列('控制'=>'员工','行动'=>'登录'),
        authError'=> 你必须先登录才能查看此页。,
        loginError'=> 无效的用户名或密码进入,请重试。,
        '身份验证'=>阵列(
            形= GT;阵列(
            '域'=>阵列('用户名'= GT;用户名,密码= GT;'密码'),
            '的usermodel'=>'员工',
            passwordHasher'=> 您的密码散列器的名称'
            ))
    ));

2.Regarding CakePHP's code convetion控制器重命名为 EmployeeController

3.In您的员工的模型,而不是你的 isUniqueUsername isUniqueEmail 您更好地使用有效性规则 isUnique设置

4.使用创建的密码和密码更新相同的密码散列器

I am trying to get my login working but I seemed to run into a problem. Could someone please help? I am using the 'Employees' as the user of the database. Below is my code for AppController, EmployeeController, Employee and login.ctp:

App Controller:

class AppController extends Controller {

    public $components = array(
    'DebugKit.Toolbar',
    'Session',
    'Auth' => array(
        'loginRedirect' => array('controller' => 'employees', 'action' => 'index'),
        'logoutRedirect' => array('controller' => 'employees', 'action' => 'login'),
        'authError' => 'You must be logged in to view this page.',
        'loginError' => 'Invalid Username or Password entered, please try again.'

    ));

// only allow the login controllers only
public function beforeFilter() {
    $this->Auth->allow('login');
}
}

Employees Controller:

class EmployeesController extends AppController {
//..other code
/**
 * Components
 *
 * @var array
 */
    //public $components = array('Paginator');
    public $paginate = array(
        'limit' => 25,
        'conditions' => array('status' => '1'),
        'order' => array('Employee.employee_username' => 'asc' ) 
    );

    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('login','add'); 

    }



    public function login() {

        //if already logged-in, redirect
        if($this->Session->check('Auth.Employee')){
            $this->redirect(array('action' => 'index'));      
        }

        // if we get the post information, try to authenticate
        if ($this->request->is('post')) {
            if ($this->Auth->login()) {
                $this->Session->setFlash(__('Welcome, '. $this->Auth->user('username')));
                $this->redirect($this->Auth->redirectUrl());
            } else {
                $this->Session->setFlash(__('Invalid username or password'));
            }
        } 
    }

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

/**
 * index method
 *
 * @return void
 */
    public function index() {
        $this->paginate = array(
            'limit' => 6,
            'order' => array('Employee.employee_username' => 'asc' )
        );
        $employees = $this->paginate('Employee');
        $this->set(compact('employees'));
    }

Employee Model:

class Employee extends AppModel {
//..other code
function isUniqueUsername($check) {

        $username = $this->find(
            'first',
            array(
                'fields' => array(
                    'Employee.id',
                    'Employee.employee_username'
                ),
                'conditions' => array(
                    'Employee.employee_username' => $check['username']
                )
            )
        );

        if(!empty($username)){
            if($this->data[$this->alias]['id'] == $username['Employee']['id']){
                return true; 
            }else{
                return false; 
            }
        }else{
            return true; 
        }
    }

    /**
     * Before isUniqueEmail
     * @param array $options
     * @return boolean
     */
    function isUniqueEmail($check) {

        $email = $this->find(
            'first',
            array(
                'fields' => array(
                    'Employee.id'
                ),
                'conditions' => array(
                    'Employee.employee_email' => $check['email']
                )
            )
        );

        if(!empty($email)){
            if($this->data[$this->alias]['id'] == $email['Employee']['id']){
                return true; 
            }else{
                return false; 
            }
        }else{
            return true; 
        }
    }

    public function alphaNumericDashUnderscore($check) {
        // $data array is passed using the form field name as the key
        // have to extract the value to make the function generic
        $value = array_values($check);
        $value = $value[0];

        return preg_match('/^[a-zA-Z0-9_ \-]*$/', $value);
    }

    public function equaltofield($check,$otherfield) 
    { 
        //get name of field 
        $fname = ''; 
        foreach ($check as $key => $value){ 
            $fname = $key; 
            break; 
        } 
        return $this->data[$this->name][$otherfield] === $this->data[$this->name][$fname]; 
    } 

    /**
     * Before Save
     * @param array $options
     * @return boolean
     */
     public function beforeSave($options = array()) {
        if (isset($this->data[$this->alias]['password'])) {
        $this->data[$this->alias]['password'] = $passwordHasher->hash(
            $this->data[$this->alias]['password']
        );
    }
    // if we get a new password, hash it

        if (isset($this->data[$this->alias]['password_update'])) {

            $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password_update']);

        }
    // fallback to our parent

        return parent::beforeSave($options);
    //return true;
    }

}

Login page:

<div class="employees form">
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('Employee'); ?>
    <fieldset>
        <legend>
            <?php echo __('Please enter your username and password'); ?>
        </legend>
        <?php echo $this->Form->input('username');
        echo $this->Form->input('password');
    ?>
    </fieldset>
<?php echo $this->Form->end(__('Login')); ?>
</div>

解决方案

1.Adapt the config of your Auth component regarding userModel, fields and passwordHasher:

public $components = array(
    'DebugKit.Toolbar',
    'Session',
    'Auth' => array(
        'loginRedirect' => array('controller' => 'Employee', 'action' => 'index'),
        'logoutRedirect' => array('controller' => 'Employee', 'action' => 'login'),
        'authError' => 'You must be logged in to view this page.',
        'loginError' => 'Invalid Username or Password entered, please try again.',
        'authenticate' => array(
            'Form' => array(
            'fields' => array('username' => 'username', 'password' => 'password'),
            'userModel'=>'Employee',
            'passwordHasher' => 'name of your password hasher'
            ))
    ));

2.Regarding CakePHP´s code convetion rename your controller to EmployeeController

3.In your Employee model instead your isUniqueUsername and isUniqueEmail you better use validation rule isUnique

4.Use same password hasher for creating password and update password

这篇关于CakePHP的认证/注册用的,而不是'用户''员工'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆