Oauth Implementation using PHP and JS facebook SDK - codeigniter

Hai Fellow Developers,
I am implementing A facebook Login to my Web App using codeigniter (E-commerce kind of platform).
So, I have lot of filters in my site based upon them i am trying to fetch data and requesting a service. so user has to log in to request a service, so at last i am forcing user to login to continue (like buying something).
Here comes the problem, I implemented Facebook login using Javascript SDK and trying to get accesstoken. and created a FACEBOOK library in codeigniter which fetches user's data using FacebookJavaScriptLoginHelper. and now i should update user details in all sessions and attach the user name dynamically to the current view in codeigniter.
you can look below what i have tried upto now:
Facebook Libabry:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( session_status() == PHP_SESSION_NONE ) {
session_start();
}
// Autoload the required files
require_once( APPPATH . 'libraries/facebook/autoload.php' );
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\FacebookJavaScriptLoginHelper;
use Facebook\GraphObject;
use Facebook\GraphUser;
class Facebook {
var $ci;
var $helper;
var $session;
var $permissions;
public function __construct() {
$this->ci =& get_instance();
$this->permissions = $this->ci->config->item('permissions', 'facebook');
// Initialize the SDK
FacebookSession::setDefaultApplication( $this->ci->config->item('api_id', 'facebook'), $this->ci->config->item('app_secret', 'facebook') );
$this->helper = new FacebookJavaScriptLoginHelper();
// No session exists
try {
$this->session = $this->helper->getSession();
} catch( FacebookRequestException $ex ) {
} catch( Exception $ex ) {
// When validation fails or other local issues
}
}
/**
* Returns the login URL.
*/
public function login_url() {
return $this->helper->getLoginUrl( $this->permissions );
}
/**
* Returns the current user's info as an array.
*/
public function get_user() {
if ( $this->session) {
$request = ( new FacebookRequest( $this->session, 'GET', '/me' ) )->execute();
// Get response as an array
$user = $request->getGraphObject()->asArray();
return $user;
}
return false;
}
public function logout(){
session_start();
session_destroy();
}
}
And in My controller i have my index function like this
public function index(){
$fb_data = $this->facebook->get_user();
$profile_data=array(
'name'=>$fb_data['name'],
'id' =>$fb_data['id'],
'image'=>'http://graph.facebook.com/'.$fb_data['id'].'/picture?width=300',
'email'=>$fb_data['email'],
'oauthProvider'=>'facebook',
);
$this->session->set_userdata('user_name', $fb_data['name']);
echo json_encode($profile_data);
}
My Header View:
<?php if($this->session->userdata('user_name')): ?>
<li id="userName" class="dropdown">
Welcome <span class="user_name"><?php echo $this->session->userdata('user_name')?></span><span class="caret"></span>
<ul class="dropdown-menu">
<li>Account settings</li>
<li>Logout</li>
</ul>
</li>
<?php else: ?>
<li id="login">Login</li>
<?php endif; ?>
Ajax call
$.ajax({
url:"<?php echo base_url('redirectoauth');?>",
success:function(data){
var data=$.parseJSON(data);
$('.user_name').html(data.name);
$('#userName').css('display','block')
$('#login').css('display','none');
$('#socialLogin').modal('hide');
}
});
Any references or tuts,suggestions on architecture to overcome this problem.

this will fix your issue
ajax call
$.ajax({
url:"<?php echo base_url('redirectoauth');?>",
success:function(data){
var data=$.parseJSON(data);
$('.user_name').html(data.name);
$('#logined').css('display','block')
$('#sociallogined').css('display','none');
$('#socialLogin').modal('hide');
}
});
view
<ul id="logined" <?php echo $this->session->userdata('user_name') ? 'style="display:none"' :''; ?>>
<li id="userName" class="dropdown">
Welcome <span class="user_name"><?php echo $this->session->userdata('user_name')?></span><span class="caret"></span>
<ul class="dropdown-menu">
<li>Account settings</li>
<li>Logout</li>
</ul>
</li>
</ul>
<ul id="sociallogined">
<li id="login">Login</li>
</ul>

Related

Checking if Post author is equal to logged in user

A user can post a 'Tutorial', each tutorial is associated with its author via their 'user_id'.
My problem is I want to alter the view if the logged in user is viewing their own post (Tutorial).
CONTROLLER:
public function view($id = null)
{
$tutorial = $this->Tutorials->get($id, [
'contain' => ['Users','Courses', 'TutorialComments.Users']
]);
$tutorialComment = $this->Tutorials->TutorialComments->newEntity();
$this->set(compact('tutorial', 'tutorialComment'));
}
VIEW:
<? if (($tutorial->user->id) === ($this->request->session()->read('Auth.User.id'))): ?>
<p> hello </p>
<? endif; ?>
you should access the logged in the controller through the Auth component and pass the user to the view
controller
$logged_user_id = $this->Auth->user('id');
$this->set(compact('tutorial', 'tutorialComment', 'logged_user_id '));
view
if($tutorial->user->id == $logged_user_id) {
// your code here
}

laravel login link with return back redirection

I create main menu with login link for quest users.
#if(Auth::guest())
<li>Login</li>
#endif
What is the best way to make back redirection after login?
Now I made the next crutch:
// menu.blade.php
#if(Auth::guest())
<?php
if (Route::getCurrentRoute()->getName() != 'auth::login')
Session::put('login_back_url', Request::url());
?>
<li>Login</li>
#endif
// AuthController.php
public function __construct()
{
...
if (Session::has('login_back_url'))
$this->redirectPath = Session::get('login_back_url');
else
$this->redirectPath = route('home');
...
}
You can use:
use Redirect;
Redirect::back();

Codeigniter links for search results

I'm a new to CodeIgniter and I have a problem when I display a list of items, I want each items to be a link, so when the user clicks that particular item, it will show the details of that item. Or perhaps give some suggestion on what I should google for. I have literally no idea whats terms or keywords that should I search about.
controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Site extends CI_Controller
{
public function index()
{
$this->getListOfAgent();
}
function getListOfAgent()
{
$this->load->model("agentDB_model");
$data['results'] = $this->agentDB_model->getAllAgentInfo();
$this->load->view("viewAgent_view", $data);
}
function userInformation()
{
//how to i get the selected item which the user clicked and show the details accordingly?
}
}
model
<?php
class agentDB_model extends CI_Model
{
function getAllAgentInfo()
{
$query = $this->db->query("SELECT * FROM user");
return $query->result();
}
function addAgent($newAgent)
{
$this->db->insert("user", $newAgent);
}
}
view
<!DOCTYPE html>
<html lang="en">
<head>
<title>Welcome</title>
</head>
<body>
<div id="content">
<h1>Home Page</h1>
<p>List Of Agent in database</p>
</div>
<?php
foreach($results as $row)
{
echo "<a href = 'Site/userInformation'>$row->userName</a>";
echo "</br>";
echo "</br>";
}
//$this->load->controller(Site/userInformation);
?>
<div id="footer">
<p>Copyright (c) 2012 basicsite.com</p>
</div>
</body>
</html>
You need to tell the Site/userInformation method for what record you want the information. You use URI segments for this.
So, in your view, change the following line:
echo "<a href = 'Site/userInformation'>$row->userName</a>";
to:
echo "<a href = 'Site/userInformation/$row->userID'>$row->userName</a>";
Then, in your controller method, add the parameter to the method declaration:
function userInformation($userID)
{
// now, you use the model to get the correct record from the db based on
// the $userID and display the information
}

Magento 1.8.0.0: Add custom payment method redirecting to a new page

I'm working locally with magento 1.8.0.0. I succeeded to create a custom payment method. The method is appearing to the list of payment method at the "Payment Information" during the checkout. The problem is that when I select it, it automatically brings a credit card form, which is not what I want. What I want is to select it and once I click the "continue" button I get redirected to another php page containing my own form.
Solution by OP.
For you who want to redirect to the gateway and want the gateway to redirect back to your controller's action method, here is how things work:
In the file app/code/local/Yourcompany/Yourmodule/Model/PaymentMethod.php ,do as follow:
class Yourcompany_Yourmodule_Model_PaymentMethod extends Mage_Payment_Model_Method_Abstract{
protected $_code = "yourmodule";
protected $_isGateway = true;
protected $_canAuthorize = true;
protected function _getCheckout() {
return Mage::getSingleton('checkout/session'); }
public function getOrderPlaceRedirectUrl() { return Mage::getUrl(yourmodule/index/youraction', array('_secure' => true)); }}
In the line return Mage::getUrl(yourmodule/index/youraction', array('_secure' => true)); , "index" means that my controller php file is named IndexController.php. You may change the name as you wish.
In the file app/code/local/Yourcompany/Yourmodule/controllers/IndexController.php , you may code as follow:
class Yourcompany_Yourmodule_IndexController extends Mage_Core_Controller_Front_Action{
public function indexAction() {
$this->loadLayout();
$block = $this->getLayout()->createBlock('Mage_Core_Block_Template','yourmodule',array('template' => 'yourmodule/redirect.phtml'));
$this->getLayout()->getBlock('content')->append($block);
$this->renderLayout(); }
/*In the response action, you may code like this*/
public function responseAction() {
$status=$_REQUEST['param1'];
$orderNo=$_REQUEST['param2'];
if(somecondition)
{
/*update order status */
$ordera = Mage::getModel('sales/order')->loadByIncrementId($orderNo);
$ordera->setState(Mage_Sales_Model_Order::STATE_PENDING_PAYMENT, true)->save();
$this->_redirect("checkout/onepage/success");
}
else
{
$this->_redirect("checkout/cart/");
}
} }
The indexAction() is redirecting to a template redirect.phtml file. This file will collect some parameters to send to the gateway (order number, customer name, total money, etc.). You may put that phtml file here:
app/design/frontend/base/default/template/yourmodule/redirect.phtml
Its content may be coded as follow:
<?php
$orderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order = Mage::getSingleton('sales/order')->loadByIncrementId($orderId);
$order_amount=$order->getGrandTotal();
$customerData = Mage::getSingleton('customer/session')->getCustomer();
$customerAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultBilling(); //oder getDefaultShipping
$address = Mage::getModel('customer/address')->load($customerAddressId);
$customer_name=$address->getFirstname().' '.$address->getLastname();
$customer_email=$customerData->getEmail();
?>
<form name="myjs" method="post" action="http://yourgatewayaddreshere">
<input type="hidden" name="customername" value="<?php echo $customer_name; ?>">
<input type="hidden" name="customermail" value="<?php echo $customer_email; ?>">
<input type="hidden" name="TotalMoney" value="<?php echo $order_amount; ?>">
</form>
<script type="text/javascript">
document.myjs.submit();
</script>

user can't login using CodeIgniter with facebook php sdk

I am following the guide here to play around with the facebook php sdk, but my little app doesn't work. It keeps staying on the login page.
Here is the controller:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Facebook_connect extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper(array('form','url'));
$this->load->library('fb_connect');
}
function index()
{
}
function test()
{
$data['title'] = 'Facebook API Testing';
$data['user_id'] = $this->fb_connect->user_id;
if($data['user_id'])
{
$data['user_profile'] = $this->fb_connect->user;
}
if($data['user_id'])
{
$data['logout_url'] = $this->fb_connect->getLogoutUrl();;
}
else
{
$data['login_url'] = $this->fb_connect->getLoginUrl();
}
$this->template->load('template', 'facebook_connect/test', $data);
}
}
?>
Here is the view:
<h1>php-sdk</h1>
<?php if($user_id): ?>
Logout
<?php else: ?>
<div>
Login using OAuth 2.0 handled by the PHP SDK:
Login with Facebook
</div>
<?php endif ?>
<h3>PHP Session</h3>
<pre><?php print_r($_SESSION); ?></pre>
<?php if($user_id): ?>
<h3>Your Avata</h3>
<img src="https://graph.facebook.com/<?php echo $user_id; ?>/picture">
<h3>Your User Object (/me)</h3>
<pre><?php print_r($user_profile); ?></pre>
<?php else: ?>
<strong><em>You are not Connected.</em></strong>
<?php endif ?>
I get stuck at it and couldn't figure out why.
Use this example provided by facebook:
https://github.com/facebook/php-sdk/blob/master/examples/example.php
But keep your $this->load->library('fb_connect'); and make sure to add $this->fb_connect to any facebook library calls in that example.
It works 100%. Try to just put all the code in the controller to make sure it works, then distribute as needed. Not sure what your problem is, perhaps faulty return url.

Resources