How to create login authentication in Codeigniter

This tutorial lays a strong foundation that will help you implement a better and stronger authentication system that will make it difficult for attackers to gain unauthorized entry. The tutorial starts with the theory followed by the implementation. If you are already familiar with the theoretical aspect and authentication best practices then you can skip the theory and go directly to the practical implementation.

Login authentication in codeigniter

Controllers – Auth.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Auth extends CI_Controller {
	public function __construct() {
        parent::__construct();
        $this->load->library("Aauth");
    }
	public function index()
	{
	     $this->load->view('login');
	}
}
?>

View – login.php

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Login</title>
</head>
<body>

<div id="container">
	<h1>Login</h1>
	<div id="body">
		<form method="post" action="">
			Username: <br>
			<input type="text" name="username" class="form-control">
			Password: <br>
			<input type="text" name="password" class="form-control">
			<br>
			<button class="btn btn-primary" type="submit">Save</button>
			<br />
		</form>
	</div>
</div>

</body>
</html>

Form redirect in controller

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Auth extends CI_Controller {
	public function __construct() {
        parent::__construct();
        $this->load->library("Aauth");
    }
	public function index()
	{
		if($_POST)
		{
			$username = $this->input->post('username'); 
			$password = $this->input->post('password');
			if($this->aauth->login($username, $password))
			{
				echo "success";
			}
			else
			{
				echo 'Username and Password Wrong!!';
			}
		}
		else
		{
			$this->load->view('login');
		}
	}
}

$this->aauth->login($username, $password) (libraries/Aauth)

public function login($email, $pass, $remember = FALSE) {

	// Remove cookies first
	$cookie = array(
		'name'	 => 'user',
		'value'	 => '',
		'expire' => time()-3600,
		'path'	 => '/',
	);

	$this->CI->input->set_cookie($cookie);

	if( !valid_email($email) OR strlen($pass) < 5 OR strlen($pass) > $this->config_vars['max'] )
	{
		$this->error($this->CI->lang->line('aauth_error_login_failed'));
		return FALSE;
	}


	$query = null;
	$query = $this->CI->db->where('email', $email);
	$query = $this->CI->db->get($this->config_vars['users']);
	$row = $query->row();

	// only email found and login attempts exceeded
	if ($query->num_rows() > 0 && $this->config_vars['ddos_protection'] && ! $this->update_login_attempts($row->email)) {

		$this->error($this->CI->lang->line('aauth_error_login_attempts_exceeded'));
		return FALSE;
	}

	//recaptcha login_attempts check
	$query = null;
	$query = $this->CI->db->where('email', $email);
	$query = $this->CI->db->get($this->config_vars['users']);
	$row = $query->row();
	if($query->num_rows() > 0 && $this->config_vars['ddos_protection'] && $this->config_vars['recaptcha_active'] && $row->login_attempts >= $this->config_vars['recaptcha_login_attempts']){
		$reCAPTCHA_cookie = array(
			'name'	 => 'reCAPTCHA',
			'value'	 => 'true',
			'expire' => time()+7200,
			'path'	 => '/',
		);
		$this->CI->input->set_cookie($reCAPTCHA_cookie);
	}

	// if user is not verified
	$query = null;
	$query = $this->CI->db->where('email', $email);
	$query = $this->CI->db->where('banned', 1);
	$query = $this->CI->db->where('verification_code !=', '');
	$query = $this->CI->db->get($this->config_vars['users']);

	if ($query->num_rows() > 0) {
		$this->error($this->CI->lang->line('aauth_error_account_not_verified'));
		return FALSE;
	}

	// to find user id, create sessions and cookies
	$query = $this->CI->db->where('email', $email);
	$query = $this->CI->db->get($this->config_vars['users']);

	if($query->num_rows() == 0){
		$this->error($this->CI->lang->line('aauth_error_login_failed'));
		return FALSE;
	}

	$user_id = $query->row()->id;

	$query = null;
	$query = $this->CI->db->where('email', $email);

	// Database stores pasword hashed password
	$query = $this->CI->db->where('pass', $pass, $user_id);
	$query = $this->CI->db->where('banned', 0);

	$query = $this->CI->db->get($this->config_vars['users']);

	$row = $query->row();
	if($this->CI->input->cookie('reCAPTCHA', TRUE) == 'true'){
		$reCaptcha = new ReCaptcha( $this->config_vars['recaptcha_secret']);
		$resp = $reCaptcha->verifyResponse( $this->CI->input->server("REMOTE_ADDR"), $this->CI->input->post("g-recaptcha-response") );

		if(!$resp->success){
			$this->error($this->CI->lang->line('aauth_error_recaptcha_not_correct'));
			return FALSE;
		}
	}

	// if email and pass matches and not banned
	if ( $query->num_rows() > 0 ) {

		// If email and pass matches
		// create session
		$data = array(
			'id' => $row->id,
			'name' => $row->name,
			'email' => $row->email,
			'loggedin' => TRUE
		);

		$this->CI->session->set_userdata($data);

		// if remember selected
		if ( $remember ){
			$expire = $this->config_vars['remember'];
			$today = date("Y-m-d");
			$remember_date = date("Y-m-d", strtotime($today . $expire) );
			$random_string = random_string('alnum', 16);
			$this->update_remember($row->id, $random_string, $remember_date );

			$cookie = array(
				'name'	 => 'user',
				'value'	 => $row->id . "-" . $random_string,
				'expire' => time() + 99*999*999,
				'path'	 => '/',
			);

			$this->CI->input->set_cookie($cookie);
		}

		$reCAPTCHA_cookie = array(
			'name'	 => 'reCAPTCHA',
			'value'	 => 'false',
			'expire' => time()-3600,
			'path'	 => '/',
		);
		$this->CI->input->set_cookie($reCAPTCHA_cookie);

		// update last login
		$this->update_last_login($row->id);
		$this->update_activity();
		$this->reset_login_attempts($row->id);

		return TRUE;
	}
	// if not matches
	else {

		$this->error($this->CI->lang->line('aauth_error_login_failed'));
		return FALSE;
	}
}

$this->load->library(“Aauth”); (config/aauth)

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/*
  | -------------------------------------------------------------------
  |  Aauth Config
  | -------------------------------------------------------------------
  | A library Basic Authorization for CodeIgniter 2.x
 */


// Config variables

$config['aauth'] = array(
    'login_page' => '/login',
    // if user don't have permisssion to see the page he will be
    // redirected the page spesificed below
    'no_permission' => '/',
    //name of admin group
    'admin_group' => 'admin',
    //name of default group, the new user is added in it
    'default_group' => 'default',
    // public group , people who not logged in
    'public_group' => 'public',
    // The table which contains users
    'users' => 'aauth_users',
    // the group table
    'groups' => 'aauth_groups',
    // 
    'user_to_group' => 'aauth_user_to_group',
    // permitions
    'perms' => 'aauth_perms',
    // perms to group
    'perm_to_group' => 'aauth_perm_to_group',
    // perms to group
    'perm_to_user' => 'aauth_perm_to_user',
    // pm table
    'pms' => 'aauth_pms',
    // system variables
    'system_variables' => 'aauth_system_variables',
    // user variables
    'user_variables' => 'aauth_user_variables',

    // remember time
    'remember' => ' +3 days',

    // pasword maximum char long (min is 4)
    'max' => 13,

    // non alphanumeric characters that are allowed in a name
    'valid_chars' => array(' ', '\''),

    // ddos protection,
    //if it is true, the user will be banned temporary when he exceed the login 'try'
    'ddos_protection' => true,

    'recaptcha_active' => false, 
    'recaptcha_login_attempts' => 4,
    'recaptcha_siteKey' => '', 
    'recaptcha_secret' => '', 

    // login attempts time interval
    // default 20 times in one hour
    'max_login_attempt' => 10,

    // to register email verifitaion need? true / false
    'verification' => false,

    // system email.
    'email' => 'admin@admin.com',
    'name' => 'Emre Akay'
    
);


/* End of file aauth.php */
/* Location: ./application/config/aauth.php */

Leave a Reply

Your email address will not be published. Required fields are marked *