Welcome Guest, Not a member yet? Register   Sign In
Login Controller - with Auto-protect User library
#1

[eluser]wiredesignz[/eluser]
application/controllers/login.php

Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Login Controller
*
* @author: Wiredesignz (c) 2008-12-25
*/
class Login extends Controller {

    function Login()
    {
        parent::Controller();
        $this->load->model('users_model', 'users');
    }
    
    function index()
    {        
        delete_cookie('ci_user'); // kill existing cookie

        $path = implode('/', array_slice($this->uri->rsegments, 2)); //get return path    
        
        $login = (object) array('username' => '', 'password' => '', 'remember' => '');
        $message = 'Enter your Username & Password to continue';
        
        if ($_POST)
        {
            //all inputs use XSS_clean filter
            $login->username = $this->input->post('username', TRUE);
            $login->password = md5($this->input->post('password', TRUE)); //hash the password
            $login->remember = $this->input->post('remember', TRUE);
            
            if ($this->try_login($login)) redirect($path);

            $message = 'Login failed. Please try again!';
        }
        
        if ($uid = get_cookie('ci_login', TRUE)) //check for auto-login cookie ('ci_login')
        {
            $user = $this->users->findBy("`uid` = '{$uid}'");
            
            $login->username = $user->username;
            $login->password = $user->password;
            
            if ($this->try_login($login)) redirect($path);
        }
        
        $data = array
        (
            'title'    => 'Login',
            'username' => '',
            'password' => '',
            'checked'  => '',
            'message'  => $message,
            'action'   => site_url().'login/'.$path,
            'lost_usr' => site_url().'register/lost-user',
        );
        
        $this->load->view('login/form', $data, FALSE);
    }
    
    function try_login($login)
    {        
        if ($login->password)    
        {
            //find user, check password & create cookie if valid
            if ($user = $this->users->findBy("`username` = '{$login->username}'") AND $login->password == $user->password)    
            {
                set_cookie('ci_user', $user->uid, 0); //cookie expires on browser close
                if ($login->remember) set_cookie('ci_login', $user->uid, 86500);
                return TRUE;
            }
        }
        return FALSE;
    }
}

application/views/login/form.php

Code:
<style type="text/css">
    <!--
    #login { font: 12px verdana; margin: 20px }
    #login form { margin-top: 6px }
    #login input { vertical-align: middle }
    #login #sbmt, #login .chk { margin: 3px 6px 3px 70px }
    #login .pwd { margin: 2px }
    -->
</style>

<div id="login"&gt;&lt;?php echo $message."\n"; ?&gt;
    &lt;form action="&lt;?php echo $action; ?&gt;" method="post"&gt;
        
        <div class="usr"><label for="usr">Username: </label>
        &lt;input size="22" type="text" name="username" id="usr" value="&lt;?php echo $username; ?&gt;" /&gt;</div>
        
        <div class="pwd"><label for="pwd">Password: </label>
        &lt;input size="22" type="password" name="password" id="pwd" value="&lt;?php echo $password; ?&gt;" /&gt;</div>
        
        <div class="chk">&lt;input type="checkbox" &lt;?php echo $checked; ?&gt; name="remember" id="chk" value="on" /&gt;<label for="chk">Remember this login</label></div>
        <div class="sbmt">&lt;input type="submit" id="sbmt" value="Login" /&gt;<a href="&lt;?php echo $lost_usr; ?&gt;">lost password?</a></div>
    &lt;/form&gt;
</div>

application/config/routes.php

Code:
*/
$route['default_controller'] = "welcome";
$route['scaffolding_trigger'] = "";

//login controller route override (enables path back to caller)
$route['login/(.*)'] = 'login/index';

mysql users table

Code:
--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `id` int(11) NOT NULL auto_increment,
  `username` varchar(25) NOT NULL,
  `password` varchar(60) NOT NULL,
  `fullname` varchar(50) NOT NULL,
  `privileges` int(2) NOT NULL,
  `uid` varchar(100) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;

--
-- Data for table `users`
--

INSERT INTO `users` VALUES (1, 'admin', '21232f297a57a5a743894a0e4a801fc3', 'Administrator', 99, 'be4817c3d37d255db342d419be86185799f9d06c');

Password = md5('admin')
#2

[eluser]Michael Wales[/eluser]
nm, spoke to quickly


This looks pretty good - why not make it a library so others can use it more easily?
#3

[eluser]wiredesignz[/eluser]
Thanks Micheal,

Please explain what you mean by -- "make it a library so others can use it more easily?".
#4

[eluser]freshface[/eluser]
Hey wiredesignz is it possible to post your model?
And how do you check if somebody can view an other controller?
#5

[eluser]wiredesignz[/eluser]
This is actually a Base model I use for all tables in my database.
My Users model extends this, but it provides all the basic functionality I require.

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

class Base_model extends Model    //required by all models
{
     var $table, $resultset, $select;
    
    function Base_model($table = NULL)
    {
        parent::Model();
        $this->table = $table;
        $this->resultset = array();
        $this->select = '*';
        
        log_message('debug', "Base_model initialised as {$this->table}");
    }
    
    function delete($qry = NULL)
    {
        return $this->db->delete($this->table, $qry);
    }
    
    function insert($data = array())
    {
        return $this->db->insert($this->table, $data);
    }
    
    function update($qry = NULL, $data = array())
    {
        return $this->db->update($this->table, $data, $qry);
    }
    
    function findBy($qry = NULL)
    {
        $this->db->select($this->select);
        $found = $this->db->getwhere($this->table, $qry, 'LIMIT 1');
        
        return $found->row();
    }
    
    function findAll($qry = NULL)
    {        
        $this->db->select($this->select);
        $found = $this->db->getwhere($this->table, $qry);
        $this->resultset = $found->result();
        
        return count($this->resultset);
    }
    
    function findArray($qry = NULL)
    {
        $this->db->select($this->select);
        $found = $this->db->getwhere($this->table, $qry);
        $this->resultset = $found->result_array();
        
        return count($this->resultset);        
    }
    
    function findPaged($qry = NULL, $limit = 1, $offset = 0)
    {
        $this->db->limit($limit);
        $this->db->offset($offset);
        
        $this->db->select('SQL_CALC_FOUND_ROWS'.$this->select);
        $found = $this->db->getwhere($this->table, $qry);
        $this->resultset = $found->result();
        
        $query = $this->db->query('SELECT FOUND_ROWS() AS rows');
        $count = $query->row();
        
        return $count->rows;
    }
}
The Users model extends Base model
Code:
&lt;?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

class Users_model extends Base_model
{    
    function Users_model()
    {
        parent::Base_model('users');
    }
}
#6

[eluser]wiredesignz[/eluser]
A sample controller protected by the User library.
The user library automatically checks the access level required by the controller when instantiated and redirects to login if user privileges are lower than access level.

Code:
class Admin_controller extends Controller
{
    function Admin_controller($access_level = 98) //minimum access level for the admin pages
    {
        parent::Controller();
        $this->load->library('user', $access_level);
    }
}

The User library can be found here:
http://ellislab.com/forums/viewthread/69253/
#7

[eluser]freshface[/eluser]
Thx, will try this later.
#8

[eluser]ejanmapet[/eluser]
i've try but got this error..

Fatal error: Class 'Base_Model' not found in C:\wamp\www\try\system\application\models\Users_model.php on line 3
#9

[eluser]wiredesignz[/eluser]
autoload or include the Base_model
#10

[eluser]ejanmapet[/eluser]
now..coming with this error..i've try 2 solve this error since last week..

Fatal error: Call to undefined function delete_cookie() in C:\wamp\www\try\system\application\controllers\login.php on line 17




Theme © iAndrew 2016 - Forum software by © MyBB