开发者

Checking auth for entire site section (multiple controllers)

开发者 https://www.devze.com 2023-03-16 14:03 出处:网络
My login-protected members area has many sub sections and controllers. For checking that the user is logged in and allowed to be there, I was just going to place my auth->is_logged_in() method in

My login-protected members area has many sub sections and controllers.

For checking that the user is logged in and allowed to be there, I was just going to place my auth->is_logged_in() method in the constructor of each of those controllers.

Would it be worthwhile creating a base controller that has this check in it and then exten开发者_如何学运维ding on that for all members area controllers? (best practice?)


I would argue yes on the base controller. You can add additional checks too.

I suggest you call it a Secured_Controller (or something like that), make the constructor of the secured controller take an (optional) access level (so you can have some for just logged in users, and some for admins, etc...)

Also make it take no access level (but provide a gaurd method so you can gaurd specific methods in a controller and let others run free.

Example:

Admin Controller

class Admin_Controller extends Secure_Controller
{
    public __construct()
    {
        parent::__construct(ACCESS_LEVEL_ADMIN);
    }
}

Partially Secured Controller

class Partial_Controller extends Secure_Controller
{
    public __construct()
    {
        parent::__construct();
    }

    public function Index() 
    {
        $this->GaurdPermissions(ACCESS_LEVEL_ADMIN); // Would redirect if not enough permissions

    }
}


I created Auth library for this

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Auth
{
    private $CI;
    private $redirect;

    function __construct()
    {
        $this->CI =& get_instance();
        $this->redirect = 'home/login';
    }

    function _redirect($redirect, $rurl)
    {
        redirect(($rurl == '') ? $this->redirect : $rurl);
    }

    function check_login($redirect = FALSE, $rurl = '')
    {
        if($this->CI->session->userdata('logged') == TRUE) {
            return TRUE;
        }
        $this->_redirect($redirect, $rurl);
    }

    function check_admin($redirect = FALSE, $rurl = '')
    {
        if($this->CI->session->userdata('user_type') == 'administrator') {
            return TRUE;
        }
        $this->_redirect($redirect, $rurl);
    }
}
?>

And this one is the User Controller

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users extends CI_Controller
{
    function __construct()
    {
        parent::__construct();

        $this->load->library('auth');
        // second param is optional // will redirect if not admin //
        $this->auth->check_admin(TRUE, 'admin/login');
    }

Hope this helps you, let us know if there anything... Thanks!!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号