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.
Related
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();
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>
I'm just wondering how I can use/define my own function using the $this->set() method in CakePHP? I want to do something like this...
AppController.php
<?php
function checkSetup() {
if ($this->Auth->user('setup') == 'notcomplete') { return true; }
}
$this->set('isSetup', checkSetup());
?>
And then I will be able to access and call it in my view file:
<?php if ($isSetup): ?>
You haven't setup your profile yet!
<?php endif; ?>
I've tried that, but It clearly doesn't work as I get a massive fatal error. Any ideas/suggestions on how I can do this?
$this->set('isSetup', checkSetup());
That line needs to be inside some function in order to be called. Presumably you want it in the beforFilter of your app controller - something like this:
<?php
App::uses('Controller', 'Controller');
class AppController extends Controller {
function beforeFilter() {
$this->set('isSetup', checkSetup());
}
function checkSetup() {
if ($this->Auth->user('setup') == 'notcomplete') { return true; }
}
}
?>
I am using cakephps Auth Component to login to my site. When I correctly enter in my username and password, it will log me in. Then when I use loggedIn() to check that I am logged in, it is very inconsistent in returning true.
This is my AppController where I set loggedIn() to a variable to use later:
<?php
App::uses('Controller', 'Controller');
App::uses('File', 'Utility');
App::uses('AuthComponent', 'Component');
class AppController extends Controller {
public $components = array(
'Session',
'Auth'=>array(
'loginRedirect'=> array('controller'=>'users', 'action'=>'index'),
'logoutRedirect'=> array('controller'=>'users', 'action'=>'index'),
'authError' =>"You can't access that page",
'authorize'=> array('Controller')
)
);
//determines what logged in users have access to
public function isAuthorized($user){
return true;
}
//determines what non-logged in users have access to
public function beforeFilter(){
$this->Auth->allow('index','view');
$this->set('logged_in', $this->Auth->loggedIn());
$this->set('current_user', $this->Auth->user());
}
}
And here is a bit of my code where I use 'logged_in'
<?php if($logged_in): ?> //this only returns true some of the time
Welcome <?php echo $current_user['username']; ?>. <?php echo $this->Html->link('Logout', array('controller'=>'users', 'action'=>'login')); ?>
<?php else: ?>
<?php echo $this->Html->link('Login', array('controller'=>'users', 'action'=>'logout')); ?>
<?php endif; ?>
And here is my login():
public function login(){
if($this->request->is('post')){
if($this->Auth->login()){ //this returns true every time
$this->redirect($this->Auth->redirect());
}else{
$this->Session->setFlash('Your username and/or password is incorrect');
}
}
}
I have tried calling $this->Auth->loggedIn() instead of using $logged_in but I get the error that the Auth Helper cannot be found.
Please let me know if there is any more information needed to answer my question.
Move these lines to beforeRender()
$this->set('logged_in', $this->Auth->loggedIn());
$this->set('current_user', $this->Auth->user());
Besides that, nothing seems wrong with your code.
The comment that Auth->login() would always return true only happens when you pass any argument to the login() method, which the code you show doesnt have though.
OK, I admit it. I'm a CI newbie. I'm doing something really basic wrong and I've been at it for a couple of hours and can't find my error.
I have a controller called login. It's in the resources folder in my controllers folder. It loads a view called login_form. But for the life of me it will not load if I go to domain.com/resources/login or domain.com/resources/index. But I can get to it via a route:
$route['engineering-resources/login'] = "resources/login";
Even when I get to it this way, my form action isn't found. Here is my form:
<?php
echo form_open('resources/login/validate_credentials'); //folder/controller/method. I think this is where my problem is
echo form_input('username', 'Username');
echo form_password('password', 'Password');
echo form_submit('submit', 'Login');
echo anchor('login/signup', 'Create Account');
echo form_close();
?>
The path is my resources folder in my controllers folder, and the controller is the login controller using the validate_credentials method. Here is the pertinent part of my login controller:
class Login extends Controller {
function index()
{
$data['title'] = 'Engineering Resources | Login';
$data['main_content'] = 'resources/login_form';
$this->load->view('templates/main.php', $data);
}
function validate_credentials()
{
$this->load->model('login/membership_model');
$query = $this->membership_model->validate();
if($query) // if the user's credentials validated...
{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('resources/members_area');
}
else // incorrect username or password
{
$this->index();
}
}
The index function works when I use the route, but not when I use the above domain.com paths. I assume that is why it cannot find the validate_credentials method. What am I doing wrong?
Here is main.php
<?php $this->load->view('includes/header.php'); ?>
<?php $this->load->view('includes/nav.php'); ?>
<?php $this->load->view($main_content); ?>
<?php $this->load->view('includes/footer.php'); ?>
$route['engineering-resources/login'] = "resources/login";
This does not route to engineering-resources/login/validate_credentials to resources/login/validate_credentials
You should have something like this:
// not tested
$route['engineering-resources/login/(\S*)'] = "resources/login/$1";
One more thing is that if you are using routes, you should use the routes from your views too..
echo form_open('engineering-resources/login/validate_credentials');