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

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. :)

Related

Session not remember, and why the session created each time I load the page?

I start to work with my project using laravel 5. I realized that it work fine in my local directory with session after I login to my site, But I just know that I got problem when I hosted my project to server. After I login each time, the session could not remember and recreated each time I loan the page. That cause the problem to me.
Laravel Login
public function postLogin(){
$hit = 0;
if(Request::ajax()){
$pw = Request::input('pw');
if(!empty($pw)){
$admin_pass = AdminPassword::first(['admin_pass']);
$ip_address = Request::ip();
if(!empty($admin_pass) && trim($admin_pass->admin_pass) == trim($pw)){
if(Auth::attempt(['username' => Request::input('username'), 'password' => Request::input('password'),'status'=>1])){
try{
$user = Auth::user();
$user->last_login = date('Y-m-d H:i:s');
$user->login_ip = $ip_address;
$user->save();
$permissions = Auth::user()->permission;
if(!empty($permissions) && count($permissions) >0){
session(['ROLE_PERMISSION'=>$permissions]);
}
$failed = FailedLogin::whereRaw('ip_address = INET_ATON(\''.$ip_address.'\')')->first();
if(!empty($failed)){
$failed->delete();
}
}catch (\Exception $ex){}
$url = Request::session()->pull('url.intended', '/');
return ['url'=>$url,'msg'=>'Successfully.','status'=>true,'hit'=>$hit];
}else{
$hit = $this->updateFailedLogin($ip_address,Request::input('username'));
}
}else{
$hit = $this->updateFailedLogin($ip_address,Request::input('username'));
}
}
}else{
return redirect()->route('login');
}
return ['url'=>'','msg'=>'Try again.','status'=>false,'hit'=>$hit];
}
Please help me out. This is the final step of my project.
Thank you in advanced.
It's possible you have SESSION_DRIVER in your .env set to file - depending on your hosting environment, this could mean that your session isn't persisting due to each request being served from a different file server (common in cloud environments).
Try changing your SESSION_DRIVER to database.
Did you put the
session_start();
in all your pages?
If not it might be your problem, I d suggest you to add this in your index directly

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

Creating orders programmatically

I try to create an order in code, but sometimes the code works, but sometimes it goes wrong with exception "The requested Payment Method is not available." (first browser request is ok, but the second one goes wrong, etc..).
My code is:
if (Mage::getSingleton('customer/session')->isLoggedIn()) {
$customer = Mage::getSingleton('customer/session')->getCustomer();
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
} else {
$customer = Mage::getModel('customer/customer');
$email = 'test#example.com';
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->setStoreId(Mage::app()->getStore()->getId());
$customer->loadByEmail($email);
Mage::getSingleton('customer/session')->loginById($customer->getId());
}
$customAddress = Mage::getModel('customer/address')
->setCustomerId($customer->getId())
->getCustomer();
$customAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultBilling();
if ($customAddressId) {
$customAddress = Mage::getModel('customer/address')->load($customAddressId);
}
Mage::getSingleton('checkout/session')->getQuote()
->setBillingAddress(Mage::getSingleton('sales/quote_address')->importCustomerAddress($customAddress))
->setShippingAddress(Mage::getSingleton('sales/quote_address')->importCustomerAddress($customAddress));
$product = Mage::getModel('catalog/product')
->setStoreId(Mage::app()->getStore()->getId())
->load(2);
$cart = Mage::getSingleton('checkout/cart');
$cart->truncate();
try {
$cart->addProduct($product, array('qty' => 2));
$cart->save();
$message = $this->__('%s was successfully added to your shopping cart.', $product->getName());
Mage::getSingleton('checkout/session')->addSuccess($message);
} catch (Exception $ex) {
echo $ex->getMessage();
}
$storeId = Mage::app()->getStore()->getId();
$checkout = Mage::getSingleton('checkout/type_onepage');
$checkout->initCheckout();
$checkout->saveCheckoutMethod('register');
$checkout->saveShippingMethod('flatrate_flatrate');
$checkout->savePayment(array('method' => 'banktransfer'));
try {
$checkout->saveOrder();
} catch (Exception $ex) {
echo $ex->getMessage();
}
$cart->truncate();
$cart->save();
$cart->getItems()->clear()->save();
Mage::getSingleton('customer/session')->logout();
I checked your code in my local server, It s working fine 1st time, but second time it shows error like The requested Shipping Method is not available not like you mentioned above. But after I enabled that shipping method it working fine, So try to enable the shipping and payment methods that you used in your code in admin..

Prevent subscriber saving in observer newsletter_subscriber_save_before Magento

I created an Observer to monitor the event subscriber_save_before. In this observer I handle a new field, the value of that is saved, but if some errors occurs I wanna the record not to be saved and to display only my error message. The throwException seems not to do the trick. The only method I think could work is to force the email field to null but wasn't able to achieve this.
In the subscriberController.php (Mage Core) I have this:
$email = (string) $this->getRequest()->getPost('email');
try {
if (!Zend_Validate::is($email, 'EmailAddress')) {
Mage::throwException($this->__('Please enter a valid email address.'));
}
This is my code (not working):
public function NewsletterSaveSubscriber($observer)
{
$subscriber = $observer->getEvent()->getSubscriber();
$name = Mage::app()->getRequest()->getParam('subscriber_name');
// server side validation
// no name specified
if (!Zend_Validate::is(trim($name), 'NotEmpty')) {
$session = Mage::getSingleton('core/session');
try {
Mage::throwException(Mage::helper('newsletter')->__('The name field cannot be empty!'));
} catch (Mage_Core_Exception $e) {
$session->addException($e, Mage::helper('newsletter')->__('There was a problem: %s', $e->getMessage()));
}
$observer->getRequest()->setPost('email', ''); // this code doesn't work
Mage::app()->getRequest()->setPost('email', ''); // this too
// Ohh nooo! The subscriber is stored :-(
return $this;
}
// save the name
$name = htmlspecialchars($name);
$subscriber->setSubscriberName($name);
return $this;
}
This will solve your probem:
//Error Message
$session = Mage::getSingleton('core/session');
$session->getMessages(true);
$session->addError(Mage::helper('cartware_automaticreview')->__('CouldĀ“t save.'));
// Ohh nooo! The subscriber is not stored :)
$controller = $observer->getControllerAction()->setFlag('',Mage_Core_Controller_Varien_Action::FLAG_NO_DISPATCH,true);
$controller->getResponse()->setRedirect(Mage::app()->getRequest()->getServer('HTTP_REFERER'));
return;
Good luck!

How to send email after successful checkout process?

In my store, I have created a custom module for one-step checkout process.
All the code works fine. But the order detail email is not sent to the customer after the checkout process. Here is the relevant part of my code.
$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();
$order = $service->getOrder();
//This one is the email send code
$order_mail = new Mage_Sales_Model_Order();
$incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order_mail->loadByIncrementId($incrementId);
$order_mail->sendNewOrderEmail();
$this->_redirect('downloadable/customer/products/');
To send/resend an order email in magento
try {
$incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$_order = Mage::getModel('sales/order')->loadByIncrementId($incrementId);
$_order->sendNewOrderEmail();
$this->_getSession()->addSuccess($this->__('The order email has been sent.'));
} catch (Exception $e) {
$this->_getSession()->addError($this->__('Failed to send the order email.'));
Mage::logException($e);
}
try putting it in a try catch to see what the error is like this
<?php
$order_mail = new Mage_Sales_Model_Order();
$incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order_mail->loadByIncrementId($incrementId);
try
{
$order_mail->sendNewOrderEmail();
} catch (Exception $ex) { }
?>
Did you debug when it goes into sendNewOrderEmail? Maybe this helps to figure out where the problem is?
Regards
Try this,
< ?php
$order = new Mage_Sales_Model_Order();
$incrementId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order->loadByIncrementId($incrementId);
try
{
$order->sendNewOrderEmail();
} catch (Exception $ex) { }
?>
Save the above snippet as .phtml and upload it in app/code/core/Mage.
Now make an order in your site and check after successful checkout Email is sending or not.Hope your problem should solved now.

Resources