[eluser]bsteve[/eluser]
Hello to you all,
I am very grateful for those who provided me with the solution to my last post but this time i have another problem, i would like to add sessions to my application but i have failed, i am developing an application(using code ignitor and doctrine)which has several pages. i would like to limit any user from accessing a page without logging in but i have failed do it.
Below is my login controller.
<?php
class Login extends Controller {
public function __construct() {
parent::Controller();
$this->load->helper(array('form','url'));
$this->load->library('form_validation');
}
public function index() {
$this->load->view('login_form');
}
public function submit() {
if ($this->_submit_validate() === FALSE) {
$this->index();
return;
}
redirect('/');
}
private function _submit_validate() {
$this->form_validation->set_rules('username', 'Username',
'trim|required|callback_authenticate');
$this->form_validation->set_rules('password', 'Password',
'trim|required');
$this->form_validation->set_message('authenticate','Invalid login. Please try again.');
return $this->form_validation->run();
}
public function authenticate() {
// get User object by username
if ($u = Doctrine::getTable('User')->findOneByUsername($this->input->post('username'))) {
// this mutates (encrypts) the input password
$u_input = new User();
$u_input->password = $this->input->post('password');
// password match (comparing encrypted passwords)
if ($u->password == $u_input->password) {
unset($u_input);
return Current_User::login($this->input->post('username'),
$this->input->post('password'));
}
unset($u_input);
}
return FALSE;
}
}
and the Current user model is as below.
<?php
class Current_User {
private static $user;
private function __construct() {}
public static function user() {
if(!isset(self::$user)) {
$CI =& get_instance();
$CI->load->library('session');
if (!$user_id = $CI->session->userdata('user_id')) {
return FALSE;
}
if (!$u = Doctrine::getTable('User')->find($user_id)) {
return FALSE;
}
self::$user = $u;
}
return self::$user;
}
public static function login($username, $password) {
// get User object by username
if ($u = Doctrine::getTable('User')->findOneByUsername($username)) {
// this mutates (encrypts) the input password
$u_input = new User();
$u_input->password = $password;
// password match (comparing encrypted passwords)
if ($u->password == $u_input->password) {
unset($u_input);
$CI =& get_instance();
$CI->load->library('session');
$CI->session->set_userdata('user_id',$u->id);
self::$user = $u;
return TRUE;
}
unset($u_input);
}
// login failed
return FALSE;
}
public function __clone() {
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
}
So i would like to put some code in the controllers of the other pages that will limit a user from accessing the page without logging in.every time the user tries to access the page he should be redirected to the login page.
Thank you.