I have an issue setting session data. I want to set the session data to a boolean 'loggedIn' and an id 'userID'. For some reason when submitting the login form, the login() function will reach the line where it redirects to the dashboard() function, but then stops at the dashboard function.
Controllers
public function login() {
// echo 'login page';
$this->session->set_userdata('userID', NULL);
$this->session->set_userdata('loggedIn', NULL);
$data['session_data'] = array(
'userID' => $this->session->userdata('userID'),
'loggedIn' => $this->session->userdata('loggedIn')
);
$this->load->view('navigation');
$this->load->view('login', $data);
if ($this->session->userdata('loggedIn') == TRUE) {
$this->session->set_flashdata('error_msg', 'please log out to access this page ');
echo 'Please log out to access this page!...';
sleep(2);
redirect('index.php/user/dashboard');
}
if ($this->input->post('login')) {
$this->form_validation->set_rules('username', 'username', 'required');
$this->form_validation->set_rules('password', 'password', 'required');
$login_details = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
if ($this->form_validation->run() == true) {
$this->session->set_flashdata('sucess_msg', 'form running ');
$verify_password = $this->user_model->verify_password($login_details);
if ($verify_password == true) {
$this->session->set_flashdata('error_msg', 'password verified true ');
$userID = $this->user_model->get_userID($login_details);
$data_session = array(
'loggedIn' => TRUE,
'userID' => $userID
);
$session_loggedIn = array('loggedIn' => TRUE);
$session_userID = array('userID' => $userID);
$this->session->set_userdata('loggedIn', $session_loggedIn);
$this->session->set_userdata('userID', $session_userID);
//$this->session->set_userdata('loggedIn', $data_session['loggedIn']);
//$this->session->set_userdata('userID', $data_session['userID']);
$this->session->set_flashdata('success_msg', 'loggedIn and userID changed to current log in account ');
echo 'USER ID: ' . $this->session->userdata('userID');
//$this->load->view('dashboard', $);
redirect('index.php/user/dashboard');
} else {
$this->session->set_flashdata('error_msg', 'wrong email or password, try again!...');
//redirect('index.php/user/login');
}
}
}
}
public function dashboard() {
if ($this->session->userdata('loggedIn') == FALSE) {
$this->session->set_flashdata('error_msg', 'please log in to access the dashboard page');
sleep(2);
redirect('index.php/user/login');
} else {
$data['user'] = array(
'user' => $this->user_model->get_user_data($this->session->userdata('userID'))
);
$this->load->view('navigation');
$this->load->view('dashboard', $data);
}
}
Models
public function verify_password($login_details){
$this->db->select('password');
$this->db->from('user_account');
$this->db->where('username', $login_details['username']);
$query = $this->db->get->result_array();
if($query[0] == $login_details['password']){
return true;
} else {
return false;
}
}
Config
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = APPPATH.'cache/sessions/';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = TRUE;
Result
session data: Array ( [userID] => [loggedIn] => )
session data: Array ( [__ci_last_regenerate] => 1522538883 [userID] => [loggedIn] => )
The program will reach the first condition of the dashboard function and then redirect back to the login page because it says that the session data 'loggedIn' is not set to TRUE.
Related
I want to use Session data as a condition for a query in database, but it only returns NULL. I have tried $this->session->userdata('account'), but it still won't work.
Function - Login/Set Userdata :
public function login_auth()
{
$this->load->helper('security');
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
if ($this->form_validation->run() == FALSE) {
if(isset($this->session->userdata['logged_in'])){
$this->dashboard();
}else{
$this->index();
}
} else {
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$result = $this->agent_model->login($data);
if ($result == TRUE) {
$username = $this->input->post('username');
$result = $this->agent_model->read_user_information($username);
if ($result != false) {
$session_data = array(
'username' => $result[0]->username,
'owner' => $result[0]->owner,
'account' => $result[0]->account,
'id' => $result[0]->id
);
$this->session->set_userdata('logged_in', $session_data);
$this->dashboard();
}
} else {
$data = array(
'error_message' => 'Invalid Username or Password'
);
$this->load->view('header');
$this->load->view('pages/login', $data);
$this->load->view('footer');
}
}
}
Function - Using Userdata->Account as a condition(From Another Function)
$sess_account = $this->session->userdata('account');
var_dump($this->session->userdata('account'));
$coords = $this->map_model->get_coordinates($sess_account);
Am i missing something here? Any help is truly appreciated. Thank you!
If you are certain that the session item 'logged_in' should have been set and $this->session->userdata['logged_in'] is returning null it is likely you do not have session configured correctly.
It's almost always improper $config value for session and or cookie items.
Here is a git repo that should help you test your setup.
I have users table where I am storing the user logged in time in a timestamp column and the datatype is int(11). I am trying to check which users have not logged in during the past 60 days and redirect them to the reset password page. Can any one help me how to do that?
Here is my controller:
public function login_user() {
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean', 'required');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean', 'required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('login_view');
} else {
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$result = $this->Login_model->login($data);
$sessionres = $this->Login_model->sessionStore($data);
if ($result == 1) {
$userData = $this->Login_model->getUserData($data);
$sessionArray = array(
'is_logged' => TRUE,
'user_name' => $data['username'],
'first_name' => $userData['firstname'],
'last_name' => $userData['lastname'],
'userlevel' => $userData['userlevel'],
'organisation_id' => $userData['organisation_id'],
'user_id' => $userData['id'],
'lastip' => $userData['lastip']
);
$this->session->set_userdata($sessionArray);
redirect('dashboard');
} else if ($result == 2) {
$this->session->set_flashdata('message', 'Password seems to be wrong!');
$this->load->view('login_view', $data);
} else if ($result == 4) {
$this->session->set_flashdata('message', 'Username is not active!');
$this->load->view('login_view', $data);
}else {
$this->session->set_flashdata('message', 'Username not found!');
$this->load->view('login_view', $data);
}
}
}
Well, if you have the user's last logged in timestamp, then you could check if it falls within the last two months, and if not, redirect the user to password reset page.
Let's say you have the user's last logged in time in $userData['timestamp'], then just before redirect('dashboard'); you can add something like this:
$this->session->set_userdata($sessionArray);
if ($userData['timestamp'] > strtotime('-2 months')){
redirect('dashboard');
die();
}else{
redirect('reset-password');
die();
}
I assume that 'reset-password' is the route to password reset page and $userData['timestamp'] contains the user's last logged in time.
Hope it helps!!
I am building a website wherein I have an admin and user page. I have a problem wherein I can access the admin page via URL even though I am logged in as a user. I have validation checks at the login page, however if I am already logged in as a user or as an admin, I can access all the pages. I want to restrict the pages to their roles only. Here's my code.
MY_Controller:
function __construct()
{
parent::__construct();
$this->is_logged_in();
$session_admin = $this->session->userdata('isAdmin');
$method = $this->router->fetch_method();
if(($session_admin == FALSE) && $method != 'login')
{
$this->session->set_flashdata( 'message', 'You need to login to access this location' );
redirect('user_home');
}
else
{
redirect('admin_ticketing/new_tickets');
}
}
function is_logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if(!isset($is_logged_in) || $is_logged_in != true) {
redirect('login');
die();
}
}
Model:
function validate()
{
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$query = $this->db->get('accounts');
$result = $query->row();
if($query->num_rows() == 1)
{
return true;
}
else
{
return false;
}
}
function check_role()
{
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$this->db->where('role', 1);
$query = $this->db->get('accounts');
$result = $query->row();
if($query->num_rows() == 1)
{
$data = array(
'userid' => $result->userid,
'username' => $result->username,
'password' => $result->password,
'firstname' => $result->firstname,
'lastname' => $result->lastname,
'email' => $result->email,
'address' => $result->address,
'monthly_dues' => $result->monthly_dues,
'arrears' => $result->arrears,
'isAdmin' => true,
'contactnum' => $result->contactnum,
'role' => $result->role,
'is_logged_in' => true
);
$this->session->set_userdata($data);
return true;
}
else
{
return false;
}
}
function check_user()
{
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$this->db->where('role', 0);
$query = $this->db->get('accounts');
$result = $query->row();
if($query->num_rows() == 1)
{
$data = array(
'userid' => $result->userid,
'username' => $result->username,
'password' => $result->password,
'firstname' => $result->firstname,
'lastname' => $result->lastname,
'email' => $result->email,
'address' => $result->address,
'monthly_dues' => $result->monthly_dues,
'arrears' => $result->arrears,
'isAdmin' => false,
'contactnum' => $result->contactnum,
'role' => $result->role,
'is_logged_in' => true
);
$this->session->set_userdata($data);
return true;
}
else
{
return false;
}
}
function check_active()
{
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$this->db->where('isActive', 1);
$query = $this->db->get('accounts');
$result = $query->row();
if($query->num_rows() == 1)
{
return true;
}
else
{
return false;
}
}
Controller:
function validate_login()
{
$this->load->model('model_accounts');
$valid = $this->model_accounts->validate();
$isAdmin = $this->model_accounts->check_role();
$isUser = $this->model_accounts->check_user();
$isActive = $this->model_accounts->check_active();
if($valid && $isAdmin && $isActive) // Active Admin
{
redirect('admin_ticketing/new_tickets');
}
else if($valid && $isActive && $isUser) // Active User
{
redirect('user_home');
}
else if(($valid && $isAdmin) && $isActive == false) //Deactivated Admin
{
redirect('login/admindeact');
}
else if($valid && ($isActive && $isAdmin) == false) //Deactivated User
{
redirect('login/userdeact');
}
else if($valid == false) //Invalid Account
{
$data['message'] = "Sorry, the username and password you entered did not match our records. Please double-check and try again. ";
$this->template->load('template', 'view_login', $data);
}
}
You can check this in your controller, See this code,
function __construct()
{
parent::__construct();
$session_admin = $this->session->userdata('admin'); //getting admin session
$method = $this->router->fetch_method(); // get the current method
if(empty($session_admin) && $method != 'login'){ // check for admin session and methos is login
$this->session->set_flashdata( 'message', 'You need to login to access this location' );
redirect('admin/users/login');
}
}
If you only want to set roles for admin and front-user simply at the time of login, set a session value 'is_admin'
Then you can check if($is_admin) like that.
how can I stay in dashboard when the user is logged even though when the user write localhost/storeLTE/login/ then stay home. but my code doesnt work.
public function getAccess(){
if ($this->session->set_userdata('username')) {
redirect('home');
}
$username = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean($this->input->post('password'));
$array = $this->User_model->login($username,$password);
if($array[0] == 0){
echo 0;
}else{
$data_session = array(
'id' => $array[0]['iduser'],
'username' => $array[0]['username'],
'password' => $array[0]['password'],
'name' => $array[0]['name'],
'last_name' => $array[0]['last_name'],
'type' => $array[0]['idType'],
'logged_in' => TRUE
);
$this->session->set_userdata('log',$data_session);
}
}
if ($this->session->set_userdata('username')) {
should be
if ($this->session->userdata('username')) {
or
if ($this->session->userdata('username') !== NULL) {
//since NULL is returned if item is not found
Docs.
FYI
Its is NOT a good sign of STORING PASSWORD IN THE SESSION. Its better to store name, type, logged_in, id.
In Controller
function getAccess(){
$this->load->library('session'); # load library here or in autoload.php
if($this->session->userdata('logged_in') == TRUE)
{
redirect('home');
}
else
{
$username = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean($this->input->post('password'));
$result = $this->User_model->login($username,$password);
if($result == FALSE)
{
echo 'Invalid Login';
}
else{
$data_session = array(
'id' => $result[0]['iduser'],
'username' => $result[0]['username'], # Better to remove
'password' => $result[0]['password'], # Better to remove
'name' => $result[0]['name'],
'last_name' => $result[0]['last_name'],
'type' => $result[0]['idType'],
'logged_in' => TRUE
);
$this->session->set_userdata('log',$data_session);
$this->load->view('home'); # Load the view
}
}
}
In Model
function login($username,$password)
{
$query = $this->db->query("SELECT * FROM table name WHERE username = '$username' AND password = '$password'");
$result = $query->result_array();
if (count($result) > 1 || empty($result))
{
return FALSE;
}
else {
return $result;
}
}
if ($this->session->set_userdata('username')) {
redirect('home');
}
change this to
if ($this->session->userdata('username') !='') {
redirect('home');
}
this is a controller where i'm creating a session :
public function login(){
if(isset($_POST)){
$res = $this->register_model->loginUser();
if($res['result'] === true){
// declare session variables
$user = $res['info']; // array containing user information
// set session variables
$_SESSION['storeId'] = $user->str_id;
$_SESSION['sName'] = $user->str_nme;
$_SESSION['sId'] = $user->str_identifier;
$_SESSION['hash'] = $user->hash;
$res['info'] = null;
}
} else {
$res = array('result'=>false,'msg'=>'Login failed. Please try again');
}
echo json_encode($res);
}
and this is a controller where i retrieve a session
Try this
public function login(){
if(isset($_POST)){
$res = $this->register_model->loginUser();
if($res['result'] === true){
// declare session variables
$user = $res['info']; // array containing user information
// set session variables
$this->load->library('session');
$newdata = array(
'storeId' => $user->str_id,
'sName' => $user->str_nme,
'sId' => $user->str_identifier,
'hash' => $user->hash,
'info' => null,
'logged_in' => TRUE,
);
$this->session->set_userdata($newdata);
}
} else {
$res = array('result'=>false,'msg'=>'Login failed. Please try again');
}
echo json_encode($res);
}