在CakePHP中使用不同的用户角色登录?

问题描述:

我正在制作一个使用CakePHP的系统,其中用户可以是A,B或C,就像学生,老师和其他角色一样。是否有可能让他们都通过1链接登录?所以不是/学生/登录和/教师/登录,但像www.somewebsite /登录所有这些?在CakePHP中使用不同的用户角色登录?

Read this tutorial,它完全涵盖了你所要求的。也read this section

对于不同类型的用户拥有不同的控制器根本没有任何意义,您只需复制代码即可。如果您需要根据角色采取不同的操作,则可以在登录方法中通过调用另一种方法(如login()方法中的afterStudentLogin())来执行此操作,并在其中执行特定于角色的操作。原因在于单个方法应该总是只执行一项任务,因此您可以使用单独的方法将特定于角色的代码与其分离。

public function login() { 
    if ($this->Auth->user()) { 
     /* ... */ 
     $callback = 'after' . $this->Auth->user('role') . 'Login'); 
     $this->{$callback}($this->Auth->user()); 
     /* ... */ 
    } 
} 

即使用户类型非常不同,他们都会共享一个共同的东西:登录。在这种情况下有一个用户表,例如student_profils表和teacher_profiles表。如果差异只是几个字段,我会把它们全部放在一个表中,如profiles

如果你想要/登录而不是/用户/登录,你应该使用routing

Router::connect(
    '/login', 
    array(
     'controller' => 'users', 
     'action' => 'login' 
    ) 
); 

您还可以采取look at this Users plugin,其中涵盖了许多常见的用户相关任务。和here is a simple multi-role authorization adapter

+0

您也可以使用[TinyAuth]给出(http://www.dereuromark.de/2011/12/18/tinyauth作为Auth适配器的最快和最容易的授权for cake2 /)。如果你只有这三个角色,那将是小菜一碟。 – mark

+0

谢谢。并感谢@mark – Loolooii

根据用户组的简单基本的登录功能将类似于下面

<?php 
public function login() {  

     //if user already logged in call routing function... 
     if($this->Session->read('Auth.User')) { 
      $this->routing(); 
     } 

     if ($this->request->is('post')) { 

      if ($this->Auth->login()) { 

       //if user status is active... 
       if ($this->Auth->user('status') == 1){ 

        //redirect users based on his group id... 
        if($this->Auth->User('group_id')==1){ 
         $this->redirect($this->Auth->redirect('/admins/dashboard')); 
        } 
        else if($this->Auth->User('group_id')==2){ 
         $this->redirect($this->Auth->redirect('/teachers/dashboard')); 
        } 
        else if($this->Auth->User('group_id')==3){ 
         $this->redirect($this->Auth->redirect('/students/dashboard')); 
        } 
       } 
       else{ 

        $this->Session->delete('User'); 
        $this->Session->destroy(); 
        $this->Session->setFlash('Your account is not yet activated. Please activate your account to login.', 'warning'); 
       } 

      } 
      else { 
       $this->Session->setFlash('Your username or password was incorrect.', 'error'); 
      } 
     } 
    } 

//just route the loggedin users to his proper channel... 
public function routing() { 

     if($this->Session->read('Auth.User.Group.id') == 1) { 
      $this->redirect('/admins/dashboard'); 
     } 
     else if($this->Session->read('Auth.User.Group.id') == 2) { 
      $this->redirect('/teachers/dashboard'); 
     } 
     else if($this->Session->read('Auth.User.Group.id') == 3) { 
      $this->redirect('/students/dashboard'); 
     } 
     else { 
      $this->Session->destroy(); 
      $this->redirect('/'); 
     } 
    } 
?>