Magento, see if back-end user is online? - magento

I have a Magento website.
There is admin user, thats me, and a other user.
How can I see if the other user is logged in (back-end) ?
EDIT
Thanks to Sandeep I now have this:
<?php
$session = Mage::getSingleton('admin/session');
$userDetails = Mage::getSingleton('admin/session');
// Get data from the session $userID =
$userDetails->getUser()->getUserId();
// Get user ID $userID =
$userDetails->getUser()->getEmail();
// Use the 'admin/session' object to check loggedIn status
if ( $session->isLoggedIn() ) {
echo "Ingelogd";
} else {
echo "Niet ingelogt";
}
?>

$session = Mage::getSingleton('admin/session');
// Use the 'admin/session' object to check loggedIn status
if ( $session->isLoggedIn() ) {
echo "logged in";
} else {
echo "not logged in";
}

Related

Change password for logged in user (codeigniter)

Is there any solution how to make change password for logged in user? i want to make a change password for logged in user, the code i made only change user password with user id number 1. it doesn't change for logged in user. so any idea?
this is my controller:
public function update(){
$this->form_validation->set_rules('password', 'Current Password', 'required|alpha_numeric|min_length[6]|max_length[20]');
$this->form_validation->set_rules('newpass', 'New Password', 'required|alpha_numeric|min_length[6]|max_length[20]');
$this->form_validation->set_rules('confpassword', 'Confirm Password', 'required|alpha_numeric|min_length[6]|max_length[20]');
if($this->form_validation->run()){
$cur_password = $this->input->post('password');
$new_password = $this->input->post('newpass');
$conf_password = $this->input->post('confpassword');
$this->load->model('queries');
$userid = '1';
$passwd = $this->queries->getCurrPassword($userid);
if($passwd->password == $cur_password){
if($new_password == $conf_password){
if($this->queries->updatePassword($new_password, $userid)){
echo 'Password updated successfully';
}
else{
echo 'Failed to update password';
}
}
else{
echo 'New password & Confirm password is not matching';
}
}
else{
echo'Sorry! Current password is not matching';
}
}
else{
echo validation_errors();
}
This is my model:
public function getCurrPassword($userid){
$query = $this->db->where(['id'=>$userid])
->get('users');
if($query->num_rows() > 0){
return $query->row();
} }
public function updatePassword($new_password, $userid){
$data = array(
'password'=> $new_password
);
return $this->db->where('id', $userid)
->update('users', $data); }
You can initialize a session when the user logs in to the system at the beginning, and store the information of the user in that session, like this:
function login() {
$query = $this->db->select(*)
->from('table_name')
->where('your parameters....');
return $query->row();
}
function index() {
$userid = $this->login()->id; //id of the user which is currently logged IN
$this->session->set_userdata('current_userId', $userid);
}
You have now stored the id of currently logged IN user in the session. You can access the id by $this->session->userdata('current_userId');. Replace your $userid = '1' by the session data. Also, you will have to load the session library in order to do so.

Codeigniter Login controller views

function index()
{
# code...
$this->load->view('signin');
$username = $this->input->post('username');
$password = $this->input->post('password');
$this->load->model('LoginModal');
if ($this->LoginModal->login_valid($username, $password)) {
# code...
echo "Login Succesfully";
}
else
{
$wrong = "Wrong Credentials";
$this->load->view('signin',['wrong'=>$wrong]);
}
}
This is my controller in codeiniter i want to pass wrong credentials values to the views if the login password is wrong but it shows two views of the same page if the login credentials are wrong
Kindly please help me
Thanks
Regards
Here's my proposal. Enjoy coding in codeigniter.
<?php
function index()
{
$this->load->model('LoginModal');
$data = array();
$data['wrong'] = '';
# code...
if($this->input->post()) {
$username = $this->input->post('username');
$password = $this->input->post('password');
if ($this->LoginModal->login_valid($username, $password)) {
# code...
echo "Login Succesfully";
//maybe redirect if you want
redirect('../home', 'refresh');
} else {
$data['wrong'] = "Wrong Credentials";
}
}
$this->load->view('signin',$data);
}

Magento: Login and redirect to account page from outside magento

I am using this below code to login and redirect to account page:
<?php
include('store/app/Mage.php');
Mage::app();
if($_POST && $_POST['login']['username'] && $_POST['login']['password']){
$email = $_POST['login']['username'];
$password = $_POST['login']['password'];
$session = Mage::getSingleton('customer/session');
try {
$log = $session->login($email, $password);
$session->setCustomerAsLoggedIn($session->getCustomer());
$customer_id = $session->getCustomerId();
$send_data["success"] = true;
$send_data["message"] = "Login Success";
$send_data["customer_id"] = $customer_id;
Mage::getSingleton('customer/session')->loginById($customer_id);
Mage_Core_Model_Session_Abstract_Varien::start();
}catch (Exception $ex) {
$send_data["success"] = false;
$send_data["message"] = $ex->getMessage();
}
}else {
$send_data["success"]=false;
$send_data["message"]="Enter both Email and Password";
}
echo json_encode($send_data);
?>
And then on file from where I am making ajax request, I am using this code:
if(data.success){
window.location = "http://domain.com/store/customer/account/"
}
But it always show user as logout, though I do get correct customer id as well as success.
$email = strip_tags($_GET["login"]);
$password = strip_tags($_GET["psw"]);
function loginUser( $email, $password ) {
umask(0);
ob_start();
session_start();
Mage::app('default');
Mage::getSingleton("core/session", array("name" => "frontend"));
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId;
$customer->setStore($store);
try {
$customer->loadByEmail($email);
$session = Mage::getSingleton('customer/session')->setCustomerAsLoggedIn($customer);
if($session->login($email, $password)){ return true;} else { };
}catch(Exception $e){
return $e->getMessage();
}
}
if (loginUser($email,$password) == 1) {
echo ".. user loged as ".Mage::getSingleton('customer/session')->getCustomer()->getName()."<br>";} else {
//bad things goes here
}
In my case Martin's code works if I change the session name
session_name('frontend');
session_start();
If you leave the session name alone it defaults PHPSESSID which isn't the same as that created by Magento on a manual login and didn't work in my install. That may vary, try logging in manually and check your cookie names.
session_name documentation: http://php.net/manual/en/function.session-name.php

Magento doesn't assign website id when creating customer programatically

I m creating customer programatically but customer created successfully but can't login with frontend.issue is website id dosen't assign to customer i have tried below code
if ($detail->ContactEmail && $detail->ContactName != '' && filter_var($detail->ContactEmail, FILTER_VALIDATE_EMAIL)) {
$customer = Mage::getModel('customer/customer');
$customer->setWebsiteId(1);
$customer->loadByEmail($detail->ContactEmail);
/*
* Check if the email exist on the system.
* If YES, it will not create a user account.
*/
if (!$customer->getId()) {
//setting data such as email, firstname, lastname, and password
$customer->setEmail($detail->ContactEmail);
$name = preg_split('/\s+/', trim($detail->ContactName));
if (count($name) == 1) {
$customer->setFirstname($name[0]);
$customer->setLastname($name[0]);
} else {
$customer->setFirstname($name[0]);
$customer->setLastname($name[1]);
}
//$customer->setWebsiteId(array(1));
$customer->setcontactJobTitle($detail->ContactJobTitle);
$customer->setcontactSeqNo($detail->ContactSeqNo);
$customer->setdebtorAccNo($detail->DebtorAccNo);
$customer->setdebtorApiKey($debtorAPI);
$customer->setStoreId(Mage::app()->getStore('default')->getId());
$customer->setPassword($customer->generatePassword($passwordLength));
}
try {
//the save the data and send the new account email.
$customer->save();
$customer->setConfirmation(null);
$customer->save();
$customer->sendNewAccountEmail();
$customerCount[] = $i;
//echo 'contact added';
}
catch (Exception $e) {
//echo 'contact not added';
}
I have found where is the problem to saving customer. whenever we load the customer by loadByEmail function we must set website id to load customer otherwise customer save raise the exception Customer website ID must be specified when using the website scope. so I have made following changes to set website id when creating customer.
if ($detail->ContactEmail && $detail->ContactName != '' && filter_var($detail->ContactEmail, FILTER_VALIDATE_EMAIL)) {
$customer = Mage::getModel('customer/customer')->setWebsiteId(1);
$customer->loadByEmail($detail->ContactEmail); /* changed line */
/*
* Check if the email exist on the system.
* If YES, it will not create a user account.
*/
if (!$customer->getId()) {
//setting data such as email, firstname, lastname, and password
$customer->setEmail($detail->ContactEmail);
$name = preg_split('/\s+/', trim($detail->ContactName));
if (count($name) == 1) {
$customer->setFirstname($name[0]);
$customer->setLastname($name[0]);
} else {
$customer->setFirstname($name[0]);
$customer->setLastname($name[1]);
}
$customer->setcontactJobTitle($detail->ContactJobTitle);
$customer->setcontactSeqNo($detail->ContactSeqNo);
$customer->setdebtorAccNo($detail->DebtorAccNo);
$customer->setdebtorApiKey($debtorAPI);
$customer->setStoreId(Mage::app()->getStore('default')->getId());
$customer->setPassword($customer->generatePassword($passwordLength));
}
try {
//the save the data and send the new account email.
$customer->save();
$customer->setConfirmation(null);
$customer->setWebsiteId(1); /* changed line */
$customer->save();
$customer->sendNewAccountEmail();
$customerCount[] = $i;
//echo 'contact added';
}
catch (Exception $e) {
//echo 'contact not added';
}
please find the below code for creating customer programmatically:
error_reporting(E_ALL | E_STRICT);
$mageFilename = 'app/Mage.php';
if (!file_exists($mageFilename)) {
if (is_dir('downloader')) {
header("Location: downloader");
} else {
echo $mageFilename." was not found";
}
exit;
}
require_once $mageFilename;
Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app('default');
$customer_email = 'test#testemail.com';
$customer_fname = 'test_firstname';
$customer_lname = 'test_lastname';
$passwordLength = 10;
$customer = Mage::getModel('customer/customer');
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($customer_email);
if(!$customer->getId()) {
$customer->setEmail($customer_email);
$customer->setFirstname($customer_fname);
$customer->setLastname($customer_lname);
$customer->setPassword($customer->generatePassword($passwordLength));
}
try{
$customer->save();
$customer->setConfirmation(null);
$customer->save();
}
================================================================================

Magento. Customer online, but not logged in

Here is the problem:
I am using a script to create a user in Magento and trying to login this user if he he/she already exists.
try {
// If new, save customer information
$customer -> firstname = $firstname;
$customer -> lastname = $lastname;
$customer -> email = $email;
$customer -> password_hash = md5($password);
if ($customer -> save()) {
echo $customer -> firstname . " " . $customer -> lastname . " information is saved!";
$customer->setConfirmation(null);
$customer->save();
} else {
echo "An error occured while saving customer";
}
} catch(Exception $e) {
// If customer already exists, initiate login
if (preg_match('/This customer email already exists/', $e)) {
$customer -> loadByEmail($email);
$session = Mage::getSingleton('customer/session');
$session -> login($email, $password);
echo $session -> isLoggedIn() ? $session -> getCustomer() -> getName() . ' is online!' : 'not logged in';
}
}
the script echoes "user is online!", but when I go to the main page, it shows me the login button, as if I am not logged in. How do I login the user?
Did you set the website id?
You could also check if the customer exist by loadByEmail
$customer = Mage::getModel('customer/customer');
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
// This customer email exists
if($customer->getId()){
Mage::getSingleton('core/session', array('name' => 'frontend'));
Mage::getSingleton('customer/session')->setCustomerAsLoggedIn($customer);
}
else{
.....
$customer->save();
}
or
$customer = Mage::getModel('customer/customer');
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
if(!$customer->getId()){
$customer->setFirstname($firstname);
$customer->setLastname($lastname);
.....
$customer->save();
}
Mage::getSingleton('core/session', array('name' => 'frontend'));
Mage::getSingleton('customer/session')->setCustomerAsLoggedIn($customer);
See
Auto Login customer to Magento
Programatically create customer

Resources