CodeIgniter Forums
sessions and authentication - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forumdisplay.php?fid=21)
+--- Thread: sessions and authentication (/showthread.php?tid=6060)

Pages: 1 2


sessions and authentication - El Forum - 02-13-2008

[eluser]wildcard99[/eluser]
elow guys... im trying to use the ci session, I get it storing the session id on the database but how do i implement my authentication?

I want my authentication to be secure in a way that when the user is logged-in, if i try to login using a diferent browser with the same account.. the second user will just be ignored.

plss help!


sessions and authentication - El Forum - 02-14-2008

[eluser]systemsos[/eluser]
I'll give you what I have thus far. Make sure that in your application/config/config.php the following is set
Code:
$config['sess_cookie_name']        = 'rapid_session';
$config['sess_expiration']        = 7200;
$config['sess_encrypt_cookie']    = TRUE;
$config['sess_use_database']    = TRUE;
$config['sess_table_name']        = 'ci_sessions';
$config['sess_match_ip']        = TRUE;
$config['sess_match_useragent']    = TRUE;
$config['sess_time_to_update']         = 300;

I then use the following adaption of Erkana: Code Authorization Library (I rewrote it with additional applications in mind... Please not it's not finished, so there is probably 1000 different ways to improve it. But the security is very "so so" when you aren't using the session database.

Code:
/-------------------------------------
//system/libraries/Rapidauth.php
/-------------------------------------

<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* @package    Rapidauth
* @author        Darren Nolan -  Rapid Hosting - Based on Erkana: CodeIgniter Authorization Library (www.michaelwales.com)
  * @link        http://www.rapidhosting.com.au
* @since        Version 1.0
* @filesource
*/

class Rapidauth
{
    var $CI;
    
    function Rapidauth()
    {
        $this->CI =& get_instance();
        log_message('debug', 'RapidAuth class loaded');
        
        $this->CI->load->database();
        $this->CI->load->library('session');
        $this->CI->load->helper('Rapidauth_helper');
    }
    
    function check_login ($condition = array(), $table = 'users', $select = 'id')
    {
        $this->CI->db->select($select);
        $query = $this->CI->db->getwhere($table, $condition, 1, 0);
        if ($query->num_rows != 1) {
            return FALSE;
        } else {
            $row = $query->row();
            $this->CI->session->set_userdata(array('user_id' => $row->$select, 'authenticated' => 'TRUE'));
            return TRUE;
        }
    }
    
    function check_session ()
    {
        if ($this->CI->session->userdata('user_id') AND $this->CI->session->userdata('authenticated')=='TRUE') {
            return TRUE;
        } else {
            return FALSE;
        }
    }
    
    function logout ()
    {
        $this->CI->session->unset_userdata('user_id');
        $this->CI->session->unset_userdata('authenticated');
        $this->CI->session->sess_destroy();
    }
}
?>
/-------------------------------------
/Use the below code in your parent controller or index function for the controller to load it up
/-------------------------------------
$this->load->library('Rapidauth');    //Login, Logout and Log-Check functions

This is the code I use to check is the user/password combo is right.
Code:
if ($this->validation->run()) {
    if ($username=$this->input->post('username', true)) {
        $password = dohash($this->input->post('password'));
        $details = array ('username'=>$username, 'password'=>$password);
        if ($this->rapidauth->check_login($details)) {
            redirect ('admin/main');
        } else {
            //THIS SET MESSAGE PART DOESN'T WORK YET... STILL TRYING TO FIGURE IT OUT...
            $this->validation->set_message('required', 'Username or Password incorrect.');
        }
    }
}

At the start of all protected pages I use
Code:
if (!$this->rapidauth->check_session()) {
    redirect ('admin/login');
}

Now a thing to note with the library at the moment, is it only checks if the user is authenticated - there is no "role" system (yet) as defined with Erkana's code base.

However, by reading over the script - I'm a little more flexible with the table name for users and field returned to the session by passing values to the function.

of course $this->rapidauth->logout() and the such are all there. I'll attach the library here once it's complete - but I hope this gets you in the right direction.


Cheers,


sessions and authentication - El Forum - 02-15-2008

[eluser]wildcard99[/eluser]
Does rapid auth support one time login? say IM ALREADY logged-in and then another user who knows my account tries to login.. what will happen?


sessions and authentication - El Forum - 02-15-2008

[eluser]systemsos[/eluser]
Of course not. "Not yet" at least. I'm still learning all this. I'm going to post again tonight though when I get something fancy like that working Smile Give me two days.


sessions and authentication - El Forum - 02-15-2008

[eluser]wiredesignz[/eluser]
[quote author="wildcard99" date="1203084655"]Does rapid auth support one time login? say IM ALREADY logged-in and then another user who knows my account tries to login.. what will happen?[/quote]

You could use a logged in cookie and session IP type authentication.


sessions and authentication - El Forum - 02-15-2008

[eluser]systemsos[/eluser]
Guys this does use Session IP/Browser matching. The config setup ensure that is how the sessions are run.


sessions and authentication - El Forum - 02-15-2008

[eluser]xwero[/eluser]
i took the code from the article Detecting Users Online and used it to create a model to check if the user is logged in.
Code:
class Usersmodel extends Model
{
    
    var $visit_timeout = 600;
    
    function Usersmodel()
    {
        parent::Model();
    }
    
    function track_user()
    {
      
       $name = $this->session->userdata('username');
       // changed
       /*$name = "";
       if(isset($_SESSION['username'])) {
          // user is logged in so track the username
          $name = $_SESSION['username'];
       } else {
          // user is not logged in so track the IP
          $name = $_SERVER['REMOTE_ADDR'];
       }*/
    
       $time = time();
      
       // Cleanup old visits
       $this->db->where('timestamp <=',$time-$this->visit_timeout);
       $this->db->delete('userOnline');
       /*$query = "DELETE FROM `userOnline` WHERE `timestamp` <= '"
          .($time-VISIT_TIMEOUT)."';";
       @mysql_query($query);*/
    
       // check if user is already listed
       $this->db->where('title',$name);
       $this->db->from('userOnline');
       $count = $this->db->count_all_results();
       /*$query = "SELECT COUNT(*) AS total FROM `userOnline` ".
                     "WHERE `title`='$name';";
       $result = @mysql_query($query, $db);
       if($result = @mysql_fetch_array($result)) {
          $count = $result['total'];
       } else {
          // Could not get a record from the result, so must be 0
          $count = 0;
       }*/
      
       // If already visitor then update, otherwise add them
       // changed
       if($count > 0) {
               return true;
       }
       else
       {
               $this->db->set('timestamp',$time);
               $this->db->set('title',$name);
               $this->db->insert('userOnline');
               return false;
       }
       /*if($count > 0) {
          $query = "UPDATE `userOnline` SET `timestamp`='".$time.
                     "' WHERE title='$name';";
       } else {
          $query = "INSERT INTO `userOnline` (`title`, `timestamp`) ".
                     "VALUES ('$name', '$time');";
       }
       @mysql_query($query, $db);*/
    }
    
}
I left the original code in for educational purpose Smile Change the code to your needs


sessions and authentication - El Forum - 02-15-2008

[eluser]systemsos[/eluser]
check_session checks to see if the user is logged in, return false on a "no he's not" or true on "yeah he is".

I think the user table needs to have a session-id - so that as above, two computers can't be logged in (and browsing) at the same time. Or should I leave that out for individual applications?


sessions and authentication - El Forum - 02-15-2008

[eluser]wiredesignz[/eluser]
It should be optional.

logged in should be db session IP based, and user auth should be user_id cookie based.

pull the user unique_id from their account into a cookie and store their IP + id into a session db.

if someone else logins in they get the unique_id but the session IP fails to match.

if the genuine user leaves and comes back they still have the cookie and the session IP matches


sessions and authentication - El Forum - 02-15-2008

[eluser]systemsos[/eluser]
Problem I'm facing when using this is using CI's session classes to handle things. I'm very not used to it.

I normally start a session, record the session-id in a database, their IP, their username, timetodie (or log-out automatically) and remember login.

I don't like sessions keeping much more than that - and I hate cookies keeping anything other than the session ID.

Just out of curiosity xwero - that timeout value you have set in the class - how do I grab that value from the config.php file on a "per application" basis.