Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

SEAuth Session Extension for Authorization

Derek Jones edited this page · 4 revisions
Clone this wiki locally

Hey everybody. This my my first bit of code to share, so please go easy on me ;) I was looking for something REALLY simple to do user validation / authorization. I didn't see it. So I made an extension to the Session class.

It works like this:

$this->session->login($username,$password);
$this->session->logout();
$this->session->auth($privilege_type_needed);

Login checks the user name and password, then loads the privileges in to the cookie.

Logout removes all privileges

Auth checks to see if the user has that privilege.

It has a config file called auth.php that needs the following: [quote]$user_table - The name of the database table to use for user lookup.

$user_name - This is the record where the user name is stored.

$password - This is the record where the user password is stored.

$session_auth - This is the variable saved in the cookie that validates the user is logged in.

$privilege - This is an array of boolean records to indicate if the user has permission to access various types of content.[/quote]

Here is a SUPER simple login page:

      function login(){
      $data = array();
      $data['user'] = $this->input->post('user');
      $data['password'] = $this->input->post('password');

      if ($data['user']) {
          $secure = $this->session->login($data['user'],$data['password']);
          if ($secure) {redirect('/authclients/admin');}
          else {show_error('Bad User Name or Password');}
        } else {$this->load->view('view_login');}
      }

Here is a SUPER simple logout page:

      function logout(){
        $this->session->logout();
      echo "logged out";
      }

Here is a SUPER simple admin page (with session authorization):

      function admin(){
        $user_is_admin = $this->session->auth('user_admin');
      if ($user_is_admin) {
        $this->load->view('view_admin');
      }
      else {
        show_error('Permission Denied');
      }
      }

I threw together the program quickly over the past two hours or so and tested it. It works great so far. I like it because it doesn't add too much extra code. Just make sure the session library is loaded and you're done. I didn't feel it was significant enough to need another library (though it could be made in to one in minutes).


Install instructions:

1. Install auth.php in to the /application/configs directory 

2. Install MY_Session.php in to the /application/librariess directory

3. Update the config.php according to the directions in the auth.php

4. Setup the session database

[u]/application/config/auth.php[/u]


<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| SEAuth - Session Extension for Authorization
| -------------------------------------------------------------------
| This is intended as a simple way to integrate session authorization
| in to any CodeIgniter application.
| $this->session->login($username,$password);
| $this->session->logout();
| $this->session->auth($privilege_type_needed);
| -------------------------------------------------------------------
| Created by Paul R. Dillinger of CR Solutions Group S.A.
| http://www.crsolutionsgroup.com/
| -------------------------------------------------------------------
| EXPLANATION OF VARIABLES
| -------------------------------------------------------------------
|
|    $user_table The name of the database table to use for user lookup.
|
| $session_auth This is the variable saved in the cookie that
| validates the user is logged in.
|
|    $user_name This is the record where the user name is stored.
|
|    $password This is the record where the user password is stored.
|
|    $privilege This is an array of boolean records to indicate if the
| user has permission to access this content.
*/

$user_table = "auth";
$session_auth = "logged_in";
$user_name = "username";
$password = "password";
$privilege = array('user_admin', 'user_member');
/*
| -------------------------------------------------------------------
| !!!!!!!!!!!!!!!!!!!!!!!!!! IMPORTANT !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
| -------------------------------------------------------------------
| Changes MUST be made to the application/config/config.php file
| -------------------------------------------------------------------
| THE APPLICATION REQUIRES THE SESSION DATABASE AND ENCRYPTION
| SEE THE USER GUIDE FOR MORE INFORMATION
| http://codeigniter.com/user_guide/libraries/sessions.html
| -------------------------------------------------------------------
|
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
| $config['encryption_key'] = "";
|
| This needs a 32 digit mix of random letters and numbers for example:
| 1q2W3e4R5t6Y7u8I9o0PZaXsCdVfBgNh
| Do not use the one above, just make a new on.
|
|--------------------------------------------------------------------------
| Session Variables
|--------------------------------------------------------------------------
|    $config['sess_encrypt_cookie']    = TRUE;
|    $config['sess_use_database']    = TRUE;
|    $config['sess_table_name']        = 'ci_sessions';
|
| -------------------------------------------------------------------
| MySQL Example for ci_sessions table below:
| -------------------------------------------------------------------
|

CREATE TABLE IF NOT EXISTS  `ci_sessions` (
session_id varchar(40) DEFAULT '0' NOT NULL,
ip_address varchar(16) DEFAULT '0' NOT NULL,
user_agent varchar(50) NOT NULL,
last_activity int(10) unsigned DEFAULT 0 NOT NULL,
PRIMARY KEY (session_id)
);

--
-- Sample Table structure for table `auth` database
--

CREATE TABLE IF NOT EXISTS `auth` (
  `id` int(10) NOT NULL auto_increment,
  `username` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `user_admin` bool NOT NULL default '0',
  `user_member` bool NOT NULL default '0',
  PRIMARY KEY  (`id`)
);

|
*/

/* End of file auth.php */
/* Location: ./system/application/config/auth.php */

[u]/application/libraries/My_Session.php[/u]


<?php
/*
| -------------------------------------------------------------------
| SEAuth - Session Extension for Authorization
| -------------------------------------------------------------------
| This is intended as a simple way to integrate session authorization
| in to any CodeIgniter application.
| $this->session->login($username,$password);
| $this->session->logout();
| $this->session->auth($privilege_type_needed);
| -------------------------------------------------------------------
| Created by Paul R. Dillinger of CR Solutions Group S.A.
| http://www.crsolutionsgroup.com/
| -------------------------------------------------------------------
*/
class MY_Session extends CI_Session {

    function MY_Session()
    {
        parent::CI_Session();
    }
///////////////////////////////////////////////////////////////////////////////
// Validates username and password info then begins the session              //
///////////////////////////////////////////////////////////////////////////////
    function login($user,$pass)
    {
          if ($this->CI->config->item('sess_encrypt_cookie') == TRUE AND $this->CI->config->item('sess_use_database') == TRUE AND $this->CI->config->item('sess_table_name') != '')
          {
             include(APPPATH.'config/auth'.EXT);
        // Call User Database $user_table
        $this->CI->load->database();
        $this->CI->db->where($user_name, $user);
        $this->CI->db->where($password, $pass);
        $query = $this->CI->db->get($user_table);
        if ($query->num_rows() == 1) {
          foreach ($query->result_array() as $row)
          {
            $userdata = array();
            $userdata[$session_auth] = TRUE;
            foreach ($privilege as $permission)
            {
              echo $permission.": ".$row[$permission]."<br>";
              $userdata[$permission] = $row[$permission];
            }
            $this->set_userdata($userdata);
            return true;
          }
        }
        else
        {
          return false;
        }
           }
      else
      {
        show_error('ENCRYPTION AND DATABASE MUST BE ENABLED - PLEASE READ /APPLICATION/CONFIG/AUTH.PHP');
        return false;
      }
    }
///////////////////////////////////////////////////////////////////////////////
// Removes the session authorization and user name from the client           //
///////////////////////////////////////////////////////////////////////////////
    function logout()
    {
           include(APPPATH.'config/auth'.EXT);
      $this->unset_userdata($session_auth);
      foreach ($privilege as $remove_permission)
      {
        $this->unset_userdata($remove_permission);
      }
    }
///////////////////////////////////////////////////////////////////////////////
// Checks to see if the user is logged in and if they have access to the area//
///////////////////////////////////////////////////////////////////////////////
    function auth($access)
    {
          if ($this->CI->config->item('sess_encrypt_cookie') == TRUE AND $this->CI->config->item('sess_use_database') == TRUE AND $this->CI->config->item('sess_table_name') != '')
          {
             include(APPPATH.'config/auth'.EXT);
        $authorized = $this->userdata($session_auth);
        if ($authorized) {
          if ($this->userdata($access) == TRUE) {
            return TRUE;
          }
          else {
            return FALSE;
          }
        }
           }
      else
      {
        show_error('ENCRYPTION AND DATABASE MUST BE ENABLED - PLEASE READ /APPLICATION/CONFIG/AUTH.PHP');
        return FALSE;
      }
    }
///////////////////////////////////////////////////////////////////////////////
}

Enjoy!

Something went wrong with that request. Please try again.