How to build login api to other sites in Codeigniter different sites ex. IP.Board / wordpress - codeigniter

I'm starting with Codeigniter and i have a question. How (if possible) to create authorization api to other sites (no facebook, twitter etc.).
I have three sites - CI system, IP.Board and WordPress, and my point is a integrating all those systems in one auth api.
I heared about Oauth and OpenId, but I don't know how this things has postponement to CI. Is complicated?

Hello It can be possible
I can suggestion you can use temporary table store that table logged user id and current date& time and also ip address ,and store that one in to Sharing Cookies Across Multiple Domains/send hidden stored id to your multiple site.based on id and ip and time you can implement logic
note: logout and session time out times you can delete the record form table
I have written small example plz check it once . it my be helpful you
Session will most likely not to work. I thought of using JSON but I failed to figure out how to make the Javascript to be dynamic as I always prefer to use jQuery (if you have an idea, feel free to share). In the end, I decided to use PHP along with MySQL and cURL.
We will first start by creating a table to handle the login session:
CREATE TABLE IF NOT EXISTS `sso_login` (`user_id` int(11) NOT NULL)
Purpose of the table is to store logged in users and remove then upon signing out.
Next is the PHP script which will insert new user id upon signing in (file name: register.php):
<?php
/**
*
* #
*/
$userId = $_GET['id'];
$sql = sprintf("INSERT INTO sso_login VALUES ('%s')", $userId);
mysql_query($sql);
?>
Simple, isn’t it? All it does is inserting the user id into the table.
Next is the file which delete the user id when user is signing out (file name: drop.php):
<?php
/**
*
*
*/
$userId = $_GET['id'];
$sql = sprintf("DELETE FROM sso_login WHERE user_id = '%s'", $userId);
mysql_query($sql);
?>
I believe the script is pretty much self-explainatory.
Next is the file which checks whether user is already logged in or vice versa (file name: check.php):
<?php
/**
*
*
*/
$userId = $_GET['userId'];
$sql = sprintf("SELECT COUNT(*) FROM sso_login WHERE user_id = '%s'", $userId);
$query = mysql_query($sql);
if (mysql_result($query, 0, 0) > 0)
{
echo 'User '.$userId.' has logged in';
}
else
{
echo 'User '.$userId.' is not logged in.';
}
?>
This script will check whether the user id being passed is available in the table or not. If not it means that the user have not logged in.
These three scripts will be store on the other party’s server. Next are scripts which will be store on BC’s server where the login and logout process being done. All these processes are using cURL.
First is the script which will update the other site when user is logged in (file name: login.php):
<
?php
/**
*
*
*/
if($_POST)
{
$username = $_POST['username'];
$password = $_POST['password'];
if (($username == "bcoffee") && ($password == "demo"))
{
$userId = 10;
$target_site = sprintf("http://the-other-site.com/register.php?id=%s", $userId);
$timeout = 5;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_site);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_exec($ch);
curl_close($ch);
header('location: index.php');
}
}
?>
You might notice that the username and password are hard coded, this was for P.O.C purpose, so it does not matter. Back to the tutorial.
As you can see, it will reach register.php with the user’s id. Refer back to content of register.php which will then insert the user id into the table. This way, the other server will know that user is already logged in.
Next is the script which will notify the other server when the user is signing out (file name: logout.php):
<?php
/**
*
*
*/
$userId = 10;
$target_site = sprintf("http://the-other-site.com/drop.php?id=%s", $userId);
$timeout = 5;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_site);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_exec($ch);
curl_close($ch);
header('location: login.html');
?>
Similar to login.php but this time, it will remove the user id when user is signing out. Hence when the system checks (using check.php) and found that the user id is not available, it will know that the user is not currently logged in.

Related

add product to wishlist in magento API

I have checked in magento soap API but I can not find API for add product to wish list so I am developing own API but I don't know what is the problem with my code so please help me to find solution.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once '../app/Mage.php';
Mage::app();
$customer_id = $_GET['customer_id'];
$product_id = $_GET['product_id'];
$customer = Mage::getModel('customer/customer');
$wishlist = Mage::getModel('wishlist/wishlist');
$product = Mage::getModel('catalog/product');
$customer->load($customer_id);
$wishlist->loadByCustomer($customer_id);
$res = $wishlist->addNewItem($product->load($product_id));
if($res)
{
$status =1;
$message = "your product has been added in wishlist";
}
else
{
$status =0;
$message = "wrong data send";
}
$result = array("status" =>$status,"message"=>$message);
header('Content-type: application/json; charset=utf-8');
echo json_encode($result);
?>
There is a similar question you might want to check.
In your code you are not extending Magento API in any way but creating a standalone hackish script that inserts items to wishlist. I suggest that you take a look on how to develop a magento extension or if you need to create a backend (CLI) script, at least use the same structure as in shell/abstract.php and extend the shell base class - you will save yourself loads of headaches.
Moreover, your code is not secure, maintainable and removes all the benefits of using Magento as an ecommerce platform/framework (security, authorization & authentication etc)
Inchoo have quite some blog posts that could give you an idea where to begin
http://inchoo.net/magento/magento-api-v2/
http://inchoo.net/magento/extending-the-magento-api/
/* error_reporting(E_ALL);
ini_set("display_errors", 1);*/
You Have Comment This line And Write this
require_once './app/Mage.php';

magento got invalid login or password error for customer

i added one customer programmatically and send mail to that customer for new password and also in admin side i found that customer but when customer try to login with email id and password got error 'Invalid login or password'
here is my code
what is problem with this?
define('MAGENTO_ROOT', getcwd());
$mageFilename = MAGENTO_ROOT . '/app/Mage.php';
require_once $mageFilename;
Mage::init();
Mage::setIsDeveloperMode(true);
ini_set('memory_limit', '-1'); //for unlimited memory being more trickey
ini_set('display_errors', 1);
Varien_Profiler::enable();
umask(0);
Mage::app('default');
$customer_email = 'test#testemail.com'; // email adress that will pass by the questionaire
$customer_fname = 'test_firstname'; // we can set a tempory firstname here
$customer_lname = 'test_lastname'; // we can set a tempory lastname here
$passwordLength = 10; // the lenght of autogenerated password
$customer = Mage::getModel('customer/customer');
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($customer_email);
/*
* 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($customer_email);
$customer->setFirstname($customer_fname);
$customer->setLastname($customer_lname);
$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();
}
catch(Exception $ex){
}
Advance thanks....
I would guess it's not automatically setting the customer to active. You can confirm by running this query on your db;
SELECT * FROM customer_entity WHERE email = 'the#email.com'
There is a column in there called 'is_active', almost certainly set to 0 for no.
In your script to create the customer add this before you save;
$customer->setIsActive(1);

Add user to group in Joomla not working

I am trying to add a user to a group. I can run this PHP code without any errors, but the user group is still not changed.
<?php
define('_JEXEC', 1);
define('JPATH_BASE', realpath(dirname(__FILE__)));
require_once ( JPATH_BASE .'/includes/defines.php' );
require_once ( JPATH_BASE .'/includes/framework.php' );
require_once ( JPATH_BASE .'/libraries/joomla/factory.php' );
$userId = 358;
$groupId = 11;
echo JUserHelper::addUserToGroup($userId, $groupId);
?>
I run in the same issue with payment callback. I found that user groups save in the database correctly, but are not refreshed in Juser object (becouse You add user to group in different session). When user interacts on a page groups are restored.
Another think that i found is that changing groups in administrator panel works the same way if user is logged in.
To deal with it I made system plugin and in onAfterInitialise function i do:
//get user
$me = JFactory::getUser();
//check if user is logged in
if($me->id){
//get groups
$groups = JUserHelper::getUserGroups($me->id);
//check if current user object has right groups
if($me->groups != $groups){
//if not update groups and clear session access levels
$me->groups = $groups;
$me->set('_authLevels', null);
}
}
Hope it will help.
Possible "Easy" Solution:
The code is correct and it should put your $userId and $groupId in the db to be precise in #__user_usergroup_map .
Btw consider that this method is rising an error if you use a wrong groupId but it's not raising any error if you insert a wrong $userId and for wrong I mean that it doesn't exist.
So there are canches that the user with $userId = 358; doesn't exist.
Update - Hard Debugging:
Ok in this case I suggest you to digg in the code of the helper.
The file is :
libraries/joomla/user/helper.php
On line 33 You have JUserHelper::addUserToGroup.
This is the code:
public static function addUserToGroup($userId, $groupId)
{
// Get the user object.
$user = new JUser((int) $userId);
// Add the user to the group if necessary.
if (!in_array($groupId, $user->groups))
{
// Get the title of the group.
$db = JFactory::getDbo();
$query = $db->getQuery(true)
->select($db->quoteName('title'))
->from($db->quoteName('#__usergroups'))
->where($db->quoteName('id') . ' = ' . (int) $groupId);
$db->setQuery($query);
$title = $db->loadResult();
// If the group does not exist, return an exception.
if (!$title)
{
throw new RuntimeException('Access Usergroup Invalid');
}
// Add the group data to the user object.
$user->groups[$title] = $groupId;
// Store the user object.
$user->save();
}
if (session_id())
{
// Set the group data for any preloaded user objects.
$temp = JFactory::getUser((int) $userId);
$temp->groups = $user->groups;
// Set the group data for the user object in the session.
$temp = JFactory::getUser();
if ($temp->id == $userId)
{
$temp->groups = $user->groups;
}
}
return true;
}
The bit that save the group is $user->save();.
Try to var_dump() till there and see where is the issue.
Author already halfish solved this problem so this answer may help to others. It took me hours of debugging with Eclipse and XDebug to find the issue. This error was very tricky because addUserToGroup() was returning true for me and user object was as well with successful changes, but they were not saved in database. The problem was that onUserBeforeSave() method in my plugin was throwing exception whenever addUserToGroup() was trying to save a user. So check your implementation of onUserBeforeSave() if you touched it. If not you must install Eclipse with XDebug and try to debug what is your exact problem.

Magento external Script and Session

I want to add an external script which gets a sku via GET check the ID and then redirect to the cart if available otherwise it sets en error and also redirecting to the cart.
The script is called from a product page:
http://myhost/scripts/addto.php?sku=12345
Here is the colmplete code
<?php
include_once '../../../../../app/Mage.php';
Mage::app();
$session = Mage::getSingleton('core/session', array('name' => 'frontend'));
$sku = $_GET['sku'];
if (!isset($_GET['qty'])) { $qty = '1'; } else { $qty = $_GET['qty']; }
$id = Mage::getModel('catalog/product')->getIdBySku($sku);
if ($id == '') {
$id = $sku;
Mage::getSingleton('checkout/session')->addError("Product not found!");
}
Works fine, but after logout and relogin the error message is missing. I found out that's because of a cookie which is set. After deleting that cookie the error message is working again after relogin.
What does not work?
You logout and login and then the script stop working? So the session is not found? The product ist not found? The product is not loaded? The user is not forwarded? :-)
Sure it does not. The Message is a Notice. If it is shown once, it is deleted.
What behaviour do you want?
use Mage::getSingleton('core/session')->addError("Product not found!");, maybe checkout/session is user specific...
cheers

Checking for Magento login on external page

I'm hitting a wall here while trying to access items from Magento on an external page (same server, same domain, etc, etc). I want to see if the user is logged into Magento before showing them certain parts on the site.
Keep in mind that this code exists outside of Magento.
Mage::app("default");
Mage::getSingleton("core/session", array("name" => "frontend"));
if (empty($session))
{
$session = Mage::getSingleton("customer/session");
}
if($session->isLoggedIn())
echo "hi";
$cart = Mage::helper('checkout/cart')->getCart()->getItemsCount();
echo $cart;
$cart returns 0, where I definitely have products in my cart. isLoggedIn() also returns false. What am I doing wrong here? Is there an option in Magento that I need to turn on or off to be able to access this information outside of Magento?
Using the code above, I created a php file in the Magento folder. From there, added the number of items in the cart and whether you were logged in or not to an array and encoded it as json. I used some jquery on my external page to grab the file and pull the data I needed.
Not quite the ideal situation, but it works for now.
Are you including Mage.php (which defines getSingleton)?
require_once ($_SERVER['DOCUMENT_ROOT'] . '/app/Mage.php');
What does $session have in it after the getSingleton() call?
print_r ($session);
EDIT: I tried this on my end and was not able to get accurate isLoggedIn() or getItemsCount() data. When I dumped out $session its showing all the fields as 'protected.'
I'm not interested in requiring the user to log in...I merely want to access data from the already logged in session.
Anyone else have any thoughts on this? All the examples out there seem to be pre 1.4.x.
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