CodeIgniter Forums
building an efficient admin control panel - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: building an efficient admin control panel (/showthread.php?tid=4600)

Pages: 1 2 3


building an efficient admin control panel - El Forum - 12-06-2007

[eluser]A.M.F[/eluser]
thank u very much, i appriciate it


building an efficient admin control panel - El Forum - 12-06-2007

[eluser]JOKERz[/eluser]
i try to use your method

MY_Controller.php
Code:
class Admin_Controller extends Controller {
    function Admin_Controller() {
        parent::Controller();
    }
}

class Public_Controller extends Controller {
    function Public_Controller() {
        parent::Controller();
    }
}

admin.php
Code:
class Admin extends Admin_Controller {
    function Admin() {
        parent::Admin_Controller();
    }
    function index(){
        echo "this is admin.php";
    }
    function logout() {
        $this->session->destroy();
        redirect('', 'refresh');
    }
}

when i go to /admin i got "Fatal error: Class 'Admin_Controller' not found in \system\application\controllers\admin.php on line 2"

explain it please....


building an efficient admin control panel - El Forum - 12-07-2007

[eluser]JOKERz[/eluser]
guys...?


building an efficient admin control panel - El Forum - 12-07-2007

[eluser]Michael Wales[/eluser]
Where did you place MY_Controller.php? It should be in application/libraries/.


building an efficient admin control panel - El Forum - 12-07-2007

[eluser]JOKERz[/eluser]
SMOOTH!!
Thanx for your help!!!


building an efficient admin control panel - El Forum - 12-07-2007

[eluser]Phil Sturgeon[/eluser]
Thats a damn site easier than my hooks method... Good stuff.


building an efficient admin control panel - El Forum - 12-07-2007

[eluser]sandwormusmc[/eluser]
Ok, this is pretty complex, but I think it's a flexible and powerful solution:

Calling the MyAuth Class from the main controller:

Code:
/*
    Originally coded by Charlie Dumont for Detroit Public Schools - Summer 2007
    Modified and completed for Detroit Public Schools by Matt Moldvan - Fall 2007
*/
        $this->params = array(
            'AppName'    => 'UAMS',
            'AuthMethod' => 'LDAPAuth',
            'RolesBased' => FALSE, // SET TO TRUE TO CHECK ROLES
            'RolesType'  => 'LocalRoles'
        );
        $this->load->library('MyAuth', $this->params);

MyAuth Class (allows for different "AuthTypes" which dictates which custom auth library it will call, we are using LDAP at our site):

Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/*
    Originally coded by Charlie Dumont for Detroit Public Schools - Summer 2007
    Modified and completed for Detroit Public Schools by Matt Moldvan - Fall 2007
*/

class MyAuth {
    public $CI;
    public $isRoles;
    public $authFailure = '';
    protected $authType;
    protected $params;
    protected $callingFunction;
    private $roles;
    private $userArray;
    private $username;
    private $password;

    public function __construct($params) {
        $this->CI=&get;_instance();
        $this->params = $params;
        // print_r($this->CI=& get_instance());
        /*echo '<pre>';
        print_r($this->CI);
        echo '</pre>';*/
        $authMethod = $params["AuthMethod"];
        $this->CI->load->library($authMethod);
        // this kludginess is because CI insists that libraries be all lowercase when called
        $authMethod = strtolower ($authMethod);
        $this->authType =& $this->CI->$authMethod;
        // if Roles based we load the roles class and set a static variable
        if ($params['RolesBased']) {
            $this->isRoles = TRUE;
            $this->_loadRoles();
        }
        $this->username=$this->CI->input->post("username");
        $this->password=$this->CI->input->post("password");
    }

    public function check($path='') {
        // Find the calling function for roles based validation
        $backtrace = debug_backtrace();
        $this->callingFunction = $backtrace[1]['function'];
        $username = $this->CI->input->post("username");
        $params=array('username'=>$username);
        $this->_setUserArray($params);

        // Check session, cookie, or post variables
        if ($this->_isValidSession() || $this->_isValidLogin()) {
            $username = $this->CI->session->userdata('username');
            if ($this->isRoles) {
                // echo "<br />checking roles";
                $this->CI->roles->checkRoleAgainstAction($this->callingFunction, $this->CI->session->userdata('role'));
            }
            $params=array(
              'username'=>$username,
              'prevAction'=>'login',
              'action'=>'default',
              'loggedIn'=>TRUE
            );
            $this->_setUserArray($params);
            return TRUE;
        }
        // echo "this is the calling function: " . $backtrace[1]['function'] . " and this is the URI Path:$path";

        // if not available or valid offer login screen

        $data = array(
            'actionPath' =>$path,
            'error'      =>$this->authFailure,
            'header'     =>$this->CI->load->view($this->params['AppName'].'_header','',true),
            'footer'     =>$this->CI->load->view($this->params['AppName'].'_footer','',true)
        );

        $this->CI->load->vars($data);
        $this->CI->load->view('login.php',$data);
        $string = $this->CI->output->get_output();
        $this->CI->output->set_output($string);
        // $this->CI->load->view($this->params['AppName'] . '_footer');
        exit($string);
    }

    public function logout() {
        $newdata = array(
          'username' => 0,
          'action'   => 'default',
          'loggedIn' => FALSE
        );

        $this->_setUserArray($newdata);
        $this->CI->load->view('logout');
    }

    public function get_username() {
        return $this->CI->session->userdata('username');
    }

    public function get_role() {
        return $this->CI->session->userdata('role');
    }

    private function _loggedIn() {
        return $this->CI->session->userdata('loggedIn');
    }

    private function _isValidSession() {
        if($this->CI->session->userdata('loggedIn')) {
            return TRUE;
        }
        else {
            return FALSE;
        }
    }

    private function _isValidLogin() {
        $username = $this->CI->input->post("username");
        $password = $this->CI->input->post("password");

        if (strlen($username) < 1) {
            return FALSE;
        }

        if ($this->authType->verifyLogin($username, $password) ) {
            return TRUE;
        }
        else {
            $this->authFailure='There was a problem with your LDAP credentials.';
            return FALSE;
        }
    }

    private function _setUserArray($params) {
        if ($this->isRoles) {
            $role = $this->CI->roles->getUserRole($username);
            $params['role']=$role;
        }
        $this->CI->session->set_userdata($params);
    }

    private function _loadRoles() {
        $this->CI->load->library("Roles", $this->params);
    }
}
?&gt;

Running out of allowed length for this post ...


building an efficient admin control panel - El Forum - 12-07-2007

[eluser]Michael Wales[/eluser]
Quote:Thats a damn site easier than my hooks method… Good stuff.

Yeah - I'm not a big fan of the hooks method. There is no "real" way to understand what is occurring if you are just looking at the source.

Well, not until someone says, "Uh... I'm usings, go look here..."


building an efficient admin control panel - El Forum - 12-07-2007

[eluser]sandwormusmc[/eluser]
Local Roles Model (used to check if the currently logged in user has priveleges to run the PHP function being called):
Code:
&lt;?php
/*
    Originally coded by Charlie Dumont for Detroit Public Schools - Summer 2007
    Modified and completed for Detroit Public Schools by Matt Moldvan - Fall 2007
*/
class LocalRoles_Model extends Model {

  function Localroles_model() {
    parent::Model();
  }
  function get_NameByUserID($User_id) {
    $result = $this->db->query("SELECT userLDAP FROM Users WHERE User_id=$User_id LIMIT 1");
    if ($result->num_rows()) {
        $row = $result->row();

        $userLDAP = $row->userLDAP;
        return $userLDAP;
        }
  }
  function get_UserIDByName($username) {
    $result = $this->db->query("SELECT User_id FROM Users WHERE userLDAP='$username' LIMIT 1");
    if ($result->num_rows()) {
    $row = $result->row();
    
    $User_id = $row->User_id;
    return $User_id;
    }
  }
  function getUserRoleByUserName($username) {
    $role = 0;
    $results = $this->db->query("SELECT Role_id FROM Users WHERE userLDAP='$username'");
    if ($results->num_rows() > 0) {
      $temp = $results->row(0);
      $role = $temp->Role_id;
    }
    return $role;
  }

  function getFunctionIdByName($functionName) {
    $result = $this->db->query("SELECT Function_id FROM Functions WHERE FunctionName='$functionName'");
    if ($result->num_rows() > 0) {
      $temp = $result->row(0);
      return $temp->Function_id;
    } else {
      return;
    }
  }

  function getPermissionsByFunctionAndRole($functionID, $roleID) {
// echo "<br/> FunctionID: $functionID, RoleID:$roleID";
    $result = $this->db->query("SELECT isAllowed FROM FunctionsToRoles WHERE Role_id='$roleID' AND Function_id='$functionID'");
    if ($result->num_rows() > 0) {
      $temp = $result->row(0);
      return $temp->isAllowed;
    } else {
      return;
    }
  }

}
?&gt;

Roles library:
Code:
&lt;?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/*
    Originally coded by Charlie Dumont for Detroit Public Schools - Summer 2007
    Modified and completed for Detroit Public Schools by Matt Moldvan - Fall 2007
*/

class Roles {

  var $CI;
  var $params;
  var $rolesModel;

  function Roles($params) {
    $this->params = $params;
    $this->CI =& get_instance();
    $roleLoc = $this->params['RolesType'] . "_model";
    $this->CI->load->model($roleLoc , '', TRUE);
    $this->rolesModel =& $this->CI->$roleLoc;
  }

  function getUserRole($username) {
    return $this->rolesModel->getUserRoleByUserName($username);
  }

  function checkRoleAgainstAction($action, $role) {
// echo "<br/>$action and RoleID:$role";
    $functionID = $this->rolesModel->getFunctionIdByName($action);
// echo "<br/> FunctionID: $functionID";
    // Need to check functionID for a null and throw an error message
    if ($functionID == '') { $this->_showImproperlyConfiguredRole($action); }
    //check function id against role for isAllowed
    $isAllowed = $this->rolesModel->getPermissionsByFunctionAndRole($functionID, $role);
// echo "<br/>$isAllowed :P";
    if ($isAllowed) { return 1; }
    else { $this->_showInsufficientRights(); }
  }

  function _showInsufficientRights() {
    $this->_exitWithError("Insufficient Rights");
  }

  function _showImproperlyConfiguredRole($action) {
    $this->_exitWithError("$action is not properly configured in the permissions systems");
  }

  function _exitWithError($errorString) {
    $data['error'] = $errorString;
    $data['header'] = $this->CI->load->view($this->params['AppName'] . '_header', '', true);
    $data['footer'] = $this->CI->load->view($this->params['AppName'] . '_footer', '', true);
    $this->CI->load->vars($data);
    $this->CI->load->view("improperPermissions.php");
    $string = $this->CI->output->get_output();
    $this->CI->output->set_output($string);
    exit($string);
  }

}

?&gt;

So basically, each function being called (CI function) is checked by debug_backtrace(), then the return value from that is checked against a database table that has a list of all user roles and the privileges they have.

There should be 3 tables: Roles (role_id, role_name), Functions (function_id, function_name), and RolesToFunctions (role_id,function_id,isAllowed[enum 0 or 1]). In the table you're using to track your users, you would insert their role_id, then make the corresponding entries in the related tables.

Hope that helps, even though it is pretty complex ... let me know what you think.

If nothing else, it can at least spur some discussion and get you thinking.


building an efficient admin control panel - El Forum - 12-07-2007

[eluser]JOKERz[/eluser]
in admin.php
Code:
class Admin extends Admin_Controller {
    function Admin() {
        parent::Admin_Controller();
    }
    function index(){
        echo "this is admin.php";
    }
    function logout() {
        $this->session->destroy();
        redirect('', 'refresh');
    }
}

how to use logout function?
when i go to "admin/logout" it return 404 Not Found

so i try to create admin_logout.php and add this code
Code:
class Admin_logout extends Admin_Controller{

    function Admin_logout(){
        parent::Admin_Controller();
    }
    function index(){
        $this->logout();
    }
}

But still return error....