普通网友 2013-06-16 23:04
浏览 38
已采纳

cakephp2 Auth Component,包含2个用户表

I have a cakephp 2.0 application with 'users' and 'administrators' but they are organized into 2 different tables, how can I check these 2 tables to login using Auth Component using the same form? I tried with this solution but you have to do 2 different forms, one for each model, is there a way to force the authentication to look inside two tables?

  • 写回答

1条回答 默认 最新

  • donglieshe4692 2013-06-18 11:09
    关注

    Ok, after some tries I sort this out, first I defined 2 authenticate , one for users and one for administrators,like this:

    App::uses('FormAuthenticate', 'Controller/Component/Auth');
    class AdministratorAuthenticate extends FormAuthenticate {
    }
    

    and

    App::uses('FormAuthenticate', 'Controller/Component/Auth');
    class UserAuthenticate extends FormAuthenticate {
    }
    

    now we can define the components variable in AppController like this:

    public $components = array(
        'Session',
        'Auth' => array(
            'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'home'),
            'authenticate' => array(
                    'Administrator' => array(
                        'fields' => array('username' => 'email'),
                        'userModel' => 'Administrator'
                    ),
                    'User' => array(
                        'fields' => array('username' => 'email'),
                        'userModel' => 'User'
                    )
                    )
        )
    );
    

    then in the login method of access controller I try the administrator login and then the users login in this way:

    if ($this->Auth->login()) {
    $this->redirect(array('controller'=>'administrator','action'=>'index'));
    } 
    else {
    $this->request->data['Users']=$this->request->data['Administrator'];
    unset($this->request->data['Administrator']);
    if ($this->Auth->login()) {
        $this->redirect(array('controller'=>'user','action'=>'index'));
    }
        else                            
          $this->Session->setFlash(__('Invalid username or password, try again'));
    }
    

    The key here is modify the request->data array substituting the userModel 'Administrator' with 'User'

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错