CakePHP Facebook Plugin redirection problem - cakephp

I have implemented Nick's Facebook Plugin.
Have Imported the Facebook Helper and Connect Component in the app_controller. Changed the Html accordingly.
app_controller.php
<?php
class AppController extends Controller {
var $components = array('Session', 'Facebook.Connect' => array('createUser' => false), 'Auth');
function beforeFilter() {
$this->Auth->allow('*');
$this->set('fbuser',$this->Connect->user());
}
function beforeFacebookSave() {
}
function beforeFacebookLogin($user) {
//Logic to happen before a facebook login
}
function afterFacebookLogin() {
//Logic to happen after successful facebook login.
}
}
?>
in the home.ctp
<?php
if($fbuser) {
echo $this->Facebook->logout();
debug($fbuser);
} else {
echo $this->Facebook->login();
}
?>
Once i click login and allow the permissions. it keeps refreshing indefinitely :(
My App settings online
Am on Windows Machine and access the code with this base http://localhost/spider/
i also set the canvas url as follows
I think its because of the configuration on the application settings online. Nick in the Video visits localhost.localdomain/websites/facebook_example to access the code. What is the need of the ".localdomain"

I had the same problem, and I found the answer here:
http://ardentdev.com/no-facebook-connect-cookies-for-localhost-development/
While doing some Facebook Connect development, I found that the expected cookies were not being set when developing on localhost. To fix the problem, I added localhost.local to my hosts file (pointing at 127.0.0.1) and changed the settings for my Facebook application to use localhost.local as the base domain.

Related

How to redirect to CodeIgniter controller using angular js

I am using CodeIgniter controller functions.
(example)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Me extends CI_Controller {
public function __construct()
{
parent::__construct();
if (is_logged_in()){if (is_admin()) { redirect('login'); }}
else { redirect('login');}
}
public function change_password()
{
$id=$this->session->userdata['user_data']['id'];
$data = json_decode(file_get_contents("php://input"));
$my_data=array(
'pass'=>$data->pass,
'new_pass'=>$data->new_pass,
);
$result=$this->vanesh_model->change_pass($id,$my_data);
if($result==1)
{
$arr = array('msg' => "Password changed successfuly.", 'error' => '');
$jsn = json_encode($arr);
print_r($jsn);
}
else if($result==2)
{
$arr = array('msg' => "", 'error' => 'Old Password is Invalid');
$jsn = json_encode($arr);
print_r($jsn);
}
else if($result==3)
{
$arr = array('msg' => "", 'error' => 'Sorry, Password change failed');
$jsn = json_encode($arr);
print_r($jsn);
}
}
}
?>
I am afraid of using angular session services, so I want to maintain sessions with only CI. What I am doing in my application is add, update, delete only if he is logged in. And I am using information stored in session. Consider the situation, suppose, I am logged in and doing something, side by side: I destroy the session using browser tools. Now I am continuing with application (doing operations like: change password). I have/had maintained error messages, success messages, its ok. If session OFF, it gives error message. But instead of error messages, I want to redirect to LOGIN page(with page refresh).
Note: For CI Login controller, I didn't used angular js. I have used angularjs only after login.
If by opening new tab I destroy the session, and come back to application's tab: I am able to perform tasks(may be with errors,). If session is OFF I see this in Browser's console: http://localhost/ums/login
This is because of CI constructor(please look over the code).
You should separate angular and CI as much as possible, since both have view-controller it creates a mess. Instead you should have CI in a separate folder, call it api, for example, after that anything you will need from CI should be acessed from angular with ajax calls.
I made a small webapp a while ago and this seemed to be the best way to organize code.
Few updates have been made to angular since then so if there's a better way please let me know
Solved.
Used javascript function. Checking session by http request everytime. If response comes "1". Means redirect to login as:
/* function for checking logged-in and role */
function check_session()
{
$.get("servercontroller/check_session", function(data, status){
if(data=="1") /* error 1 => un-athorized user */
{
window.location.href="/login-page-url";
}
});
}

cakephp prevent admin to access front-end

I am using cakephp 1.3.I want to prevent the admin to access the front-end action.
I am using croogo cms.Is there any configuration settings or anything else by which admin can't visit the front end ?
for example:
Suppose there is any controller named shop, and there are two actions 'buy' and 'detail':
class ShopController extends AppController {
....
....
function beforeFilter() {
$this->Auth->allow(array('detail'));
parent::beforeFilter();
}
function detail() {
$detail= $this->shop->find('first');
...
}
function buy() {
$buy= $this->shop->find('first');
...
}
}
Now when admin is login from admin-panel and comes on http://embidomain.com/shop/detail page he can visit this page but when he goes to shop/buy, then he will asked for login.

CakePHP facebook integration logout issue with CakePHP-Facebook-Plugin

I'm looking for a way with the CakePHP-Facebook-Plugin log users out of my app, but not log them out of their own facebook.
If I call my apps logout() function no matter what I do I just keep getting logged back in via facebook. If I use the plugins facebook helper in the view to generate a logout button ($this->Facebook->logout()), it definetly logs the user out of my app...but it also logs them out of their own facebook which is kinda ridiculous.
So how do I work around this to log users out of my app, and but leave them logged into facebook.
To have them "logout" of your app (meaning the next time they try to use the app, they're going to be asked to authenticate your app again), then send an HTTP DELETE command to me/permissions using their user access token.
I know this is an old question, but I figured this one out just now, trying to figure this same thing out. Basically, although in the demos with webtechnick's examples, he puts "Facebook.Connect" in the AppController, but, if you want the selective logout piece, the Best place to put it is within the actual controllers that you want to use it in or put it in AppController and pass noAuth=> true into it. Either way, whichever way you choose, you set up one controller (facebook_controller.php?) to handle the logins, and set its component with the noauth set to false (which is default). That way, you have total control over whether or not the user is logged back into the site, and you can ACTUALLY log them out (with the regular redirect($this->Auth->logout());
Let me give you an idea:
app_controller.php
class AppController extends Controller {
var $components = array('Auth', 'Acl', 'Session');
//or if you want access to "$this->Connect" universally:
// array('Auth', 'Facebook.Connect' =>
// array('noauth'=>'true', 'Acl', 'Session');
}
users_controller.php:
class UsersController extends AppController{
var $helpers = array('Facebook.Facebook');
//an example of the users controller, enabling connect, but
// not authorizing the user (because logout() used by Auth is here)
var $components = array('Email', 'Session', 'Facebook.Connect' => array('createUser'=>false, 'noauth'=>true));
//login() doesnt need to be shown and can be left alone
function logout(){
if ($this->Connect->FB->getUser() == 0){
$this->redirect($this->Auth->logout());
}else{
//ditch FB data for safety
$this->Connect->FB->destroysession();
//hope its all gone with this
session_destroy();
//logout and redirect to the screen that you usually do.
$this->redirect($this->Auth->logout());
}
}
}
your "facebook_controller.php":
class FacebookaController extends AppController {
...
// i dont personally like to have his piece create my user so:
var $components = array('Facebook.Connect' => array('createUser'=>false));
...
function login(){
//just need this stub function for later
$this->autoRender = false;
}
//you also need this for deauths or they will still be able to get into the site after deauth (against policy or whatever)
function deauthorize(){
//get user id from facebook API
$uid = $this->Connect->FB->getUser();
$record = $this->User->findByFacebookId($uid);
$this->User->delete($record['id'], FALSE);
}
}
now your users/login.ctp file:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'your app id', // App ID
channelUrl : '//'+window.location.hostname+'/facebook/channel', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Additional initialization code here
FB.Event.subscribe('auth.statusChange', function(response){
if (response.status == "connected"){
alert('redirecting you to auto facebook login');
//here is out default place for login
window.location.href = "http://"+window.location.hostname + "/facebook/login";
}
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script>
<?php e($this->Facebook->login(array('registration-url'=>'http://www.yoursite.com/facebook/signup'))); ?>
And that should be pretty much it. I hope this helps someone reading this who still needs the help.
You may want to take a look at $this->Facebook->disconnect();
It does exactly what you want.
http://projects.webtechnick.com/docs/facebook/default/FacebookHelper.html#disconnect
Have you tried killing the PHP session?
// this would destroy the session variables
session_destroy();

webtechnick Facebook logout not working

I am using webtechnick facebook plugin, i have everything set and its FB login works perfectly.
I am using $fbc =$this->Connect->User(); to fetch FB details of logged in user
And using
<?php
echo $facebook->login(array('perms' => 'email,publish_stream','size'=>'small'));
?>
<?php
echo $this->Facebook->logout();
?>
for login,logout respectively. i am getting details of user after login, but it will not unset after performing a logout();
I am using webtechnick fb plugin version 3.1.1 . Please help me
My help isn't much help because I haven't really found a solution. The good news is that you are not alone:
https://github.com/webtechnick/CakePHP-Facebook-Plugin/issues/43
What I can tell you is that the facebook cookie (fbsr_{facebook_app_id}) is either not deleting or is being recreated and that is the root of the problem.
EDIT
I may have found out what's going on here. Until the other night I had not bothered to setup my .htaccess files and both http:/www.example.com and http:/example.com were valid.
In my facebook app, I had set up example.com as a domain and pointed the site URL to www.example.com.
With the fbsr_{app id} cookie, I noticed that it was sometimes on the http://example.com while my cakephp cookies were on www.
I played around with changing the URL in my facebook app (adding www, removing www) and then also started doing the rewrite rules in .htaccess to add or remove www. I just removed the appdomain entirely from my facebook app, forced www. to the domain, and now everything is kosher.
So I think the trick is to
Not have the app domain in the facebook app
Fix canonicalization of www via .htaccess
This ensures that both the cakephp and the facebook cookies are being saved to the identical domain, and when you logout they are removed from said domain.
Hope this makes sense...
I know it is too late for some suggestion for this post. Still feel it might help some one who later reading this post.
I too was facing the logout issue with the plugin , I have modified a function in ConnectComponent in the plugin to clear its session details if the action is "logout". Below is the modified function :
private function __syncFacebookUser(){
if($this->Controller->params['action'] == 'logout')
{
$this->Controller->Session->delete('FB');
$this->uid = null;
$this->Controller->Session->delete('Auth.User');
}
else
{
if(!isset($this->Controller->Auth)){
return false;
}
$Auth = $this->Controller->Auth;
if (!$this->__initUserModel()) {
return false;
}
// if you don't have a facebook_id field in your user table, throw an error
if(!$this->User->hasField('facebook_id')){
$this->__error("Facebook.Connect handleFacebookUser Error. facebook_id not found in {$Auth->userModel} table.");
return false;
}
// check if the user already has an account
// User is logged in but doesn't have a
if($Auth->user('id')){
$this->hasAccount = true;
$this->User->id = $Auth->user($this->User->primaryKey);
if (!$this->User->field('facebook_id')) {
$this->User->saveField('facebook_id', $this->uid);
}
return true;
}
else {
// attempt to find the user by their facebook id
$this->authUser = $this->User->findByFacebookId($this->uid);
//if we have a user, set hasAccount
if(!empty($this->authUser)){
$this->hasAccount = true;
}
//create the user if we don't have one
elseif(empty($this->authUser) && $this->createUser) {
$this->authUser[$this->User->alias]['facebook_id'] = $this->uid;
$this->authUser[$this->User->alias][$this->modelFields['password']] = $Auth->password(FacebookInfo::randPass());
if($this->__runCallback('beforeFacebookSave')){
$this->hasAccount = ($this->User->save($this->authUser, array('validate' => false)));
}
else {
$this->authUser = null;
}
}
//Login user if we have one
if($this->authUser){
$this->__runCallback('beforeFacebookLogin', $this->authUser);
$Auth->authenticate = array(
'Form' => array(
'fields' => array('username' => 'facebook_id', 'password' => $this->modelFields['password'])
)
);
if($Auth->login($this->authUser[$this->model])){
$this->__runCallback('afterFacebookLogin');
}
}
return true;
}
}
}
For me now the facebook plugin is working fine for facebook connect.

cakephp: signup link on register page not working

I'm trying to use the Auth component only for viewing the progress report of a student. For all other links, authentication is not required. For the discussion board i already have a separate forum plugin.
When the user clicks the progress report link on the navigation bar, the user is directed to /merry_parents/register. Here, new users will click on signup link and existing users will click on login link.
However, my signup link is not working. I'm not being directed to the signup page when I click on signup. What am I doing wrong? any help is much appreciated.
The following is my code:
register.ctp
<?php
echo $this->Html->link('Sign Up','/merry_parents/signup').' for new user |'.$this->Html->link('Login','/merry_parents/login',array()).' for existing user';
?>
merry_parents_controller.php
<?php
class MerryParentsController extends AppController{
var $name='MerryParents';
var $components=array('Auth','Session');
function beforeFilter(){
//$this->Auth->authorize='actions';
$this->Auth->loginAction=array('controller'=>'merry_parents','action'=>'register');
//$this->Auth->loginRedirect=array('controller'=>'merry_parents','action'=>'report_card');
}
function register(){
}
function login(){
}
function logout(){
}
function signup(){
if (!empty($this->data)){
//$this->Auth->password($this->data['MerryParent']['password2'] used to get what the hashed password2 would look like.
if ($this->data['MerryParent']['password']==$this->Auth->password($this->data['MerryParent']['password2'])){
$merryparent_id=$this->MerryParent->field('id',
array('MerryParent.name'=>$this->data['MerryParent']['name'],
'MerryParent.email'=>$this->data['MerryParent']['email'])
);
echo $merryparent_id;
print_r($this->data);
if ($this->MerryParent->save($this->data))//record with $merryparent_id is updated
{
$this->Session->setFlash('You will be receiving an email shortly confirming your login and password.');
$this->Auth->login($this->data); //automatically logs a user in after registration
$this->redirect(array('controller'=>'pages','action'=>'home'));
}
else
echo $this->Session->setFlash(__('Your admission could not be saved, please try again!',true));
}//end if ($this->data['MerryParent']['password']....
else
echo $this->Session->setFlash('Typed passwords did not match');
}//end if (!empty($this->data))
}
}
?>
You have to use following code in your MerryParentsController controller.
function beforeFilter() {
$this->Auth->allow('signup');
}
This will allow your register method to get register.
For more information please read http://book.cakephp.org/view/1255/AuthComponent-Methods

Resources