I’m creating my first login process in CodeIgniter.
I’m using the simpleloginsecure library for actual session management but I wrote the controller and model myself and I was hoping if you could see any flaws in it.
My User_model Class
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_model extends CI_Model {
public function __construct() {
parent::__construct();
}
function login($email, $password) {
if($this->simpleloginsecure->login($email, $password)) {
return true;
}
return false;
}
}
?>
My User Controller class
if(!defined('BASEPATH')) exit('No Direct script access allowed');
Class User extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('user_model');
}
public function index() {
if($this->session->userdata('logged_in')) {
redirect('/user/dashboard/', 'location');
} else {
$data['message'] = '<p class="error">You need to be logged in to view the administration area</p>';
$this->load->view('user/login', $data);
}
}
public function dashboard() {
if($this->session->userdata('logged_in')) {
$data['title'] = 'Welcome';
$this->load->view('user/dashboard', $data);
} else {
$data['message'] = '<p class="error">You need to be logged in to view the administration area</p>';
redirect('/user/login/', 'location');
}
}
public function login() {
if($this->session->userdata('logged_in')) {
redirect('/user/dashboard/', 'location');
}
$this->form_validation->set_rules('email', 'E-mail', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Wachtwoord', 'trim|required|min_length[4]|max_length[32]');
if($this->form_validation->run() == FALSE) {
$this->index();
} else {
if($this->user_model->login($this->input->post('email'), $this->input->post('password'))) {
redirect('/user/dashboard/', 'location');
} else {
$this->index();
}
}
}
public function logout() {
$this->simpleloginsecure->logout();
redirect('/user/login/', 'location');
}
}
This is a good start, although it might be helpful to reduce code duplication in your controller index functions if you create two types of base controller classes, one insecure controller and one secure controller.
The insecure controller is allowed to be loaded without being authenticated where the secure controller checks for a valid login in the constructor. So you might have this for your a base class of Secure_Controller:
Then any classes that extend Secure_Controller will automatically check for authentication before proceeding. I haven’t tried to run this code, just used your starting point as an example of integrating your authentication into the constructor of to minimize code duplication in all your controller index functions.