Jump to content

What's wrong with my logic?


matthew.javelet

Recommended Posts

After giving my title a second read I laughed at myself.

I'm currently facing a small issue while using the CodeIgnitor framework.

 

I'm building a session class to handle admin sessions so they can login to admin restricted pages.

So far I just have two files handling the login in, the admin controller and the session class itself.

 

The admin controller is meant to set a variable that belongs to the session class, this is the issue, it currently does not do that and I have no idea why.

 

This is the sessions class:

<?php
class rmb_admin_sessions
{
    /**
     * The CI object
     * @var		object
     */
    private $_obj;
    
    /**
     * Session ID
     * @var		string
     */
    protected $_session_id       = '';
    
    /**
     * Session data
     * @var		array
     */
    protected $_session_data	    = array();

    /**
     * Timeout Variable
     * @var		int
     */
    protected $_session_expire	= 120;

    /**
     * Validation status
     * @var		boolean
     */
    protected $_status		    = false;

    /**
     * Display message
     * @var		string
     */
    protected $_message		    = '';

    /**
     * Constructor
     *
     * @return	void
     */
    public function __construct()
    {		
        // Get the CodeIgniter instance
        $this->_obj = & get_instance();
        
        // PR - Preformmated dump / I'm checking the session ID before&after form submission
        pr($this->_session_id);
        
        // See if we find a session
        $session_data = $this->_obj->db->query("SELECT * FROM nab_admin_sessions WHERE session_id = '{$this->_session_id}'");
            
        // PR - Preformmated dump / I'm checking the DB queries before&after form submission to see if the sesion id gets included
        pr($this->_obj->db->queries);

        // If we find a session than an admin is logged in. Sessions are only added to the DB when an admin
        // loggs in successfully. Old sessions are deleted upon new logins, as well as old sessions being
        // deleted upon expiration of 1 hour
        if($session_data->num_rows() > 0)
        {
            // Sessions Data
            $session = $session_data->row_array();
                
            // Unserialized user data
            $user_session_data = unserialize($session['user_data']);
                
            // Merge the two
            $this->session_data = array_merge($session, $user_session_data);
               
            // Verify user data
            $user_data = $this->_obj->db->query("SELECT u.*, p.* FROM nab_members AS u LEFT JOIN nab_permissions AS p ON p.group_id = u.user_group WHERE u.user_id = '{$this->session_data['user_id']}'");
            $user = $user_data->row_array();
            
            if($user['user_id'] == '')
            {
                // The user data did not match
                return $this->_set(false, '');
            }

            if ($user['group_id'] != 9)
            {
                // User does not have proper access
                return $this->_set(false, 'Invalid access level');
            }
            else
            {
                // The login was a success
                $this->_status = true;
            }
        }

        // We're logged in and legit, handle user activity
        if ($this->_status === true)
        {
            if($this->session_data['last_activity'] < (time() - $this->session_expire * 60))
            {
                $this->_status = false;
                return $this->_set(false, 'Your session timed out.');
            }

            $this->_obj->db->update( 'nab_admin_sessions',
                array(  'last_activity' => time(),
                        'user_data'	    => serialize($user)
                ), "session_id = '{$this->_session_id}'"
            );
            return $this->_set(true, '');
        }
    }
    
    /**
     * Sets status and error message 
     *
     * @param   boolean     Session Status
     * @param   string      Display messages
     * @return	void
     */
    protected function _set($status, $message)
    {
        $this->_status   = $status;
        $this->_message  = $message;
    }
    
    /**
     * Sets session id
     *
     * @return	boolean
     */
    public function set_session($session_id)
    {
        $this->_session_id = $session_id;
    }

    /**
     * Grabs session status
     *
     * @return	boolean
     */
    public function get_status()
    {
        return $this->_status;
    }

    /**
     * Grabs error message
     *
     * @return	boolean
     */	 
    public function get_message()
    {
        return $this->_message;
    }
}

 

This is the controller:

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

class Admin extends CI_Controller
{
    /**
     * Default page
     *
     * @return	void
     */
    public function index() 
    {
        $this->load->library('rmb_admin_sessions');

        if($this->rmb_admin_sessions->get_status() === true)
        {
            $this->home();
        }
        else
        {
            $this->admin_login();
        }
    }
    
    /**
     * Admin Login
     *
     * @return	void
     */
    public function admin_login()
    { 
        $user = '';
        if ($this->input->post('process'))
        {
            $user = $this->authorise($this->input->post('username', true), $this->input->post('password'));

            if(isset($user) AND is_array($user))
            {
                $session_id = md5( uniqid( microtime() ) );
                
                // Upon a successful login, we set the admin session class sessions id.
                // This means when redirected back to /admin the admin session class should 
                // have the correct value, which is still does not
                $this->rmb_admin_sessions->set_session($session_id);
                
                #$this->db->query("delete from nab_admin_sessions where session_ = '{$user['user_id']}'");
                
                $insert = array(
                    'session_id'    => $session_id,
                    'ip_address'    => $this->input->ip_address(),
                    'user_agent'    => $this->input->user_agent(),
                    'last_activity' => time(),
                    'user_data' 	=> serialize($user)
                );

                $this->db->insert('nab_admin_sessions', $insert);
                
                #redirect('/admin');
            }
        }

        $message = $this->rmb_admin_sessions->get_message();
        $message['errors'] = ( empty( $message ) ) ? $user : $message;
        
        $this->load->view('Admin/Forms/login', $message);
    }

    /**
     * Validates a users login
     *
     * @return	void
     */
    function authorise( $user_entered, $pass_entered )
    {
        $user_data = $this->db->query("SELECT * FROM nab_members WHERE user_name = '{$user_entered}' LIMIT 1");
        if( $user_data->num_rows() > 0 )
        {		
            $user = $user_data->row_array();

            if( $this->rmb_membership->encode_password($this->input->post('password'), $user['user_pwd_salt']) == $user['user_password'] )
            {									
                return $user;
            }
            else
            {
                return 'Invalid password';
            }
        }
        else
        {
            return 'Invalid username';
        }
    }
    
    /**
     * Home page
     *
     * @return	void
     */
    public function home()
    {
        $this->load->view('Admin/home');
    }
}

 

So the function set_session that is called once a user successfully logs in is not setting the session id.

 

I made a test file to see if it was my logic or CodeIgnitor and this is what I came up with:

<?php
class sessions
{
    protected $session_id;
    
    public function __construct()
    {
        echo $this->session_id;
    }
    public function set_session($sid)
    {
        $this->session_id = $sid;
    }
}

class admin
{
    public function index() 
    {
        $this->sessions = new sessions;
        $this->login();
        
        // before - sessions Object ( [session_id:protected] =>  ) 
        print_r($this->sessions);
        // after  - sessions Object ( [session_id:protected] => 123456 ) 
    }
    public function login()
    {
        if(isset($_POST['process']))
        {
            $this->sessions->set_session('123456');
        }
        echo <<<HTML
        <form method="post">
        <input type="text" />
        <input type="submit" name="process" />
        </form>
HTML;
    }
}

$admin = new admin;
$admin->index();

 

So with this test file following the same logic, it actually does what it needs to do and properly sets the session id for the session class.

 

So can somebody please tell me what's wrong? I was going to ask the people on the CI forums but they have a character limit when posting topics and don't have attachments on currently. I also tried to post my larger files as attachments but it wouldn't work so I apologize for that too.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.