Magento: Login and redirect to account page from outside magento - 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

Related

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);
}

Programatically adding product to magento cart not working at the first time only

I'm creating custom functions for sign up and adding product to customer cart.
If user signed up using my function first product that he/she added will not be added to the cart unless he added another product after that everything working perfect and the first product also appear in the cart.
If user signed up by using magento sign up form then used my function to add product to the cart everything working.
Sign up code
public function signupAction() {
$email = $this->getRequest()->getPost('email');
$password = $this->getRequest()->getPost('password');
$firstName = $this->getRequest()->getPost('firstName');
$LastName = $this->getRequest()->getPost('LastName');
$session = Mage::getSingleton('customer/session');
$session->setEscapeMessages(true);
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer->setWebsiteId($websiteId)
->setStore($store)
->setFirstname($firstName)
->setLastname($LastName)
->setEmail($email)
->setPassword($password);
try {
$customer->cleanPasswordsValidationData();
$customer->save();
$this->_dispatchRegisterSuccess($customer);
$this->_successProcessRegistration($customer);
} catch (Mage_Core_Exception $e) {
} catch (Exception $e) {
}
}
Add to cart code
public function addAction() {
$form_key = Mage::getSingleton('core/session')->getFormKey();
$json = $this->getRequest()->getPost('json');
$jsonObj = json_decode($json);
$cart = $this->_getCart();
$cart->init();
$response = array();
try {
foreach ($jsonObj as $data) {
$param = ['form_key' => $form_key,
'qty' => $data->qty, 'product' => $data->productId];
$product = $this->_initProduct($param['product']);
if ($data->type == 'simple') {
$cart->addProduct($product, $param);
}
}
$cart->save();
$this->_getSession()->setCartWasUpdated(true)
/**
* #todo remove wishlist observer processAddToCart
*/
Mage::dispatchEvent('checkout_cart_add_product_complete',
array('product' => $product,
'request' => $this->getRequest(),
'response' => $this->getResponse()));
if (!$cart->getQuote()->getHasError()) {
$response['status'] = 'SUCCESS';
} else {
$response['status'] = 'Error';
}
} catch (Mage_Core_Exception $e) {
$msg = "";
if ($this->_getSession()->getUseNotice(true)) {
$msg = $e->getMessage();
} else {
$messages = array_unique(explode("\n", $e->getMessage()));
foreach ($messages as $message) {
$msg .= $message . '<br/>';
}
}
$response['status'] = 'ERROR';
$response['message'] = $msg;
} catch (Exception $e) {
$response['status'] = 'ERROR';
$response['message'] = $this->__('Cannot add items.');
Mage::logException($e);
}
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($response));
return;
}
refresh the page is solution because magento use the form key to validate the data
so when login a customer then session is change according to that and it working
let me know if you have more Questions .

Why does Magento remove my frontend cookie after using customer/session?

I'm using Nginx and HHVM, I'm also using custom php files to interact with Magento.
When I run any PHP file the frontend cookie gets set properly, also the shoppingcart works fine.
However, whenever I use:
$session = Mage::getSingleton( 'customer/session' );
$session->login($login, $pass);
$session->setCustomerAsLoggedIn($customer);
The frontend cookie gets removed.
Question: why is that and what can I do to solve it?
Settings:
Complete example:
include_once('../app/Mage.php');
ob_start();
umask(0);
Mage::app();
Mage::getSingleton('core/session', array('name'=>'frontend'));
$login = $v[0]; //username as email
$pass = $v[1]; //user password
try {
$customer = Mage::getModel("customer/customer");
$customer->website_id = Mage::app()->getWebsite()->getId();
$customer->loadByEmail($login);
$session = Mage::getSingleton( 'customer/session' );
$session->login($login, $pass);
$session->setCustomerAsLoggedIn($customer);
} catch(Exception $e) {
$returnJson['success'] = false;
$returnJson['error'] = $e;
}
We solved this issue by adding the HHVM ini setting:
hhvm.server.allow_duplicate_cookies = 0
More info: https://github.com/facebook/hhvm/issues/2758
Maybe not related, but why load the customer before even logging in, and you never check if the login function returns true or false. Also you manually set the customer as logged in, this is performed inside the login() function for you if the user/pass is correct. I would basically change the whole try..catch part to something like:
try {
$session = Mage::getSingleton( 'customer/session' );
if (!$session->login($login, $pass)) {
throw new Exception("Authentication failed");
}
$customer = $session->getCustomer();
// more stuff?
} catch(Exception $e) {
$returnJson['success'] = false;
$returnJson['error'] = $e;
}
Obviously not tested/proofread for lazy reasons. :)

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 login from outside magento

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;
}

Resources