[eluser]JoostV[/eluser]
You seem to be overengineering it a bit. Also, you keep a lot of business logic in your controller.
First, the login logic. Move this to a model, so you can reuse it. Hope it's bug-free, did not test it
model users.php
Code:
if (! defined('BASEPATH')) exit('No direct script access allowed');
class Users extends Model
{
function __construct ()
{
parent::Model();
}
/**
* Login a user and store user data in session.
* @param $username Username, unfiltered
* @param $password Password, unfiltered
* @return boolean
*/
function login ($username, $password)
{
// Filter input
$login = mysql_real_escape_string(strip_tags(substr($this->input->post('username'), 0, 16)));
$password = mysql_real_escape_string(strip_tags(substr($this->input->post('password'), 0, 16)));
// Hash password, we do not want to store plain text passwords in DB
// We throw the username into the hash as well, making both username and password case sensitive.
$password = md5($login . $password);
// Check if a user exists with this login/password combination
$this->db->where('name', $login);
$this->db->where('password', $password);
$this->db->limit(1);
$query = $this->db->get('users');
if ($query->num_rows() > 0) {
// We have a valid user. Store user data in session.
$user = $query->row_array();
$this->session->set_userdata($user);
return true;
}
else {
// We do not have a valid user. Login failed.
return false;
}
}
}
Now for the controller login method. Make sure you have a field 'is_admin' in your user table, so you can check if this user is an admin. I'll do some ugly nested elseif statements below, you'll have to clean that up yourself
Code:
function login ()
{
// Set validation
$this->form_validation->set_rules('username', 'Username', 'required|max[16]|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'required|max[16]|xss_clean');
if ($this->form_validation->run() == TRUE) {
// Try to log in user
$this->load->model('users');
if ($this->users->login() == true) {
if ($this->session->userdata('is_admin')) {
echo 'Hooray, you are an admin!';
}
else {
show_error('You are logged in, but you are not an admin, sorry.');
}
}
else {
show_error('This user does not exist');
}
}
else {
show_error('Form did not validate');
}
}
General tips:
1. Load your helpers, libraries and database in autoload.php
2. Do not forget to autoload the session class.
3. use the database for sessions, not the cookies.
4. Create a main view and load subviews such as 'header' from there.
5. You do not need functions '_is_admin', '_username_check' and '_password_check' in this setup