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);
}
Related
function auth(){
$nic = $this->input->post('nic',TRUE);
$password = md5($this->input->post('password',TRUE));
$this->load->model('Login_model');
$validate = $this->Login_model->validate($nic,$password);
$this->load->helper("cookie");
$autoLogin = $this->input->post("autologin",true);
if($validate->num_rows() > 0){
$data = $validate->row_array();
$nic = $data['user_nic'];
$name = $data['user_name'];
$email = $data['user_email'];
$level = $data['user_level'];
$sesdata = array(
'nic' => $nic,
'username' => $name,
'email' => $email,
'level' => $level,
'logged_in' => TRUE
);
$this->session->set_userdata($sesdata);
if($level === '1'){
redirect('Forget/dashboard');
// access login for staff
}elseif($level === '2'){
redirect('welcome/officer_dashboard');
// access login for author
}elseif($level === '3'){
redirect('User/User_Dashboard');
}
}else{
echo $this->session->set_flashdata('msg','Username or Password is Wrong');
redirect('welcome');
}
}
}
This is my user auth function which redirects to ages upon user levels. I have many views as per the User levels.
But whenever I have loggedin, the second tab base url redirects to Login page again.
TIA
Debug the session data(using print statements) and make sure that you have added proper conditions in each page based on session data
I Welcome controller, Check the session data is_logged in, If data available act according to it
public function index()
{
$session_id = $this->session->userdata('nic');
if (!empty($session_id))
{
$this->load->view('login');
}
else
{
redirect('welcome/auth');
}
}
My main project is created in core php and I am working on one module which is in codeigniter in same project folder.
$_SESSION['UserName'] = $loginDetailAr['UserName'];
$_SESSION['UserType'] = $loginDetailAr['UserType'];
$_SESSION['UserTypeName'] = $loginDetailAr['UserTypeName'];
$_SESSION['IsAdmin'] = $loginDetailAr['IsAdmin'];
this can help you
$this->load->library('session');
$result = $this->login_model->userLogin($email, $password);
if ($result) {
$sess_array = array();
foreach ($result as $loginDetailAr) {
$sess_array = array(
'UserName' => $loginDetailAr->UserName,
'UserType' => $loginDetailAr->UserType,
'UserTypeName' => $loginDetailAr->UserTypeName,
'IsAdmin' => $loginDetailAr->IsAdmin,
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
} else {
$this->form_validation->set_message('check_database', ' Invalid Email Or Password ');
return FALSE;
}
Load the session library
$this->load->library('session');
// can access variables with this->session
$is_admin = $this->session->IsAdmin;
For more details please refer.
https://www.codeigniter.com/user_guide/libraries/sessions.html
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');
}
I'm working on magento module to log in customer with API.
I can log in customer and get frontend sessionId,
but when I want to load session with this sessionId to check if the customer is already logged in I can't.
Here the API function I used:
public function login($email,$password,$storecode){
$result = array();
$result['code'] = '';
$result['messages'] = '';
try{
$session = Mage::getSingleton('customers/session');
$storemodel = Mage::getModel('core/store')->load($storecode);
$store_id = $storemodel->getId();
$websiteId = $storemodel->getWebsiteId();
if($session->loginByApi($email, $password,$websiteId)){
$result['code'] = 'SUCCESS';
$result['sessionId'] = $session->getSessionId();
$customer = $session->getCustomer();
$result['customer']= array(
'customerid' => $customer->getId(),
'firstname' => $customer->getFirstname(),
'lastname' => $customer->getLastname(),
);
}
} catch (Mage_Core_Exception $e) {
$result['code'] = 'ERRORS';
$result['messages'] = $e->getMessage();
}
return $result;
}
public function isloggedin($customerId,$customersessionId ,$storecode){
if(!isset($storecode)){
$storecode = 'default';
}
Mage::app($storecode, 'store');
$core_session = Mage::getSingleton('core/session', array('name'=>'frontend'));
if($customersessionId != null){
$core_session->setSessionId($customersessionId);
$core_session->start('frontend');
}
$session = Mage::getSingleton('customer/session', array('name'=>'frontend'));
$customer = Mage::getModel('customer/customer')->load($customerId);
$session->setCustomer($customer);
if($session->isLoggedIn()){
$session->setCustomerAsLoggedIn($customer);
$result['sessionId'] = $session->getSessionId();
}else{
$result['logged'] = false;
}
return $result;
}
Anyone have an idea?
Not sure if this helps too much, but this code:
Mage::app('2', 'store');
$s = Mage::getSingleton('customer/session', array('name'=>'frontend'));
$c = Mage::getModel('customer/customer')->load(1);
$s->setCustomer($c);
if($s->isLoggedIn()){
echo $c->getName()." is logged in, session: ".$s->getSessionId().PHP_EOL;
} else {
echo "not logged in".PHP_EOL;
}
Did seem to work for me:
John Smith is logged in, session: d3rcgvd56md4u3cfctcvnt2ou6
If you have the Session ID, you can get at the data with the following call to the core session singleton:
$sessId = 'sn1q4ndvr1kieumsmplhd39n83';
$sess = Mage::getSingleton('core/session', array( 'value' => $sessId ));
That will retrieve the session for any user, logged-in or not. From there you can determine whether the session belongs to a customer with a check for the customer object:
$sessionCustomerId = $sess->getCustomer()->getId();
if ( $sessionCustomerId ) {
// yay, they are a customer!
echo $sessionCustomerId;
}
Hope that helps.
Edit:
You can get the session id from the core session (in a chicken-and-egg style) using Mage::getSingleton('core/session')->getEncryptedSessionId()
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.