Magento customer login from outside magento - ajax

I am trying to login as a customer.
I am requesting the Following code (AJAX) and this outside magento store.
<?php
require_once "../app/Mage.php";
umask(0);
Mage::app('default');
Mage::getSingleton("core/session", array("name" => "frontend"));
$user = $_POST['user'];
$password = $_POST['password'];
$session = Mage::getSingleton('customer/session');
$flag = 0;
$resultArr = array();
function customerLogin($user,$password){
try{
$session = Mage::getSingleton('customer/session');
$result = $session->login($user,$password);
$customer = $session->getCustomer();
$session->setCustomerAsLoggedIn($customer);
$resultArr['flag'] = 1;
$resultArr['msg'] ='Logged in as '.$customer->getName();
$jsonReturn = json_encode($resultArr);
return $jsonReturn;
}catch(Exception $e){
$resultArr['flag'] = 0;
$resultArr['msg'] = $e->getMessage();
$jsonReturn = json_encode($resultArr);
return $jsonReturn;
}
}
echo customerLogin($user,$password);
?>
I found the above code is Creating the session files at var/session directory successfully but unable to write customer entry in log_customer DB table . Anybody know whats the problem here.
Thanks :)
UPDATED
Okie the following updated code(customerLogin.php) is working under a condition
<?php
function customerLogin($user,$password){
require_once "./app/Mage.php";
Mage::app('default');
Mage::getSingleton("core/session", array("name" => "frontend"));
$user = $_POST['user'];
$password = $_POST['password'];
$flag = 0;
$resultArr = array();
$session = Mage::getSingleton('customer/session');
try{
$result = $session->login($user,$password);
//$customer = $session->getCustomer();
$session->setCustomerAsLoggedIn($session->getCustomer());
$resultArr['flag'] = 1;
$resultArr['msg'] ='Logged in as '.$session->getCustomer()->getName();
$cusArr = array(
'isLoggedIn' => true,
'name' => $session->getCustomer()->getName(),
'id' => $session->getId(),
'email' =>$session->getCustomer()->getEmail(),
);
$resultArr['customerData'] = $cusArr;
$jsonReturn = json_encode($resultArr);
return $jsonReturn;
}catch(Exception $e){
$resultArr['flag'] = 0;
$resultArr['msg'] = $e->getMessage();
$jsonReturn = json_encode($resultArr);
return $jsonReturn;
}
}
echo customerLogin($user,$password);
?>
if i follow the directory structure like:
|-- app
|-- **customerLogin.php**
|-- downloader
|-- install.php
|-- js
|-- lib
|-- media
|-- var
But its not working if I place code one directory level down like :
|-- app
|-- **customerLogin**
`--**customerLogin.php**
|-- downloader
|-- install.php
|-- js
|-- lib
|-- media
|-- var
Anybody knows whats the problem.
I am wondering why magento is unable to write session entry in log_customer table when i place my code one level down.

Get your customer id then use the below code.
Mage::getSingleton('customer/session')->loginById($customerId);

try this code to login from outside of magento, create demo.php file in magento root and put following code.
include('app/Mage.php');
Mage::app();
if($_POST && $_POST["email"] && $_POST["password"])
{
$email=$_POST["email"];
$password=$_POST["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;
}
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);

store id and website id here set custom
you will change accordance to u
<?php
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
require_once "app/Mage.php";
umask(0);
Mage::app();
$firstname = "krishana";
$lastname = "singh";
$email = "krish.bhati#gmail.com";
$password = "12345678";
// Website and Store details
$websiteId = Mage::app()->getWebsite()->getId('1');
$store = Mage::app()->getStore('31');
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId;
$customer->setStore($store);
$mageRunCode = isset ( $_SERVER ['MAGE_RUN_CODE'] ) ? $_SERVER ['MAGE_RUN_CODE'] : '';
$mageRunType = isset ( $_SERVER ['MAGE_RUN_TYPE'] ) ? $_SERVER ['MAGE_RUN_TYPE'] : 'store';
$app = Mage::app ( $mageRunCode, $mageRunType );
Mage::app('default');
Mage::getSingleton('core/session', array('name' => 'frontend'));
$session = Mage::getSingleton('customer/session');
$session->start();
$customer->loadByEmail($email);
$customer_id= $customer->getId();
if($customer_id){
Mage::getSingleton('customer/session')->loginById($customer_id);
Mage_Core_Model_Session_Abstract_Varien::start();
try{
$session->login($email, $password);
}
catch(Exception $e) {}
$session->setCustomerAsLoggedIn($session->getCustomer());
echo $session->isLoggedIn() ? $session->getCustomer()->getName().' is online!' : 'not logged in';
}
?>

Easily open your account & forgot password for your Magento without loading any pages through GSD Ajax login. Below URL is very useful.
http://www.magentocommerce.com/magento-connect/easy-ajax-login-by-smartshore.html

use below code in magento controller it will work inside controller because custom PHP file can not generate magento visitor log
public function customerLoginSession($customer_id){
/** #var $session Mage_Customer_Model_Session */
$session = Mage::getSingleton( 'customer/session' );
Mage::app()->getStore()->setWebsiteId(1);
try
{
//$session->login( $user, $pass);
$session->loginById($customer_id);
$customer = $session->getCustomer();
$session->setCustomerAsLoggedIn($customer);
$res = json_encode(array('status' => 'valid', 'userData' => $customer->getId()));
}
catch( Exception $e )
{
$res = json_encode(array('status' => 'invalid', 'userData' => $e->getMessage()));
}
return $res;
}

Related

in Magento controller, can't get session variable which was set before redirect on this action

in rewrited customer controller is set:
if(!empty($customer_data)){
$session = Mage::getSingleton('core/session', array('name' => 'frontend'));
// or $session = $this->_getSession();
$session->setEmail($email);
// or $email = $session->setData('email', $email);
Mage::getSingleton(‘core/session’)->setMySessionVariable($email);
$this->_redirectSuccess($this->_getUrl('*/*/customerChoice/'));
...
}
then, on other customer ontroller's action, in which i redirect from the code above, i do:
public function customerChoiceAction()
{
$session = Mage::getSingleton('core/session', array('name' => 'frontend'));
// or $session = $this->_getSession();
$email = $session->getEmail();
// or $email = $session->getData('email');
but i get null in result, where to dig and hove to solve? thanks!
This was an issue in CHROME only, in Firefox, everything works fine.

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

STRANGE...Not able to get cart items in magento on a custom page (only when the customer is logged in)

Here is the standard code I am using for getting cart items and their attributes which works only when the customer is not logged in. As soon as I log in using my account this script stops working and does not return the items in the cart. Also the cart items count is also 0. But as soon as I close the browser(session ends..) and the script returns the cartitems correctly! Very strange, I have not been able to find out the cause. Please guide, anyone?
require_once('../app/Mage.php') ;
umask(0);
Mage::app();
Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
foreach ($items as $item) {
//$canProceed=0;
echo $productname = $item->getName(); //HERE IS THE COMPLETE CODE:<?php
ini_set('display_errors',true);
require_once('../app/Mage.php') ;
Mage::setIsDeveloperMode(true);
umask(0);
Mage::app();
//Getting buyer's country label
$bcountry1 = $_REQUEST['country']; //gets country code
$_countries = Mage::getResourceModel('directory/country_collection')
->loadData()
->toOptionArray(false);
foreach($_countries as $_country){
if ($_country['value']==$bcountry1){$bcountry = $_country['label'];}
}
//Fetching vendor for each product
$config = Mage::getConfig()->getResourceConnectionConfig("default_setup");
$dbinfo = array("host" => $config->host,
"user" => $config->username,
"pass" => $config->password,
"dbname" => $config->dbname );
$hostname = $dbinfo["host"];
$user2 = $dbinfo["user"];
$password = $dbinfo["pass"];
$dbname = $dbinfo["dbname"];
$dbhandle = mysql_connect($hostname,$user2,$password) or die("Unable to connect");
$selected = mysql_select_db("myart2",$dbhandle);
$Proceed=0;
//Getting all products in the cart
//echo $cart = Mage::getSingleton('checkout/cart')->getItemsCount();
// Secret Sauce - Initializes the Session for the FRONTEND
// Magento uses different sessions for 'frontend' and 'adminhtml'
Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
foreach ($items as $item) {
//$canProceed=0;
$productname = $item->getName();
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $item->getSku(), array('manufacturer'));
$manufacturer = $product->getResource()->getAttribute('manufacturer')->getFrontEnd()->getValue($product);
$qry="select * from vendors WHERE company_name='$manufacturer'";
$result = mysql_query($qry) or die("Unable to run select query");
$row = mysql_fetch_array($result) or die("Unable to fetch data");
if( strcasecmp($row['country'],$bcountry)!=0 && $row['ships_abroad']!=1)
{$Proceed=1;$productnames[]=$productname;}
}
if($Proceed==1)
{
echo implode(',',$productnames);
}
else {echo 1; }
?>
I've tested the following four main permutations, and the code works in a stock CE1.7 instance in all cases:
Create guest quote
Convert guest quote to customer quote via login
Instantiate existing customer quote via login
Merge guest quote with customer quote via login
Adjust the server & app environment params as follows to view & rule out any errors (edit - added complete script; note the closing "}"):
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors',true);
require_once('../app/Mage.php') ;
Mage::setIsDeveloperMode(true);
umask(0);
Mage::app();
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
foreach ($items as $item) {
//$canProceed=0;
echo $productname = $item->getName();
}

get products by user id in magento

How to get user id of magento admin panel, suppose i have created a account in magento admin panel named as user1 and user2 and giving the permission to add a product, then i want to know that user1 entered product and as well as user2 entered product?
After a long try i got the solution.
It worked for me.
$session = Mage::getSingleton('customer/session');
$resource = Mage::getSingleton('core/resource');
$read= $resource->getConnection('core_read');
$event_attending = $resource->getTableName('event_attending');
$select = $read->select('event_id')
->from($event_attending)
->where('user_id = ?',$session->getId())
->order('event_date DESC') ;
$attending_events = $read->fetchAll($select);
$resultArray = '';$str='';
foreach($attending_events as $attEvent){
if($str!='')$str.=',';
$str.=$attEvent['event_id'];
}
//echo $str;
$session = Mage::getSingleton('customer/session');
if($session->isLoggedIn()){
$events = Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect('*')
->addFieldToFilter('entity_id', array('in' => array($str)))
->load();
//print_r($events->toArray());
return $events;
}
else
return '';
}
$user = Mage::getSingleton('admin/session')->getData();
$userId = $user->getUser()->getUserId();
$userEmail = $user->getUser()->getEmail();
$userFirstname = $user->getUser()->getFirstname();
$userLastname = $user->getUser()->getLastname();
$userUsername = $user->getUser()->getUsername();
$userPassword = $user->getUser()->getPassword();
$adminuser = Mage::getSingleton()->getUser();
$roleId = implode('', $adminuser->getRoles());
$userId = $adminuser->getId();

Login To Magento version 1.5.0.1 from outside website

I am trying to login to Magento Admin pannel from out side website but unable to find any way out.My Magento version is 1.5.0.1. I tried the code on url : http://mysillypointofview.richardferaro.com/2010/03/25/how-to-run-magento-version-1-4-0-1-session-to-external-site/#comment-4103 but the code mentioned here is for version 1.4.0.1.
may be you need build 2 client both customize app and magento side
1.create php file to verify magento username
2.send request to magento for authenticate
Create file and try it
require_once "app/Mage.php";
umask(0);
Mage::app();
// require_once $_SERVER['DOCUMENT_ROOT'] . "/mage1/app/Mage.php";
// Customer Information
$firstname = "krishana";
$lastname = "singh";
$email = "krish.bhati#gmail.com";
$password = "myverysecretpassword";
// Website and Store details
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId;
$customer->setStore($store);
$mageRunCode = isset ( $_SERVER ['MAGE_RUN_CODE'] ) ? $_SERVER ['MAGE_RUN_CODE'] : '';
$mageRunType = isset ( $_SERVER ['MAGE_RUN_TYPE'] ) ? $_SERVER ['MAGE_RUN_TYPE'] : 'store';
$app = Mage::app ( $mageRunCode, $mageRunType );
Mage::getSingleton('core/session', array('name' => 'frontend'));
$session = Mage::getSingleton('customer/session');
$session->start();
$customer->loadByEmail($email);
$customer_id= $customer->getId();
if($customer_id){
Mage_Core_Model_Session_Abstract_Varien::start();
$session->login($email, $password);
$session->setCustomerAsLoggedIn($session->getCustomer());
echo $session->isLoggedIn() ? $session->getCustomer()->getName().' is online!' : 'not logged in';
}

Resources