Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Simplelogin

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

Download: File:simplelogin_0.1.zip

Name: Simplelogin 0.1 License: Simplelogin is released to the public domain. Released: April 25, 2007 CI Version: Tested with CodeIgniter 1.5.3 (should work with previous versions and hopefully future versions) Author: Anthony Graddy


INTRODUCTION


Simplelogin is designed to give you a quick and simple login library that will get you up and running with an unobtrusive authorization system very quickly. It does not try to guess how you want to structure your app, it simply tries to give you a little help. Feel free to edit it in any way to suit your needs.

It is designed to help if you need it; otherwise, it stays out of your way.


INSTALLATION


To install, just copy Simplelogin.php to your application/libraries directory. You will need to load the database, session, and simplelogin libraries to run it (I recommend just autoloading them).

Simplelogin uses a database. Here is the SQL to create the table in MySQL (feel free to add columns):

CREATE TABLE users ( id INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , username VARCHAR( 64 ) NOT NULL , password VARCHAR( 64 ) NOT NULL , UNIQUE ( username ) );


METHODS


Simplelogin currently has four methods: login, logout, create, delete

I debated about putting create and delete in the library. Simplelogin is basically designed to allow users to get up and running quickly with a login system (it is simply designed to help you manage user logins, not write your login forms, not editing users, not remembering your users, etc. - those extras should be handled with Models, Views, and Controllers you setup yourself). Although I think that create and delete should fall in the "do it yourself" category, I figured it would probably be best for new users to see the basic concept (besides, advanced users can just ignore those methods if they want).

To check if a user is logged in, you just do something like this:


if($this->session->userdata('logged_in')) {
//User is logged in
} else {
//User is not logged in
}

CONTROLLER EXAMPLES


example.php and example_obsession_version.php are simply controller examples of how to work with the library (you should never use controllers like this in a real project) - these files are examples and are not necessary. They assume that you are auto loading 'database', 'session', 'simplelogin'.

If you are using the default CodeIgniter sessions, then check out the example.php controller.

I highly recommend Oscar Bajner's OB Session library. If you would like to use that library with Simplelogin, just follow the setup information in Oscar's userguide (mainly the config settings and the database info). You can then use the example_obsession_version.php controller which adds extra functionality (since Oscar's library just adds additional features to the original CodeIgniter library, you can also use the example.php controller with OBSession).


FINAL NOTES


Since Simplelogin is released to the public domain, feel free to use it in any way you want. It is designed to be easily modified to work with your setup (for instance, you may want to add additional columns to your database or you may want to add error messages in the library itself).

Please keep in mind that you are using this library at your own risk. Please direct support issues to the CodeIgniter forums, and I will help if I can (no guarantees).

  • Anthony Graddy

Here's the code if you want to see it without downloading:


<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Simplelogin Class
 *
 * Makes authentication simple
 *
 * Simplelogin is released to the public domain
 * (use it however you want to)
 * 
 * Simplelogin expects this database setup
 * (if you are not using this setup you may
 * need to do some tweaking)
 * 

    #This is for a MySQL table
    CREATE TABLE `users` (
    `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `username` VARCHAR( 64 ) NOT NULL ,
    `password` VARCHAR( 64 ) NOT NULL ,
    UNIQUE (
    `username`
    )
    );

 * 
 */
class Simplelogin
{
    var $CI;
    var $user_table = 'users';

    function Simplelogin()
    {
        // get_instance does not work well in PHP 4
        // you end up with two instances
        // of the CI object and missing data
        // when you call get_instance in the constructor
        //$this->CI =& get_instance();
    }

    /**
     * Create a user account
     *
     * @access    public
     * @param    string
     * @param    string
     * @param    bool
     * @return    bool
     */
    function create($user = '', $password = '', $auto_login = true) {
        //Put here for PHP 4 users
        $this->CI =& get_instance();        

        //Make sure account info was sent
        if($user == '' OR $password == '') {
            return false;
        }

        //Check against user table
        $this->CI->db->where('username', $user); 
        $query = $this->CI->db->getwhere($this->user_table);

        if ($query->num_rows() > 0) {
            //username already exists
            return false;

        } else {
            //Encrypt password
            $password = md5($password);

            //Insert account into the database
            $data = array(
                        'username' => $user,
                        'password' => $password
                    );
            $this->CI->db->set($data); 
            if(!$this->CI->db->insert($this->user_table)) {
                //There was a problem!
                return false;                        
            }
            $user_id = $this->CI->db->insert_id();

            //Automatically login to created account
            if($auto_login) {        
                //Destroy old session
                $this->CI->session->sess_destroy();

                //Create a fresh, brand new session
                $this->CI->session->sess_create();

                //Set session data
                $this->CI->session->set_userdata(array('id' => $user_id,'username' => $user));

                //Set logged_in to true
                $this->CI->session->set_userdata(array('logged_in' => true));            

            }

            //Login was successful            
            return true;
        }

    }

    /**
     * Delete user
     *
     * @access    public
     * @param integer
     * @return    bool
     */
    function delete($user_id) {
        //Put here for PHP 4 users
        $this->CI =& get_instance();

        if(!is_numeric($user_id)) {
            //There was a problem
            return false;            
        }

        if($this->CI->db->delete($this->user_table, array('id' => $user_id))) {
            //Database call was successful, user is deleted
            return true;
        } else {
            //There was a problem
            return false;
        }
    }


    /**
     * Login and sets session variables
     *
     * @access    public
     * @param    string
     * @param    string
     * @return    bool
     */
    function login($user = '', $password = '') {
        //Put here for PHP 4 users
        $this->CI =& get_instance();        

        //Make sure login info was sent
        if($user == '' OR $password == '') {
            return false;
        }

        //Check if already logged in
        if($this->CI->session->userdata('username') == $user) {
            //User is already logged in.
            return false;
        }

        //Check against user table
        $this->CI->db->where('username', $user); 
        $query = $this->CI->db->getwhere($this->user_table);

        if ($query->num_rows() > 0) {
            $row = $query->row_array(); 

            //Check against password
            if(md5($password) != $row['password']) {
                return false;
            }

            //Destroy old session
            $this->CI->session->sess_destroy();

            //Create a fresh, brand new session
            $this->CI->session->sess_create();

            //Remove the password field
            unset($row['password']);

            //Set session data
            $this->CI->session->set_userdata($row);

            //Set logged_in to true
            $this->CI->session->set_userdata(array('logged_in' => true));            

            //Login was successful            
            return true;
        } else {
            //No database result found
            return false;
        }    

    }

    /**
     * Logout user
     *
     * @access    public
     * @return    void
     */
    function logout() {
        //Put here for PHP 4 users
        $this->CI =& get_instance();        

        //Destroy session
        $this->CI->session->sess_destroy();
    }
}
?>

Category:Libraries::Authentication

Something went wrong with that request. Please try again.