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');
}
Related
After register into form , data does exist in the database but when i login the data can't be fetch instead it gives a msg " Unregister Account"
Doesn't display any error but just display the msg.
if ($postjson['action'] == 'login') { //login
$password = md5($postjson['password']);
$query = mysqli_query($mysqli, "SELECT * FROM user WHERE username='$postjson[username]' AND password='$password'");
$check = mysqli_num_rows($query);
if ($check > 0) {
$data = mysqli_fetch_array($query);
$datauser = array(
'user_id' => $data['user_id'],
'username' => $data['username'],
'password' => $data['password']
);
if ($data['status'] == 'y') {
$result = json_encode(array('success' => true, 'result' => $datauser));
} else {
$result = json_encode(array('success' => false, 'msg' => 'Account Inactive'));
}
} else {
$result = json_encode(array('success' => true, 'msg' => 'Unregister Account'));
}
echo $result;
}
The database
I think your query is not getting any records because of password not matching in database.
Once your query get record it will work, Just debug why password is not matching, because of md5? give it try
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 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.
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.
So after debugging my session array while logging into my website, I find that when posting a form, all session data is lost. The session data is wiped when the updateDetails and changePassword methods are called. Why is this?
session_start() is called before any data processing
Upon a POST request, session data is set and unset (but not the entire $_SESSION variable)
I use the following code to check for POST requests:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
}
It only happens once: Once the session has been lost, the methods can be called without the issue occuring any further (until they lose the session through expiration or closing their browser).
index.php (part)
session_start();
$page = $_GET['p'];
$query = $_GET['q'];
$req = $_GET['req'];
$user = new User();
switch($page) {
case 'account':
if($req=="logout") {
if($user->isLoggedIn())
$user->logout();
header("Location: /?p=account");
exit();
}
else if($req=="signup") {
if($user->isLoggedIn()) {
header("Location: /?p=account");
exit();
}
else {
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$form_data = array('username' => $_POST['username'],
'password' => $_POST['password'],
'password_repeat' => $_POST['password_repeat'],
'title' => $_POST['title'],
'first_name' => $_POST['first_name'],
'surname' => $_POST['surname'],
'dob_day' => $_POST['dob_day'],
'dob_month' => $_POST['dob_month'],
'dob_year' => $_POST['dob_year'],
'gender' => $_POST['gender'],
'email' => strtolower($_POST['email']),
'email_repeat' => strtolower($_POST['email_repeat']));
if($user->signup($form_data)) {
header("Location: /?p=account");
exit();
}
}
}
}
else {
if($user->isLoggedIn()==true) {
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if($req=='editdetails') {
$form_data = array(
'title' => $_POST['title'],
'first_name' => $_POST['first_name'],
'surname' => $_POST['surname'],
'gender' => $_POST['gender'],
'phone' => $_POST['phone'],
'email' => strtolower($_POST['email']),
'password' => $_POST['password']
);
if($user->updateDetails($form_data)) {
header("Location: /?p=account");
exit();
}
}
else if($req=='changepassword') {
$form_data = array(
'old_password' => $_POST['old_password'],
'password' => $_POST['password'],
'password_repeat' => $_POST['password_repeat'],
);
if($user->changePassword($form_data)) {
header("Location: /?p=account");
exit();
}
}
}
$user->retrieveUserDetails();
$details=$user->getUserDetails();
}
else {
if($req) {
header("Location: /?p=account");
exit();
}
else if($_SERVER['REQUEST_METHOD'] == 'POST') {
$form_data = array('username' => $_POST['username'], 'password' => $_POST['password']);
if($user->login($form_data)) {
$user->retrieveUserDetails();
$details=$user->getUserDetails();
}
}
}
}
break;
}
user.php (part)
class User {
private $auth;
private $details;
private $session_alert;
function User() {
if(isset($_SESSION['alert']))
$this->session_alert = $_SESSION['alert'];
$this->auth = isset($_SESSION['auth']) ? $_SESSION['auth'] : null;
if(isset($this->auth)) {
$database= new Database;
if($database->checkUserSession($this->auth['user_id'],session_id())) {
$this->logged_in=true;
}
else {
$this->addSessionAlert('global','Your login session has possibly timed out, you may login again by clicking here.',true);
unset($_SESSION['auth']);
}
}
}
function login($data) {
$return = false;
$this->form = new Form($data,0);
if(!$this->form->getError()) {
$database= new Database;
$error_msg = "The username/password entered was invalid. Please check to see if they are correct and try again, or use the relevant links to recover your account.";
$salt = $database->getSaltByUsername($data['username']);
if($salt) {
$hash = $this->hashpwd($data['password'],$salt);
// Do login
$this->auth = array();
$this->auth['user_id'] = $database->checkUserByHash($data['username'],$hash);
if($this->auth['user_id']) {
session_regenerate_id();
if($database->doLogin($this->auth['user_id'],session_id())) {
$details=$database->getUserDetailsById($this->auth['user_id']);
$this->auth['first_name'] = $details['first_name'];
$_SESSION['auth']=$this->auth;
$this->logged_in=true;
$return = true;
}
else
$this->form->pushError('Something went wrong, please try again.');
}
else
$this->form->pushError($error_msg);
}
else
$this->form->pushError($error_msg);
}
return $return;
}
function logout() {
$return = false;
if(isset($this->auth)) {
$database= new Database;
if($database->clearUserSession($this->auth['user_id'],session_id())) {
unset($_SESSION['auth']);
$this->logged_in=false;
session_regenerate_id();
$return = true;
}
}
return $return;
}
function signup($data) {
$return = false;
$this->form = new Form($data,1);
if(!$this->form->getError()) {
$database= new Database;
if($database->checkUserByUsername($data['username']))
$this->form->pushError("The username entered already exists, please try again.");
else if($database->checkUserByEmail($data['email']))
$this->form->pushError("The e-mail address entered is already in use, please try again.");
else {
$dbarray = $data;
unset($dbarray['password'],$dbarray['password_repeat'],$dbarray['dob_month'],$dbarray['dob_day'],$dbarray['dob_year']);
$dbarray['dob']=date("Y-m-d", mktime(0,0,0,$data['dob_month'], $data['dob_day'], $data['dob_year']));
$dbarray['salt']=strtoupper(md5(mt_rand()));
$dbarray['hash'] = $this->hashpwd($data['password'],$dbarray['salt']);
// Do signup
$this->auth = array();
$this->auth['user_id'] = $database->newUser($dbarray);
if($this->auth['user_id']) {
session_regenerate_id();
if($database->doLogin($this->auth['user_id'],session_id())) {
$details=$database->getUserDetailsById($this->auth['user_id']);
$this->auth['first_name'] = $details['first_name'];
$_SESSION['auth']=$this->auth;
$this->logged_in=true;
}
$return=true;
}
else {
$this->form->pushError("Something went wrong, please try again.");
}
}
}
return $return;
}
function updateDetails($data) {
$return = false;
$this->form = new Form($data,2);
if(!$this->form->getError()) {
$database= new Database;
if( $database->checkUserByEmailNotById($data['email'],$this->auth['user_id']) ) {
$this->form->pushError("The e-mail address entered is already in use, please try again.");
}
else {
$salt = $database->getSaltById($this->auth['user_id']);
if($salt) {
$hash = $this->hashpwd($data['password'],$salt);
if($database->checkUserIdByHash($this->auth['user_id'],$hash)) {
$database->updateUserById($this->auth['user_id'],$data);
$return = true;
}
else
$this->form->pushError("The password entered was incorrect, please try again.");
}
}
}
return $return;
}
function changePassword($data) {
$return = false;
$this->form = new Form($data,3);
if(!$this->form->getError()) {
$database= new Database;
$salt = $database->getSaltById($this->auth['user_id']);
if($salt) {
$hash = $this->hashpwd($data['old_password'],$salt);
if($database->checkUserIdByHash($this->auth['user_id'],$hash)) {
$salt=strtoupper(md5(mt_rand()));
$hash = $this->hashpwd($data['password'],$salt);
if($database->updateSaltHashById($this->auth['user_id'],$salt,$hash)) $this->addSessionAlert('yourdetails','Your password has been changed successfully.',false);
$return = true;
}
else
$this->form->pushError("The old password entered was incorrect, please try again.");
}
}
return $return;
}
function isLoggedIn() {
return $this->logged_in;
}
function getUserDetails() {
return $this->details;
}
}
Starting a session inside a class's contructor method, just does not sound nice.
Use session_start(); at the top of the index.php page instead.
in each page where you want to use sessions you must call session_start ();
See here:
http://codex.wordpress.org/Function_Reference/wp_update_user
Note: If current user's password is being updated, then the cookies
will be cleared!
Now, why WordPress will do this is not clear, but it is clearly stated that cookies, and therefore sessions, will be removed on setting a password through wp_update_user().
Some people have found that applying an exit(); immediately after a redirect when setting the password, will prevent the cookies from being lost.