如何在codeigniter中分隔管理员和用户?

时间:2017-02-14 09:58:29

标签: php codeigniter-3

我有两个页面用于管理员和用户。当管理员登录时,它将重定向到http://localhost/ci3/admin/Adminhomepage,当用户登录时,它将重定向到http://localhost/ci3/user/Userhomepage。以用户身份登录后,如果我更改了此http://localhost/ci3/admin/Adminhomepage的网址,则会直接转到管理主页。我希望它会转到管理员登录页面http://localhost/ci3/admin/Adminlogin。我有adminI的userId和权限,如view,edit,add和deleteRole。在这个任何人都设置为1然后他是管理员,否则他是用户。我想在Admin_controller中编写该逻辑。

Admin_controller

<?php
class Admin_controller extends CI_Controller{
    function __construct()
    {
        parent::__construct();
        $this->load->model("Adminmodel","",true);   

        $userId =  $this->session->userdata('cp_adminid');

        $toCheck = $this->Adminmodel->tocheckadmin($userId);            
    }
}
?>

Admin_model

public function tocheckadmin($userId){
        $sql = "SELECT * FROM users u
            INNER JOIN roles r
            ON r.roleId = u.roleId
            INNER JOIN permissions p
            ON p.roleId = r.roleId
            INNER JOIN module m
            ON m.moduleId = p.moduleId
            WHERE userId= $userId
            AND (p.view == 1 or p.add == 1 or p.edit == 1 or p.deleteRole == 1)";
}

2 个答案:

答案 0 :(得分:1)

因此,在主index.php文件中更改应用程序路径,即更改此:

$application_folder = 'application';

要:

`$application_folder = 'application/frontend';`

对于管理应用程序创建一个目录,让我们说后端,将index.php文件的副本放在那里并使其指向管理员应用程序,所以:

$application_folder = 'application/admin';

要完成操作,请将.htaccess文件的副本放在后端目录中,并将其更改为使用此目录作为重写的基础:

RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /backend/index.php/$1 [L]

答案 1 :(得分:0)

我通过在登录时在会话变量中设置用户权限来解决此问题。

$data = ['is_admin'     => true];
$this->session->set_userdata($data);

然后在管理区域的控制器中,我检查了__constructor()方法

    /**
     * login protect
     */
    public function __construct()
    {
        if (!$this->session->userdata('is_admin')) {
            redirect('admin/account/login');
        }
    }

以下是包含评论的示例的更新代码

/**
 * tocheckadmin
 */
public function tocheckadmin($admin_id)
{
    // get the admin
    $sql = "SELECT * FROM users u
            INNER JOIN roles r
            ON r.roleId = u.roleId
            INNER JOIN permissions p
            ON p.roleId = r.roleId
            INNER JOIN module m
            ON m.moduleId = p.moduleId
            WHERE userId= $userId
            AND (p.view == 1 or p.add == 1 or p.edit == 1 or p.deleteRole == 1)";
    $query = $this->db->query($sql);
    return $query->row(); // use row() to return a single object
}

/**
 *
 */
class Admin_controller extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model("Adminmodel","",true);

        $userId =  $this->session->userdata('cp_adminid');

        $toCheck = $this->Adminmodel->tocheckadmin($userId);

        if ($toCheck === false) {

            // then the user is not an admin
            // redirect to the admin login

        }
    }
}