ExpressionEngine CMS
Open, Free, Amazing

Thread

This is an archived forum and the content is probably no longer relevant, but is provided here for posterity.

The active forums are here.

Login Controller - with Auto-protect User library

January 18, 2008 9:47pm

Subscribe [5]
  • #1 / Jan 18, 2008 9:47pm

    wiredesignz

    2882 posts

    application/controllers/login.php

    <?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

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

    application/config/routes.php

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

    mysql users table

    -- 
    -- 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 / Jan 18, 2008 9:53pm

    Michael Wales

    2070 posts

    nm, spoke to quickly


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

  • #3 / Jan 18, 2008 10:04pm

    wiredesignz

    2882 posts

    Thanks Micheal,

    Please explain what you mean by—“make it a library so others can use it more easily?”.

  • #4 / Feb 07, 2008 7:38pm

    freshface

    131 posts

    Hey wiredesignz is it possible to post your model?
    And how do you check if somebody can view an other controller?

  • #5 / Feb 07, 2008 8:16pm

    wiredesignz

    2882 posts

    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.

    <?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

    <?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
    
    class Users_model extends Base_model
    {    
        function Users_model()
        {
            parent::Base_model('users');
        }
    }
  • #6 / Feb 07, 2008 8:23pm

    wiredesignz

    2882 posts

    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.

    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 / Feb 07, 2008 8:29pm

    freshface

    131 posts

    Thx, will try this later.

  • #8 / Apr 15, 2008 5:17am

    ejanmapet

    6 posts

    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 / Apr 15, 2008 5:33am

    wiredesignz

    2882 posts

    autoload or include the Base_model

  • #10 / Apr 15, 2008 5:40am

    ejanmapet

    6 posts

    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

  • #11 / Apr 15, 2008 5:49am

    wiredesignz

    2882 posts

    load the cookie helper

  • #12 / Dec 05, 2008 1:19am

    gmon

    3 posts

    Wow.  Thank you once again, wiredesignz.  Whenever I’m searching for an answer through the forums, you seem to be my answer.

    Keep up the good work.

.(JavaScript must be enabled to view this email address)

ExpressionEngine News!

#eecms, #events, #releases