I am trying to log out for the logged in users .
But its not working ,after log out ,i am getting session data also .
Below is my code .please have a look.
public function logout() {
if ($this->session->userdata('login') == "true") {
$current_user_data = $this->session->userdata('current_user_data');
$type = $current_user_data['type'];
$user_id = $current_user_data['user_id'];
$token = $current_user_data['token'];
$logout = $this->school->logout($type, $user_id, $token);
if (!empty($logout)) {
//echo $logout->responseCode;
if ($logout->responseCode == 200 || $logout->responseCode == 419) {
$this->session->sess_destroy();
$this->clear_cache();//clear the cache after logout //
redirect('login');
} else {
//$error['code']=json_encode(array('responseCode' => '500', 'response' => array('message' => 'error', 'statusReason' => 'internal_server_error')));
$url = "error/error_type/500";
redirect($url);
}
} else {
//echo "invalid token";
$url = "error/error_type/401";
redirect($url);
}
} else {
redirect('login');
}
}
Its going to conditions also , but session is not destroying .
Any thing wrong here?
Thank you
sess_destroy() will destroy all the sessions, even flash ones. Why don't use the simple function. I have tried this and it worked in my case. I made a session named userdata which will take user credential while he login. This is my logout function.
/**
* to logout the current session
*/
public function logout() {
$this->session->unset_userdata('user_login');
$this->load->view('index.php');
}
If you want to destroy the session data this should work fine too,
refer this further https://www.codeigniter.com/user_guide/libraries/sessions.html
Try this Method for logout
<?php
class Logout extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('url','html'));
$this->load->library('session');
$this->load->database();
$this->load->model('users_model');
}
function index()
{
$user_data = $this->user_model->get_user_by_id($this->session->userdata('id'));
foreach ($user_data as $key => $value) {
if ($key != 'session_id' && $key != 'ip_address' && $key != 'user_agent' && $key != 'last_activity') {
$this->session->unset_userdata($key);
}
}
$this->session->sess_destroy();
redirect('Welcome', 'refresh');
}
}
Related
i am using codeigniter-3.0.4. i load the displaySorted function inside login_controller when a user provides a valid email-id and password. The check_database method does that for me and there i set my own $sess_array as shown in the code below. This is my login_controller.
function __construct()
{
parent::__construct();
$this->load->model('user_model','',TRUE);
}
public function index()
{
//$this->load->model('user_model');
$this->load->view('login_view');
}
My login and check_database function inside this controller
function login()
{
$this->form_validation->set_rules('login_email', 'Email');
$this->form_validation->set_rules('password', 'Password','callback_check_database');//calling the check_database function
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected to login page
$this->load->view('login_view');
}
else
{
//$this->displayDatabase();
//$this->load->view('adminPanel_view') ;
//echo true;exit;
redirect('login_controller/displaySorted');
}
}
function check_database()
{
//Field validation succeeded. Now Validating against database
$email = $this->input->post('login_email');
$password = $this->input->post('password');
//echo "$email $password"; exit;
//query the database
$result = $this->user_model->login($email, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'id' => $row->ID,
'login_email' => $row->email,
'logged_in' => 1
);
$this->session->set_userdata($sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', 'Invalid Email or password');
return false;
}
}
i am using this inside my displaySorted function:
function displaySorted($sortBy = 'DeviceName',$sortOrder = 'asc',$offset=0)
{
$dataS = $this->session->userdata();
if(isset($dataS))
{
//somecode here
}
else
{
//redirect to login here
}
and finally my logout function
function logOut(){
//echo 'Logout';exit;
//$this->session->set_userdata('logged_in',FALSE);
$this->session->unset_userdata($sess_array);
//$this->session->sess_destroy();
redirect('login_controller/login', 'refresh');
}
i am unable to destroy the $sess_array with this method. i have used some other things too but when i ever i press the back button inside the browser i can see my displaySorted functionality which should not be visible to me. i have read in the codeigniter documentation that i cannot pass an associative array in unset_userdata() method. what should i do?
set your session in check_database function try like this
$this->session->set_userdata('logged_in', $sess_array);
then in logout function to unset session try to
$this->session->unset_userdata('logged_in');
in __construct()function use this to prevent login on click back button
public function __construct()
{
parent::__construct();
if ($this->session->userdata('logged_in') == FALSE) {
redirect('auth/login', 'refresh');//where are you want to redirect controller function
}
header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
}
I'm trying to make a login using sessions in codeigniter at the time the username and password match, but I can't get it. I'm doing this:
Controller:
public function __construct()
{
parent::__construct();
$this->load->model('main_select');
$this->load->helper('url');
$this->load->library('session');
}
...code when username and password match:
if($pass === $user){
$this->session->set_userdata(array(
'user_id' => $login['id_user'],
));//we create the session 'user_id'
}
here it is supposed that we created a session called 'user_id'
in the view it doesn't work, I have this:
if( !$this->session->userdata('id_user') ){
//see this content
//first content
}else{
//see this other
//second content
}
but I always see the same content('second content').
trying to destroy it (but not working):
public function logout()
{
//session_unset();
// destroy the session
//session_destroy();
$this->session->unset_userdata('id_user');
header("Location: ".base_url() );
}
what am I doing wrong? thanks
EDIT1:
$password = md5( $this->input->post('inputpassword') );
$login = $this->login_select->get_username($username);
//si no coincide
if( $login['password'] !== $password ) {}
Note : Always use database to handle user logins. (Code is related to database login check)
in your database create table with user and add this 2 fields.
username
password
Add some user logins to it
Then in your code
public function __construct()
{
parent::__construct();
$this->load->model('main_select');
$this->load->helper('url');
$this->load->library('session');
}
// logging
public function loging()
{
$user = mysql_real_escape_string($_POST['username']);
$pass = md5(mysql_real_escape_string($_POST['password']));
$validate = $this->main_select->validate_user($user,$pass);
if(empty($validate) || $validate>1)
{
//Not a valid user
//redirect to login page
$this->load->view('loging');
}
else
{
//valid user
//set the session
$array = array('user_id' => '$user');
$this->session->set_userdata();
//redirect to normal page
$this->load->view('home_page');
}
}
//logout
public function logout()
{
$result= $this->session->sess_destroy();
if ((isset($result)))
{
header("Location: ".base_url() );
}
else
{
}
}
In Model
public function validate_user($user,$pass)
{
$query = $this->db->query("SELECT * FROM user WHERE username= '$user' AND password='$pass'");
$result = $query->result_array();
$count = count($result);
return $count;
}
modify this line of changes then your script will work as id_user need to set first to use in script.
if($pass === $login['password'] && $user===$login['username']){
$this->session->set_userdata(array(
'id_user' => $login['id_user'],
));//we create the session 'user_id'
}
here $login['password'] and $login['username'] are data come from tables and need to change fieldname pass or user according to your user table.
I have successfully used Auth, but unfortunately, it seems that it does work only with Session. I want that if user checks "Remember Me" checkbox, I would use Cookie and he would be logged in for 2 weeks. I can't find anything in official book and in Google I found just few and not great blog posts. Is there any way to implement this without rewriting the core?
In your user controller:
public function beforeFilter() {
$this->Auth->allow(array('login', 'register'));
parent::beforeFilter();
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
// did they select the remember me checkbox?
if ($this->request->data['User']['remember_me'] == 1) {
// remove "remember me checkbox"
unset($this->request->data['User']['remember_me']);
// hash the user's password
$this->request->data['User']['password'] = $this->Auth->password($this->request->data['User']['password']);
// write the cookie
$this->Cookie->write('remember_me_cookie', $this->request->data['User'], true, '2 weeks');
}
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Username or password is incorrect.'));
}
}
$this->set(array(
'title_for_layout' => 'Login'
));
}
public function logout() {
// clear the cookie (if it exists) when logging out
$this->Cookie->delete('remember_me_cookie');
return $this->redirect($this->Auth->logout());
}
In the login view:
<h1>Login</h1>
<?php echo $this->Form->create('User'); ?>
<?php echo $this->Form->input('username'); ?>
<?php echo $this->Form->input('password'); ?>
<?php echo $this->Form->checkbox('remember_me'); ?> Remember Me
<?php echo $this->Form->end('Login'); ?>
In your AppController:
public $components = array(
'Session',
'Auth',
'Cookie'
);
public $uses = array('User');
public function beforeFilter() {
// set cookie options
$this->Cookie->key = 'qSI232qs*&sXOw!adre#34SAv!#*(XSL#$%)asGb$#11~_+!##HKis~#^';
$this->Cookie->httpOnly = true;
if (!$this->Auth->loggedIn() && $this->Cookie->read('remember_me_cookie')) {
$cookie = $this->Cookie->read('remember_me_cookie');
$user = $this->User->find('first', array(
'conditions' => array(
'User.username' => $cookie['username'],
'User.password' => $cookie['password']
)
));
if ($user && !$this->Auth->login($user['User'])) {
$this->redirect('/users/logout'); // destroy session & cookie
}
}
}
See this URL i think it is very help full to you.
http://lecterror.com/articles/view/cakephp-and-the-infamous-remember-me-cookie
Or Try this
function login() {
if ($this->Auth->user()) {
if (!empty($this->data) && $this->data['User']['remember_me']) {
$cookie = array();
$cookie['username'] = $this->data['User']['username'];
$cookie['password'] = $this->data['User']['password'];
$this->Cookie->write('Auth.User', $cookie, true, COOKIE_EXPIRE);
unset($this->data['User']['remember_me']);
}
$this->LogDetail->Write('activity','has logged IN');
$this->redirect($this->Auth->redirect());
}
if (empty($this->data)) {
$cookie = $this->Cookie->read('Auth.User');
if (!is_null($cookie)) {
if ($this->Auth->login($cookie)) {
$this->Session->destroy('Message.Auth'); # clear auth message, just in case we use it.
$this->LogDetail->Write('activity','has been authenticated via cookie and is now logged IN');
$this->redirect($this->Auth->redirect());
} else {
$this->LogDetail->Write('activity','attempted to gain access with an invalid cookie');
$this->Cookie->destroy('Auth.User'); # delete invalid cookie
$this->Session->setFlash('Invalid cookie');
$this->redirect('login');
}
}
}
}
use CookeAuthenticate adapter:
https://github.com/ceeram/Authenticate/blob/master/Controller/Component/Auth/CookieAuthenticate.php
here more info:
https://github.com/ceeram/Authenticate/wiki/Set-Cookie
Remember me is nothing else but session identified with a cookie, but cookie lifetime set to infinity. Look at Config/core.php for session cookie lifetime.
I think you need to know about CakePHP Security levels. Try to lower the security of your cakePHP. CakePHP's Config variables documentation. I had written a blog about it also a long ago.
you can try this
if ($this->Auth->login())
{
if (!empty($this->data['User']['remember']))
{
$cookie = array();
$cookie['login'] = $this->data['User']['login'];
$cookie['password'] = $this->data['User']['password'];
$cookie['language'] =$this->data['User']['language'];
$this->Cookie->write('Auth.projectname', $cookie, true, '+1 years');
unset($this->data['User']['remember']);
public function admin_login() {
$this->layout = 'admin_login';
if (count($this->Session->read("Auth.User"))) {
$usr = $this->Session->read("Auth.User");
if ($usr['role'] == 'A' || $usr['role'] == 'RA' || $usr['role'] == 'MAfA' || $usr['role'] == 'Af' || $usr['role'] == 'FAA')
return $this->redirect(array('controller' => 'dashboard', 'action' => 'view'));
}
if ($this->request->is('post')) {
if ($this->request->data['User']['remember_me']=="1") {
// pr($this->request->data);
// die('sdd');
$this->Cookie->write('username', $this->request->data['User']['username'], true, '1 year');
$this->Cookie->write('password', $this->request->data['User']['password'], true, '1 year');
} else {
$this->Cookie->destroy();
}
/*
* Check if email or username is passed in form
*/
$uname = $this->request->data['User']['username'];
//login via email
if (filter_var($uname, FILTER_VALIDATE_EMAIL)) {
$u = $this->User->findByemail($uname);
} else { //login via username
$u = $this->User->findByusername($uname);
}
if ($u) {
$this->request->data['User']['username'] = $u['User']['username'];
/* * *
* Error if user is not active
*/
if ($u['User']['user_status'] != 'active') {
$this->Session->setFlash(__('Sorry! Your account is not active.'), 'default', array('class' => 'alert alert-danger'));
} elseif ($this->Auth->login()) { //if logged in
$user_caps = $this->fetchCapabilitiesByRole($u['User']['role']);
$this->Session->write("Auth.User.privileges", array('capabilities' => $user_caps['capabilities'], 'geo_areas' => array()));
if ($u['User']['role'] == 'A' || $u['User']['role'] == 'RA' || $u['User']['role'] == 'Af' || $u['User']['role'] == 'MAfA' || $u['User']['role'] == 'FAA')
return $this->redirect(array('controller' => 'dashboard', 'action' => 'view'));
return $this->redirect($this->Auth->redirect());
}else { //if invalid
$this->Session->setFlash(__('Invalid username or password.'), 'default', array('class' => 'alert alert-danger'));
}
} else {//if user does not exists
$this->Session->setFlash(__('User does not exists.'), 'default', array('class' => 'alert alert-danger'));
}
}
}
It's been a while since the question was answered but hopefully this can help to ones that come after me.
I've written short walkthrough on how to setup 'remember me' functionality using Auhenticate Plugin from Ceeram
More info here: http://mirkoborivojevic.com/posts/2013/08/10/setup-remember-me-functionality-in-cakephp/
I am using CakePHP 2x with Auto-Login component. The problem is, I can write the stuff but, I am not sure how to implement it to read and authorize. When user arrives at the page, he still has the cookie in his browser but, how do I authorize it?
My Login script:
public function login() {
if ($this->Auth->user('id')) {
$this->redirect(array('action' => 'dashboard'));
}
if($this->request->data['User']['auto_login']):
$this->AutoLogin->write($this->request->data['User']['username'],
$this->request->data['User']['password']);
endif;
if ($this->request->is('post')) {
if ($this->Auth->login( )) {
//$this->redirect(array('controller' => 'users', 'action' => 'dashboard'));
return $this->redirect($this->Auth->redirect( ));
}
else
{
$this->Session->setFlash(__('Username or Password is incorrect'), 'default', array( ), 'auth');
}
}
This should be something like:
public function login()
{
if ($this->request->is('post'))
{
if ($this->Auth->login())
{
if ($this->request->data['User']['persist'] == '1')
{
$cookie = array();
$cookie['username'] = $this->data['User']['USER_LOGINNAME'];
$cookie['password'] = $this->data['User']['USER_PASSWORD'];
$this->Cookie->write('Auth.User', $cookie, true, '+4 weeks');
}
$this->redirect($this->Auth->redirect());
}
else
{
$this->Session->setFlash('Your username or password was incorrect.', 'default/flash-error');
}
}
else
{
$user = $this->Auth->user();
if (empty($user))
{
$cookie = $this->Cookie->read('Auth.User');
if (!is_null($cookie))
{
$user = $this->User->find('first', array('conditions' => array('USER_LOGINNAME' => $cookie['username'], 'USER_PASSWORD' => AuthComponent::password($cookie['password']))));
if ($this->Auth->login($user['User']))
{
$this->Session->delete('Message.auth');
$this->redirect($this->Auth->redirect());
}
else
{
$this->Cookie->delete('Auth.User');
}
}
}
else
{
$this->redirect($this->Auth->redirect());
}
}
}
This gives you the idea of how to achieve the same task, however, I used form fields according to my DB Structure.
Kindly change the form fields according to your DB Structure.
What I want to implement is a simple login page, if user login successfully, then redirect to main page, else remain login page.
I have 1 controller named login, and 1 model named main.
When user click the login button, the login/login_send will be called.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller{
function __construct() {
parent::__construct();
$this->load->model('model_login');
}
function index()
{
if ($this->model_login->is_logged_in())
{
redirect('main');
}
else
{
// load login page
$data['main'] = 'view_login';
$data['style'] = 'style_login';
$this->load->view('template', $data);
}
}
function login_send()
{
$this->form_validation->set_rules('username', 'Username', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run() == FALSE)
{
$this->index();
}
else
{
if ( $this->model_login->validate_user() )
{
$user_session_data = array(
'username' => $this->input->post('username'),
'is_logged_in' => 1
);
$this->session->set_userdata($user_session_data);
redirect('main');
}
else
{
redirect('login');
}
}
}// end function login_send
function logout()
{
if ($this->model_login->is_logged_in())
{
$this->session->sess_destroy();
$this->session->set_userdata(array('username' => '', 'is_logged_in' => 0));
log_message('debug', 'Some variable was correctly set');
}
redirect('login','refresh');
}
}// end class Login
?>
Model_login here is just to help to verify if user is logged in, by check the session data.
<?php
class Model_login extends CI_MOdel{
function _isUserExist($username, $password)
{
$options = array(
'UserName' => $username,
'Password' => $password
);
$query = $this->db->get_where('userinfo', $options);
return $query->num_rows() > 0;
}
function validate_user()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
return ($this->_isUserExist($username, $password));
}
function is_logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if ( !isset($is_logged_in) || $is_logged_in != 1 ) return FALSE;
else return TRUE;
}
}// end class model_login
?>
When first time login, and then logout, there is no problem. However, if I login second time, I can not log out. Even the login/logout was called correctly, I also refreshed the page, but the session['is_logged_in'] == 1. Something wrong with my code?
In your application/config/config.php try changing
$config['sess_time_to_update'] = 300; //This is the default setting in ver 2.1.1
to
$config['sess_time_to_update'] = 0;
This gave me some problems a few years back