Magento API : How to load customer session by ID - php

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()

Related

Weird behaviour of PHP Login

This is more like a debugging problem than an actual question. I have a login script in PHP which should check for user information from a local database and if present, then display them. Or else, redirect them to the Google OAuth2 Login process. The following php files concern the login flow :
google_login.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require('http.php');
require('oauth_client.php');
require('../config.php');
require('StructuredQuery.php');
define("SCOPE", 'https://www.googleapis.com/auth/userinfo.email '.
'https://www.googleapis.com/auth/userinfo.profile' );
$client = new oauth_client_class;
$sq= new StructuredQuery();
// set the offline access only if you need to call an API
// when the user is not present and the token may expire
$client->offline = FALSE;
$client->debug = false;
$client->debug_http = true;
$client->redirect_uri = GOOGLE_REDIRECT_URL;
$client->client_id = GOOGLE_CLIENT_ID;
$application_line = __LINE__;
$client->client_secret = GOOGLE_CLIENT_SECRET;
if (strlen($client->client_id) == 0 || strlen($client->client_secret) == 0)
die('Please go to Google APIs console page ' .
'http://code.google.com/apis/console in the API access tab, ' .
'create a new client ID, and in the line ' . $application_line .
' set the client_id to Client ID and client_secret with Client Secret. ' .
'The callback URL must be ' . $client->redirect_uri . ' but make sure ' .
'the domain is valid and can be resolved by a public DNS.');
/* API permissions
*/
$client->scope = SCOPE;
if (($success = $client->Initialize())) {
if (($success = $client->Process())) {
if (strlen($client->authorization_error)) {
$client->error = $client->authorization_error;
$success = false;
} elseif (strlen($client->access_token)) {
$success = $client->CallAPI(
'https://www.googleapis.com/oauth2/v1/userinfo', 'GET', array(), array('FailOnAccessError' => true), $user);
}
}
$success = $client->Finalize($success);
}
if ($client->exit)
exit;
if ($success) {
// Now check if user exist with same email ID
try {
$result = $sq->getUserInfo($user->id);
if ($result["count"] > 0) {
// User Exist
$_SESSION["name"] = $result["name"];
$_SESSION["email"] = $result["email"];
$_SESSION["clevel"]=$result["clevel"];
$_SESSION["new_user"] = "no";
} else {
// New user, Insert in database
$result = $sq->putNewUserInfo($user->id,$user->name,$user->email);
if ($result===true) {
$_SESSION["name"] = $user->name;
$_SESSION["email"] = $user->email;
$_SESSION["new_user"] = "yes";
$_SESSION["e_msg"] = "";
}
}
$_SESSION["login_type"]="Google";
} catch (Exception $ex) {
$_SESSION["e_msg"] = $ex->getMessage();
}>
$_SESSION["user_id"] = $user->id;
} else {
$_SESSION["e_msg"] = $client->error;
}
header("Location: ".ROOT_DIR."homepage.php");
exit;
?>
StructuredQuery.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require_once 'config.php';
class StructuredQuery{
var $opt;
var $pdo;
function __construct(){
$opt = [
PDO::ATTR_PERSISTENT => FALSE,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$this->pdo = new PDO(DB_DRIVER.":host=".DB_SERVER.";dbname=".DB_NAME, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, $opt);
}
// Cross Site Script & Code Injection Sanitization
function xss_cleaner($input_str) {
$return_str = str_replace( array('<',';','|','&','>',"'",'"',')','('), array('<',':','|','&','>','&apos;','"',')','('), $input_str );
$return_str = str_ireplace( '%3Cscript', '', $return_str );
return $return_str;
}
//SQLInjection detect
function sql_injection_detect($input_query){
try{
$blacklist=array('SELECT','WHERE','UPDATE','DELETE','INSERT','FROM','DROP','MERGE','SET','INSERT','REMOVE','REPLACE','QUERY');
$err_level=0;
foreach($blacklist as $blacklist_item){
if(stripos($input_query,$blacklist_item)!==false){
$err_level++; //Counter for number of blacklist words used. 2 means dangerous. Terminate immediately.
if($err_level==2){
die('Was that an IT joke? Cause I am a 12th grader, not an IT Pro.');
}
}
}
return true;
}catch(Exception $e){
echo 'Exception Occured:',$e->getMessage(),"\n";
die('You\'ve been Terminated');
}
}
function getUserInfo($user_id){
$user_id=xss_cleaner($user_id);
if(sql_injection_detect($user_id)){
$query=$pdo->prepare("select statement");
$query->bindParam(":user_id",$user_id,PDO::PARAM_STR);
$query->execute();
$result=$query->fetch();
$result["count"]=$query->rowCount();
return $result;
}
}
function putNewUserInfo($user_id,$name,$email){
$user_id=$this->xss_cleaner($user_id);
$name=xss_cleaner($name);
$email=xss_cleaner($email);
if(sql_injection_detect($user_id) && sql_injection_detect($name) && sql_injection_detect($email)){
$query=$pdo->prepare("insert statement");
$query->bindParam(":user_id",$user_id,PDO::PARAM_STR);
$query->bindParam(":name",$name,PDO::PARAM_STR);
$query->bindParam(":email",$email,PDO::PARAM_STR);
$query->execute();
return true;
}else{
return false;
}
}
function modifyUserInfo($user_id,$name,$email,$clevel){
$user_id=xss_cleaner($user_id);
$name=xss_cleaner($name);
$email=xss_cleaner($email);
$clevel=xss_cleaner($clevel);
if(sql_injection_detect($user_id) && sql_injection_detect($name) && sql_injection_detect($email) && sql_injection_detect($clevel)){
$query=$pdo->prepare("update statement");
$query->bindParam(":user_id",$user_id,PDO::PARAM_STR);
$query->bindParam(":name",$name,PDO::PARAM_STR);
$query->bindParam(":email",$email,PDO::PARAM_STR);
$query->bindParam(":clevel",$clevel,PDO::PARAM_INT);
$query->execute();
return true;
}else{
return false;
}
}
}
Now the issue that bothers me is this- whenever i press Login With Google, it redirects to google_login.php, well and fine. And then, directly to the homepage as if I am already logged in even though I am not. Even weirder is that it displays my e-mail and my username as blank, even though it says that I am an existing user.
P.S. No, the database does not contain any blank entries and it works fine, I double-checked.

session works on localhost but sometimes not working on server

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

Magento retrieve customer ID

I've tried various methods to get the customerID but an empty value is stored in the variable. Please advise :)
Below remnants of things I've tried. The file is located in the root.
require_once '/home/ab71714/public_html/app/Mage.php';
//Mage::app("default");
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
/* if(Mage::getSingleton('customer/session')->isLoggedIn()) {
$customerData = Mage::getSingleton('customer/session')->getCustomer();
echo $customerData->getId();
} */
if(Mage::getSingleton('customer/session')->isLoggedIn()) {
$customerId = Mage::getModel('customer/session')->getCustomer()->getId();
} else {
echo 'Not logged In';
}
require "/home/ab71714/public_html/app/Mage.php";
umask(0);
Mage::app();
$session = Mage::getSingleton('customer/session');
if($session->isLoggedIn()) {
print_r($session);
$customerId = $session->getCustomer()->getId();
} else {
echo 'Not logged In';
}
For more information:
http://ka.lpe.sh/2011/06/19/magento-get-customer-details-customer-id-name-email/
if(Mage::getSingleton('customer/session')->isLoggedIn()) {
$customerData = Mage::getSingleton('customer/session')->getCustomer();
echo $customerData->getId();
}

facebook->api('/me') not working on localhost.

<?php
require 'facebook/facebook.php';
require 'config/fbconfig.php';
require 'config/functions.php';
define('APP_ID', '******************');
define('APP_SECRET', '***********************');
$facebook = new Facebook(array(
'appId' => '******************',
'secret' => '***********************',
'cookie' => true
));
$session = $facebook->getSession();
if (!empty($session)) {
# Active session, let's try getting the user id (getUser()) and user info (api->('/me'))
try {
$uid = $facebook->getUser();
print_r($uid);
$user = $facebook->api('/me');
facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = false;
facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYHOST] = 2;
} catch (Exception $e) {
}
if ($user) {
# User info ok? Let's print it (Here we will be adding the login and registering routines)
echo '<pre>';
print_r($user);
echo '</pre><br/>';
$username = $user['name'];
$user = new User();
$userdata = $user->checkUser($uid, 'facebook', $username);
if(!empty($userdata)){
session_start();
$_SESSION['id'] = $userdata['id'];
$_SESSION['oauth_id'] = $uid;
$_SESSION['username'] = $userdata['username'];
$_SESSION['oauth_provider'] = $userdata['oauth_provider'];
header("Location: home.php");
}
} else {
# For testing purposes, if there was an error, let's kill the script
die("There was an error.");
}
} else {
# There's no active session, let's generate one
// $login_url = $facebook->getLoginUrl();
$loginUrl = $facebook->getLoginUrl( array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'email,publish_stream',
'next' => 'http://localhost/login_twitbook/',
'cancel_url' => 'http://localhost/login_twitbook/'
) );
header("Location: " . $login_url);
}
?>
The $user = $facebook->api('/me'); doesnot working properly its always returns nothing. pls help me to solve this problem. I'm working on localhost.$uid = $facebook->getUser() its returns the value but the $user doesnt return
Try changing the getCode function in the base_facebook.php file change all the $_REQUEST to $_GET. Not sure why this hasn't been fixed yet but I was pulling my hair out trying to figure out why it was returning 0 for the user until I did this, now it works flawlessly.
Should be on or around line 680 of the file and there are 4 to change.
protected function getCode() {
if (isset($_GET['code'])) {
if ($this->state !== null &&
isset($_GET['state']) &&
$this->state === $_GET['state']) {
// CSRF state has done its job, so clear it
$this->state = null;
$this->clearPersistentData('state');
return $_GET['code'];
} else {
self::errorLog('CSRF state token does not match one provided.');
return false;
}
}
return false;
}

Facebook CodeIgniter - can't log in on first attempt

I'm using the Facebook PHP integration with CodeIgniter.
I have a problem where I click on the login link, it brings me to the Facebook login, I log in successfully, and when it redirects back to my page, none of the Facebook information has come through. Then if I click the login link again, it immediately logs me in without the need for the Facebook login form. If I were to refresh the page instead of clicking the login link the second time, the Facebook information still wouldn't show.
I feel that it's something to do with the session.
$facebook = $this->facebook;
$user = $facebook->getUser();
$user is always 0 until I click the login link for the second time.
This is the login flow:
I feel as if it's failing at the GET /oath/authorize phase.
public function fb_login() {
$facebook = $this->facebook;
// Get User ID
$user = $facebook->getUser();
$this->session->set_userdata(array('user' => $user));
var_dump($user);
$profile = null;
$logoutUrl = null;
$loginUrl = null;
try {
$profile = $facebook->api('/me');
$this->session->set_userdata(array('profile' => $profile));
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
if ($user) {
$url = $this->uri->uri_string();
$url = str_replace('/', '-', $url);
$logoutUrl = $facebook->getLogoutUrl(array(
'next' => site_url('[omitted]/fb_logout'.'/'.$url)));
$this->session->set_userdata(array('logoutUrl' => $logoutUrl));
} else {
$loginUrl = $facebook->getLoginUrl(array('display' => 'touch'));
$this->session->set_userdata(array('loginUrl' => $loginUrl));
}
$facebook_array = array(
'user' => $user,
'profile' => $profile,
'logoutUrl' => $logoutUrl,
'loginUrl' => $loginUrl
);
return $facebook_array;
}
public function view_events($organiser_type) {
$this->load->helper('form');
$organiser_type = urldecode($organiser_type);
$data['organiser_type'] = $organiser_type;
$data['title'] = $organiser_type.' Events';
$data['events'] = $this->trinity_impulse_model->get_events_by_type(
$organiser_type,
array('event_start_date', 'event_start_time'),
array('asc', 'asc'));
$i = 0;
foreach ($data['events'] as $event) {
$data['events'][$i]['event_start_date'] = format_timestamp_to('dateFromDB', $event['event_start_date']);
$data['events'][$i]['event_end_date'] = format_timestamp_to('dateFromDB', $event['event_end_date']);
$data['events'][$i]['event_start_date'] = humanise_date($data['events'][$i]['event_start_date']);
$data['events'][$i]['event_end_date'] = humanise_date($data['events'][$i]['event_end_date']);
$data['events'][$i]['event_start_time'] = format_timestamp_to('shorttime', $event['event_start_time']);
$data['events'][$i++]['event_end_time'] = format_timestamp_to('shorttime', $event['event_end_time']);
}
$facebook_array = $this->fb_login();
var_dump($this->session->userdata('user'));
// Get session values.
/*$data['user'] = $this->session->userdata('user');
$data['profile'] = $this->session->userdata('profile');
$data['loginUrl'] = $this->session->userdata('loginUrl');
$data['logoutUrl'] = $this->session->userdata('logoutUrl');
*/
$data['user'] = $facebook_array['user'];
$data['profile'] = $facebook_array['profile'];
$data['loginUrl'] = $facebook_array['loginUrl'];
$data['logoutUrl'] = $facebook_array['logoutUrl'];
$this->load->view('[omitted]/view_events', $data);
}
EDIT: The other pages in my application work as normal. The login displays Facebook data on first attempt. There is nothing different in the other pages. They all use the fb_login() function in the same manner.
EDIT2: I did var_dump($facebook) to see what was different about the variable on the failed login. I found that the state is set when I encounter the problem. If it is not set, it logs in with no problem. I still don't know how to resolve that though. Here is the var_dump():
["state":protected]=> string(32) "ac816d6fa8fba908b6bd01f3e7f0ec75"
I have resolved this.
I don't know what the cause of the problem was, but I modified the code and now it works. The offending piece of code was:
try {
$profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
I wrapped an if around it so that it was only called if the $user variable was instantiated. Code is like so:
if ($user) {
try {
$profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}

Categories