根据Codeigniter中的用户角色重定向到页面 [英] Redirect to a page based on user roles in codeigniter

查看:97
本文介绍了根据Codeigniter中的用户角色重定向到页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在使用codeigniter进行用户登录身份验证。

Am working on a user login authentication with codeigniter.

登录脚本的工作原理很棒。我的问题是,当用户登录后,我希望根据用户角色将其重定向到页面

The login script works great. My question is, when a user is logged in I want the user to be redirected to a page based on his user roles

角色如下订户管理员客户端邮递员

User_model.php 如下所示:

class User_model extends CI_Model {

    public $status;
    public $roles;

    function __construct(){
        // Call the Model constructor
        parent::__construct();
        $this->status = $this->config->item('status');
        $this->roles = $this->config->item('roles');
    }

    public function insertUser($d)
    {
            $string = array(
                'firstname'=>$d['firstname'],
                'lastname'=>$d['lastname'],
                'phonenumber'=>$d['phonenumber'],
                'email'=>$d['email'],
                'roles'=>$this->roles[1],
                'status'=>$this->status[1],
                'password'=> '',
                'last_login'=> '',
                'created_at'=> '',
                'updated_at'=> ''
            );
            $q = $this->db->insert_string('users',$string);
            $this->db->query($q);
            return $this->db->insert_id();
    }

    public function isDuplicate($email)
    {
        $this->db->get_where('users', array('email' => $email), 1);
        return $this->db->affected_rows() > 0 ? TRUE : FALSE;
    }

    public function insertToken($user_id)
    {
        $token = substr(sha1(rand()), 0, 30);
        $date = date('Y-m-d');

        $string = array(
                'token'=> $token,
                'user_id'=>$user_id,
                'created'=>$date
            );
        $query = $this->db->insert_string('tokens',$string);
        $this->db->query($query);
        return $token . $user_id;

    }

    public function isTokenValid($token)
    {
       $tkn = substr($token,0,30);
       $uid = substr($token,30);

        $q = $this->db->get_where('tokens', array(
            'tokens.token' => $tkn,
            'tokens.user_id' => $uid), 1);

        if($this->db->affected_rows() > 0){
            $row = $q->row();

            $created = $row->created;
            $createdTS = strtotime($created);
            $today = date('Y-m-d');
            $todayTS = strtotime($today);

            if($createdTS != $todayTS){
                return false;
            }

            $user_info = $this->getUserInfo($row->user_id);
            return $user_info;

        }else{
            return false;
        }

    }

    public function getUserInfo($id)
    {
        $q = $this->db->get_where('users', array('id' => $id), 1);
        if($this->db->affected_rows() > 0){
            $row = $q->row();
            return $row;
        }else{
            error_log('no user found getUserInfo('.$id.')');
            return false;
        }
    }

    public function updateUserInfo($post)
    {
        $data = array(
               'password' => $post['password'],
               'last_login' => date('Y-m-d h:i:s A'),
               'created_at' => date('Y-m-d h:i:s A'),
               'updated_at' => date('Y-m-d h:i:s A'),
               'status' => $this->status[1]
            );
        $this->db->where('id', $post['user_id']);
        $this->db->update('users', $data);
        $success = $this->db->affected_rows();

        if(!$success){
            error_log('Unable to updateUserInfo('.$post['user_id'].')');
            return false;
        }

        $user_info = $this->getUserInfo($post['user_id']);
        return $user_info;
    }

    public function checkLogin($post)
    {
        $this->load->library('password');
        $this->db->select('*');
        $this->db->where('email', $post['email']);
        $query = $this->db->get('users');
        $userInfo = $query->row();

        if(!$this->password->validate_password($post['password'], $userInfo->password)){
            error_log('Unsuccessful login attempt('.$post['email'].')');
            return false;
        }

        $this->updateLoginTime($userInfo->id);

        unset($userInfo->password);
        return $userInfo;
    }

}

控制器的主要代码为见下文

The main code for controller is as seen below

defined('BASEPATH') OR exit('No direct script access allowed');

class Main extends CI_Controller {

        public $status;
        public $roles;

        function __construct(){
            parent::__construct();
            $this->load->model('User_model', 'user_model', TRUE);
            $this->load->library('form_validation');
            $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
            $this->status = $this->config->item('status');
            $this->roles = $this->config->item('roles');
        }

    public function index()
    {

            if(empty($this->session->userdata['email'])){
                redirect(site_url().'main/login/');
            }

            /*front page*/
            $data = $this->session->userdata;
            $this->load->view('header');
            $this->load->view('index', $data);
            $this->load->view('footer');
    }



        public function login()
        {

            $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
            $this->form_validation->set_rules('password', 'Password', 'required');

            if($this->form_validation->run() == FALSE) {
                $this->load->view('header');
                $this->load->view('login');
                $this->load->view('footer');
            }else{

                $post = $this->input->post();
                $clean = $this->security->xss_clean($post);

                $userInfo = $this->user_model->checkLogin($clean);

                if(!$userInfo){
                    $this->session->set_flashdata('flash_message', 'The login was unsucessful');
                    redirect(site_url().'main/login');
                }
                foreach($userInfo as $key=>$val){
                    $this->session->set_userdata($key, $val);
                }
                redirect(site_url().'main/');
            }

        }


        public function logout()
        {
            $this->session->sess_destroy();
            redirect(site_url().'main/login/');
        }


}


推荐答案

此答案可能不正确,因为它需要一些假设。

This answer may be off because it requires some assumptions.

假设:


  1. 每个用户只有一个角色

  2. $ userInfo->角色的值是字符串

  3. 要将授权用户发送到的控制器是 main

  4. main 控制器的方法与角色相同,例如
    'subscriber','admin','client','postman'

  1. There is only one "role" per user
  2. The value of $userInfo->role is a string
  3. The controller you want to send the authorized user to is main
  4. The methods of the main controller are named the same as the "role" e.g. 'subscriber', 'admin', 'client', 'postman'

如果以上任何一项为假,则此答案不起作用。

If any of the above is false then this answer won't work.

这是我建议的解决方案。

Here's my suggested solution. I'll make comments about it after this code.

public function login()
{
    $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
    $this->form_validation->set_rules('password', 'Password', 'required');

    if($this->form_validation->run())
    {
        $post = $this->input->post();
        //$clean = $this->security->xss_clean($post);

        $userInfo = $this->user_model->checkLogin($post);

        if( ! $userInfo)
        {
            $this->session->set_flashdata('flash_message', 'The login was unsucessful');
            redirect('main/login');
        }

        $this->session->set_userdata($userInfo);
        redirect('main/'.$userInfo->roles);
    }

    $this->load->view('header');
    $this->load->view('login');
    $this->load->view('footer');
}

您可能想知道为什么我要重新排列所有内容。好吧,主要是因为它消除了 if if 一起使用的必要。更少的代码是好的-对吗?

You're probably wondering why I rearranged everything. Well, mostly because it eliminates the need for an else to go with the if. Less code is good - right?

调用 redirect() 结束脚本执行表示重定向之后的任何代码都不会运行。因为 if($ this-> form_validation-> run()){代码块以对 redirect 该函数结束的地方。因此,您不需要 else 。如果验证失败,执行将直接转到视图加载代码。

A call to redirect() ends script execution meaning that any code after a redirect won't run. Because the if($this->form_validation->run()){ code block ends with a call to redirect that's where this function ends. So, you don't need an else. Should validation fail execution go straight to the view loading code.

您用于重定向的语法是错误的。 redirect()将根据您的配置文件值构建URL。 (此处的文档)因此,请确保 $ config ['base_url'] 设置正确。

Your syntax for redirect is wrong. redirect() will build the URL based on your config file values. (docs here) So, make sure $config['base_url'] is set correctly.

您的代码

redirect(site_url().'main/');

应写成

redirect('main/');

您可能会注意到我注释了这一行

You probably noticed that I commented out the line

$clean = $this->security->xss_clean($post);

大多数开发人员都会认为XSS预防应该在输出而不是输入上进行。 (关于XSS预防的信息,您想了解的更多信息此处。)

Most developers will argue that XSS prevention should be done on output, not on input. (More than you want to know about XSS prevention HERE.)

由于使用了输入数据来选择数据库记录,因此似乎值已被转义,并且您不存储输入就没有危险。使用 xss_clean()是资源密集型的,在这种情况下没有用。

Since the input data is being used to select a DB record, it appears the values are escaped, and you're not storing the inputs there is no danger. Using xss_clean() is resource intensive and not useful in this case.

我删除了以下循环

foreach ($userInfo as $key => $val)
{
    $this->session->set_userdata($key, $val);
}

并将其更改为

$this->session->set_userdata($userInfo);

如果您查看 set_userdata(),您会发现它几乎使用您创建的完全相同的代码。 (代码位于785行附近的 /system/core/Session/Session.php 中。)保持 DRY 并使用框架的工具集。 set_userdata()将接受一个关联数组并执行您需要做的事情。

If you look at the code for set_userdata() and you will find it pretty much uses the exact same code you created. (The code is in /system/core/Session/Session.php around line 785.) Stay DRY and use the framework's toolset. set_userdata() will accept an associative array and do what you need to be done.

因为 $ userInfo->角色是一个字符串,该字符串与您希望将其重定向到此调用的方法的名称匹配。

Because the value of $userInfo->roles is a string that matches the name of the method you want to redirect them to this call should do the trick.

redirect('main/'.$userInfo->roles);

如果 main 不是正确的控制者然后在上方进行更改。如果方法名称与角色值不匹配,则需要附加代码。

If main isn't the right controller then change it above. If the method names don't match the role values then additional code will be needed.

希望这很清楚并且很有帮助。

Hope this is clear and is helpful.

这篇关于根据Codeigniter中的用户角色重定向到页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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