I have an app on facebook, which is kind of a competition between users. Each user gains points and the one with most points wins.
I keep the IDs of the users in a table in my database. When a user enters the app, there's a script that checks if he is already in the table, and if not, it adds the user id to the table.
Then, I have a page that shows all of the users and how many points they have. I get through the graph api the user's name by his ID, and then shows it on a nice table.
The only problem is: when a user that used the application once deletes it from his installed application on facebook, I can't get his name anymore, and I get an uncaught OAuth exception.
How can I check if the user has installed the app, so I can display his name only if the app is currently installed on his facebook?
Basically, here is what you would need to do.
<?php
include_once("facebook.php");
$facebook = new Facebook(array(
'appId' => YOUR_APP_ID,
'secret' => YOUR_APP_SECRET
));
$user = $facebook->getUser();
try {
$user_profile = $facebook->api('/me');
} catch(FacebookApiException $e) {
$user = null;
}
if($user) {
// authenticated user
$name = $user_profile['name'];
}
This makes an API request for the current logged in user and, provided it fails, catches the exception and sets the $user variable to null. Then you can do a simple check to see if $user exists.
Hopefully this will point you in the right direction.
I would like to suggest to check this client side.
Then when a user returns you can execute this to see if the permissions are still available, and if not request them again:
FB.getLoginStatus(function(response){
if(response.status == 'connected'){
appisinstalled-actonthis();
}else{
// request permissions
FB.login(function(response){
if(response.status == 'connected'){
appisinstalled-actonthis();
}else{
handlethecancelpermissions();
}
});
}
});
Within your appisinstalled-actonthis function you can then add there name and/or profile pic
Just my two cents!
Related
I have a very simple application of scoreboard in which I send an email to the users with the link. which looks like : http://localhost:8888/users/evqGeyCgo4tIG2C for now. here the string after /users/ is a unique pin that is generated and emailed to the user.
So user simply clicks on the link and in the background I am trying to retrieve email and password of the user and attempt to login. But unfortunately, I cant use hashed password stored in Database to login.
This is my code :
Way 1 :
$user = User::select('email','password')->where('pin',$pin)->first();
if (Auth::login($user)) {
// Authentication passed...
return redirect()->intended('/user');
}
Way 2 :
$user = User::select('email','password')->where('pin',$pin)->first();
if (Auth::attempt(['email' => $user->email, 'password' => $user->password])) {
// Authentication passed...
return redirect()->intended('/user');
}
Unfortunately second way fails as I cant use the hashed password. And the first way I looked it from here but I dont see redirect to trigger. from here : https://laravel.com/docs/4.2/security#manually
I dont mind any other way/method to get the user loggedin with a pin. And I dont mind if any one user sees some other users profile.
So you might be thinking the pin is passed in url can be used by other user to login too. But I am not worried about it. Its just scores that users see of their game.
I think what you need is to log users in by their ID:
$user = User::select('id')->where('pin',$pin)->first();
Auth::loginUsingId($user->id);
return redirect()->intended('/user');
You are very close, I would do something like this
// based on the fact that you have a Request object
$user = User::where('email', $request->input('email'))
->where('password', \Hash::make($request->input('password')))
->where('pin', $request->input('pin'))
->first();
if(! $user) {
// you do not have a user that was found, so return some error
return redirect()->back()->withInput()->withErrors('Invalid user');
}
// since everything is good, just log the user in
Auth::login($user);
// redirect
return redirect()->route('whatever');
Having an issue with the Facebook PHP API/SDK, let me begin by describing:
I made a website where you can enter 'quotes' (short messages) and then after saving the quote in the website (read; too a mysql db behind it) you can decide to share the quote with Facebook to be able to win stuff.
The flow (how it should work) is this:
User opens my site, PHP gets a login url from the Facebook PHP API/SDK
PHP reads & memorizes the 'state' url variable from the login url from the above step (which several sites mention would be a valid way to identify users)
A user saves a quote, I store the state variable from above in the db record of that quote so I can use it again later to match returning users with saved quotes.
The user decides to want to win, so he/she clicks the Facebook share button, which points their browser too the Facebook login url from step 1
The user's browser is now looking at some Facebook pages where they have to allow access for the app and allow that it can post to their wall
Once the user has given said access, they return to the callback url of my site (which happens to be the same as the 'origin url' from step 4)
PHP on my site finds the state variable in the returned url variables(?), goes trough the database to find a matching quote record, and if found, it stores some Facebook user data (userid and path to avatar) in the related db record.
PHP continues to post their earlier saved quote to the user's Facebook wall.
In essence, things work, but the most important bit, step 7, identifying who comes back via the state variable, does not. The problem is that I just get some lengthy 'code' GET variable back, and not the 'state' GET variable, and nowhere in the API docs or on StackOverflow or via Google do I find how to change it so I do get the 'state' GET variable returned again...?
So to recap, basically what I'm looking for is an ability to send some sort of identifier to Facebook that then gets included in the callback-url, and to my knowledge, that's what the 'state' variable seems best for, if it would work that is.
I'm using the currently latest API (facebook-php-sdk-v4-5.0.0.zip from this morning) Below I've shared all relevant code I use to interface with the Facebook PHP API/SDK, all this code resides in the index.php in public_html dir of my site, the callback url of my app is this same index.php
This code is pieced together from several examples, and essentially works, I just don't get the needed state variable back.
require_once __DIR__ . '<PATH-TOO-FB-API>/src/Facebook/autoload.php';
session_start();
$fbStateCode = ""; // used to memorize state code
$fbLoginUrl = ""; // user to memorize login url
// Init the API
// If you go end up testing this, dont forget too change <APP-ID> & <APP-SECRET>
$fb = new Facebook\Facebook([
'app_id' => '<APP-ID>',
'app_secret' => '<APP-SECRET>',
'default_graph_version' => 'v2.4',
'default_access_token' => isset($_SESSION['facebook_access_token']) ? $_SESSION['facebook_access_token'] : '<APP-ID>|<APP-SECRET>'
]);
// login helper
$helper = $fb->getRedirectLoginHelper();
// try get an accesstoken (wich we only have if user returned from facebook after logging in)
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
//echo 'Graph returned an error: ' . $e->getMessage(); // When Graph returns an error
} catch(Facebook\Exceptions\FacebookSDKException $e) {
//echo 'Facebook SDK returned an error: ' . $e->getMessage(); // When validation fails or other local issues
}
if (isset($accessToken)) {
// User is logged in!
try {
// Now we look up some details about the user
$response = $fb->get('/me?fields=id,name');
$facebook_user = $response->getGraphUser();
exit; //redirect, or do whatever you want
} catch(Facebook\Exceptions\FacebookResponseException $e) {
//echo 'Graph returned an error: ' . $e->getMessage();
} catch(Facebook\Exceptions\FacebookSDKException $e) {
//echo 'Facebook SDK returned an error: ' . $e->getMessage();
}
// if facebook_user has an id, we assume its a user and continue
if(isset($facebook_user['id'])) {
$avatarUrl = "http://graph.facebook.com/".$facebook_user['id']."/picture";
// THE BELOW 8 LINES HANDLE LOADING A QUOTE FROM DB WITH MATCHING STATE AND SAVING
// ADDITIONAL DATA TOO IT, THE ONLY ISSUE HERE IS THAT $_GET['state'] DOESNT EXIST
// THE REST OF THIS PROCESS HAS ALREADY BEEN TESTED AND PROOFED TO BE WORKING
$curr_quote = Quotes::getQuoteByFbStateCode($_GET['state']);
$curr_quote_data = $curr_quote->getData();
$curr_quote->updateData(array(
"fb_access_token" => $accessToken,
"fb_uid" => $facebook_user['id'],
"fb_avatar_path" => $avatarUrl
));
// Save it
if($curr_quote->save()) { // Success! quote in db was updated
// Now that we are logged in and have matched the returned user with a saved quote, we can post that quote too facebook
$_SESSION['facebook_access_token'] = (string) $accessToken; // storing the access token for possible use in the FB API init
// This is the data we post too facebook
$msg_data = array (
'message' => $curr_quote_data['quote']
);
$response = $fb->post('/me/feed',$msg_data,$accessToken); // do the actual post (this, like everything else besides state variable, works)
} else { // Fail! quote in db was NOT updated?!
// handle errors
}
}
} else {
// User is NOT logged in
// So lets build up a login url
$permissions = ['public_profile','publish_actions']; // we want these permissions (note, atm im the only tester, so while the app still needs to be reviewed for the 'publish_actions' permission, it works cuz i own the app and test with same fb account)
$fbLoginUrl = $helper->getLoginUrl('http://<WEBSITE-URL>/index.php', $permissions); // get the login url from the api providing callback url and permissions array
$fbLoginUrlParams = array();
parse_str($fbLoginUrl, $fbLoginUrlParams); // store the url params in a new array so that we can (read next comment below)
$fbStateCode = $fbLoginUrlParams['state']; // read out and store the state url variable
}
Below here is logic for saving a new quote to database based on user interaction, and making use of $fbStateCode, this part of the process functions fine as well, quotes get saved with their own unique state values like they should.
So that's the story, I'm trying to do something which I'm pretty sure isn't anything special, it's just poorly documented or something?
Ended up rewriting the lot, now it works fine, not sure whats different now vs what i had, so cant really provide an awnser for others running into similair issues, sorry bout that.
#Cbroe; forwarded the headsup you gave me too the customer, got literally told 'not our problem, but the problem of the company that made the concept', so time will tell if this ever even goes online lol, still, thanks for the headsup :P
Read the docs about the state variable here:
The state parameter is a value which is provided by the client prior to the login wen redirecting to the login url. If it's available then, it get's send back in the callback url.
So, unless you provide any state variable in your step1, you won't get any from FB (and any other oAuth2 implementing API). There will not be any "magic" making that appear other than providing it with a feasable state of your PHP app in step 1.
Actually, the state parameter is to give any client the ability to restore a context, whenever the callback "happens". So the content of the state variable may be a session id, a user id or any other value which helps restoring the (php)apps context again after receiving a callback
EDIT
I assume, that the state variable needs to be added somewhere in this function here:
$helper = $fb->getRedirectLoginHelper();
I am the administrator of a Facebook page which needs to have an age restriction of 17+ on it.
On my website, I am making some Graph API queries, like querying photo albums and linking to them on Facebook. I am using the PHP Facebook API.
I can't seem to get to grips around the page access tokens and when they expire and when not.
I tried to follow this answer here, which was highly voted, but it isn't clear what you do with the first access_token after you copy it. I am not sure if this is even valid any more.
I tried to access the page using the access token I get when I do me/accounts in Graph Explorer and it works, but after some time it expires and I get an exception that the token expired. I need something that stays working and doesn't expire and need me to go in and update it.
This is the code I have so far:
$fbconfig = array();
$fbconfig['appId'] = DEF_APP_ID;
$fbconfig['secret'] = DEF_APP_SECRET;
$fbconfig['fileUpload'] = false;
Facebook::$CURL_OPTS[CURLOPT_SSL_VERIFYPEER] = false;
$facebook = new Facebook($fbconfig);
//I am not sure if the following is the right way
$facebook->setAccessToken(DEF_ACCESS_TOKEN);
$facebook->setExtendedAccessToken();
...
try
{
$albums_resp = $facebook->api('/'.$id.'/albums','GET');
...
}
catch (FacebookApiException $ex)
{
error_log($ex);
}
What is the right way to achieve this?
I need to create a system plugin (no auth plugin!) where a user which logges into the frontend automaticaly gets logged in the backend too.
(The user has the rights to log into the backend via /administrator.)
I try to do it via the very basic code you see below, the result is positive, but if i go to the backend the user still needs to log in.
In the session table the backend session row is set, but the "guest" field is set to 1 instead of 0 and the userid is set to 0 instead of the correct id.
How can this be done?
function onAfterInitialise() {
if(JFactory::getUser()->get('id')) { // logged in?
$credentials = array();
$credentials['username'] = "walter"; // hardcoded first
$credentials['password'] = "123"; // hardcoded first
$options = array();
$options['action'] = 'core.login.admin';
$result = $app->login($credentials, $options); // this seams to work
if (!($result instanceof Exception)) {
$app->redirect("www.bummer.de");
}
}
Apart from this being a very bad idea, as mentioned in this question Joomla! is implemented as two applications a front-end (/index.php) and back-end application (/administrator/index.php).
In the code provided you don't show where $app is initialised so I'm guessing that it's probably something like $app->JFactory::getApplication('site');.
To login to the admin app you need to get it rather than the front-end client app e.g.
$adminApp->JFactory::getApplication('administrator');
$result = $adminApp->login($credentials, $options);
n.b. this is untested code just typed in to stack overflow... it should be right.
I can post on group / page and user wall, but i don't want my app to show error when posting on selected wall, if the selected wall doesn't allow posting so is there any way to know that are we able to post on target wall?
Note: I found two similar questions but they do not pertain to exactly what i want
1 Application able to post on user's Wall
2 How to check the permission whether a friend allow me to post on his wall or not using php sdk
Please discuss in comment before taking any negative action.
Thanks.
AFAIK, there's no way to check exactly the way you want, coz the privacy varies, as you have already said. The only privacy setting that can be queried is the OPEN, CLOSED, or SECRET of group, which can be done by calling the graph api:
`http://graph.facebook.com/$Group_id`
That returns json data that has a field privacy, which will be one of OPEN, CLOSED, or SECRET.
But on top of that you have settings for groups where you can restrict posting to only group admins. And that permission can not be checked.
So i think what you'll have to do is check the returned value, i.e $response after making the post. If the permission is not given, then the returned data looks like this:
{
"error": {
"type": "Exception",
"message": "You do not have permission to post in this group."
}
}
Hence you can check if $response has "error" field, and inform the user accordingly. Somewhat like this: if(isset($response['error'])).
Also check the fql table that represents groups for more info, if you haven't already.
Do you mean how to check if a user has given permission to post on their wall?
try {
// Get the permissions this user has
$call = $this->facebook->api("/me/permissions");
// If they have the permission we require ('publish_stream')
if($call['data'][0]['publish_actions']){
try{
// Do your magic here...
// Also include your access token in the array
$params = array('message'=> 'hello world');
$call = $this->facebook->api('/me/feed','POST',$params);
}catch(FacebookApiException $e) {
$result = $e->getResult(); // prob no permissions
}
}
} catch(FacebookApiException $e) {
$result = $e->getResult();
}
So basically, first check to see if the user has permissions for a particular action, then if they do $call[data][0]['publish_action'] will be a set to 1 (int).
Example output of $call = $this->facebook->api("/me/permissions");
[installed] => (int) 1
[email] => (int) 1
[publish_actions] => (int) 1
I have the above permissions from the user through facebook.