I'm trying to use the Facebook PHP SDK 3.0 to be able to know if a user is currently logged on into his facebook account to display his information.
This is the flow:
User comes to my site and connects his account with my facebook app.
User is now logged in on my site, my site can access his information.
User logs out of facebook.com.
User refreshes my page.
User is logged out of my site.
User logs in on facebook.com.
User refreshes my page.
USER SHOULD BE LOGGED IN ON MY SITE BUT ISN'T.
When you use the Javascript SDK, you can check if user is logged in and everything works fine with the steps. What needs to be done with the PHP SDK 3.0? I don't want to give access_offline permissions, I just want to be able to access the user when he's logged in on facebook.com.
Thanks a lot,
Jeremie
Add this javascript in all pages(core js).
login() and logout() are functions for your system login and logout.
By this it will check every time fb is logged in or not and call function for login.
And will satisfy condition -
USER SHOULD BE LOGGED IN ON MY SITE BUT ISN'T.
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: '113700398662301', status: true, cookie: true, xfbml: true});
/* All the events registered */
FB.Event.subscribe('auth.login', function(response) {
// do something with response
login();
});
FB.Event.subscribe('auth.logout', function(response) {
// do something with response
logout();
});
FB.getLoginStatus(function(response) {
if (response.session) {
// logged in and connected user, someone you know
login();
}
});
};
</script>
based on the signed request, u should be able to know if the user has authorized your app before.
This should give u some status about the user.
to check if he is logged in to fb, for authorized user, u can try to query "/me" and see if you can query it successfully
Related
I implemented the Youtube Analytics API in js and everything is ok with that. I am the content owner and I want to get analytics for all channels and to allow login users to use their analytic.
For example, when some users make login to my dashboard I pass their channel ids to YouTube and it is ok, they get their data. They have to authenticate to YouTube with popup every time they log in.
I want to know is there any way to avoid that and to allow them like content owner to see their data.
I am using
window.onload = function () {
setInitialDates();
authenticate().then(loadClient).then(getDataFromAPI);
}
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/youtubepartner https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube.readonly https://www.googleapis.com/auth/youtubepartner https://www.googleapis.com/auth/yt-analytics-monetary.readonly https://www.googleapis.com/auth/yt-analytics.readonly" })
.then(function () {console.log("Sign-in successful"); },
function (err) {console.error("Error signing in", err); });
}
function loadClient() {
return gapi.client.load("https://youtubeanalytics.googleapis.com/$discovery/rest?version=v2")
.then(function () {console.log("GAPI client loaded for API"); userLoaded = true; },
function (err) {console.error("Error loading GAPI client for API", err); userLoaded = false; });
}
For your question about not having to log-in each time, you would need do the 'server-side flow' method of authentication.
User clicks button in your app to authenticate with YouTube.
YouTube log-in opens, user logs in with google account.
User approves any permission scopes you enabled.
User redirected back to your app with tokens, you can save the 'refresh_token' in your database.
With the refresh_token, you can then generate an authentication token to make API calls.
https://developers.google.com/youtube/reporting/guides/authorization
https://developers.google.com/youtube/reporting/guides/authorization/server-side-web-apps
I'm trying to implement Auth0 with lock (version 10.11.0) inside my Angular2 app. Auth0 works if I list every possible route in Auth0's client's Allowed Callback URLs setting. It seems Auth0 picks up the callback URL from whatever URL the user happens to be on when they decide to login. This is not a scalable approach. How do you solve this?
I've tried entering a redirectUrl value in auth options. This gets me a little further in that the app does redirect to the URL supplied, however, Auth0 lock's authenticated callback never fires so I cannot retrieve authenticated user's profile.
So, I'm stuck. It seems my only course of action is to list every conceivable route in Auth0's client's Allowed Callback URLs setting and pray the guys from marketing do not come up with more routes.
Here's my code:
let options =
{
auth:
{
//redirectUrl: 'http://localhost:4200',
//redirect: true,
responseType: 'token',
params:
{
scope: 'openid user_id name nickname email picture'
}
}
};
this.lock = new Auth0Lock('xxx', 'yyy', options);
this.lock.on("authenticated", (authResult) =>
{
console.log('#### AUTH RESULTS:', authResult);
localStorage.setItem('id_token', authResult.idToken);
this.lock.getProfile(authResult.idToken, (error, profile) =>
{
if (error)
{
return;
}
console.log('#### AUTHENTICATED USER PROFILE:', profile);
});
}
Any ideas on how to make Auth0 work so you do not have to list every possible route a user can be on before deciding to authenticate?
I'm implementing social login with oauth using the package oauth-4-laravel in my laravel application.
Following the instructions of the package I'm able to connect with facebook or with google.
Now I don't want to store user data but still I want a user to access a page only if legged with facebook or google.
I have to check if a user is logged with oauth in a route filter. Something like this
Route::filter('auth', function()
{
if (!OAuth::check()) return Redirect::guest('login');
});
How do I do that? Or should I use another method?
Typically even when you use OAuth as authentication method, your application will still have to store user_id or name, and their email isn't it? If so, you can still apply laravel authentication like so:
//After the OAuth authentication
$user = User::where('email', $email)->firstOrFail(); //$email is the email returned from OAuth
//without acessing DB
$user = new User();
$user->email = $email; //this is an eg, can be replace with whatever user's properties you have.
Auth::login($user); //login the user using laravel
//To logout user manually
Auth::logout();
//In your filters.php
Route::filter('auth', function()
{
if (Auth::guest())
return Redirect::guest('login');
});
I want to create an authentication system whereby the user can "sign up with Twitter", but all this effectively does is authenticate their Twitter account and prefills a registration form with their Twitter username. The user will then be asked to enter an email and password (or an alternative username).
Thus, upon registration, the user has authenticated access to their Twitter account, and the access token can be stored in a database. Later down the line I will use this to access the Twitter API.
Node modules such as everyauth and passport do a lot of the heavy lifting with OAuth, but they only appear to provide a findOrCreateUser method, which doesn't offer a lot of breathing space to do something like what I need to do – that is, redirect to a registration form before registering the user, or if a user is found, just logging them in as per usual.
Here's a quick sketch of a possible approach for this:
Note that Passport does not provide a findOrCreateUser method. All database management and record creation is defined by your application (as it should be), Passport simply provides facilities for authentication.
The key to this approach is to simply create an "incomplete" user record in your database, from the profile data given by twitter. Then, in your application's routes, you can check if the conditions you need are met. If not, redirect the user to a form where they are prompted to fill out missing details.
passport.use(new TwitterStrategy({
consumerKey: TWITTER_CONSUMER_KEY,
consumerSecret: TWITTER_CONSUMER_SECRET,
callbackURL: "http://127.0.0.1:3000/auth/twitter/callback"
},
function(token, tokenSecret, profile, done) {
// Create a user object in your database, using the profile data given by
// Twitter. It may not yet be a "complete" profile, but that will be handled
// later.
return done(null, user);
}
));
app.get('/auth/twitter',
passport.authenticate('twitter'));
app.get('/auth/twitter/callback',
passport.authenticate('twitter', { failureRedirect: '/login' }),
function(req, res) {
// The user has authenticated with Twitter. Now check to see if the profile
// is "complete". If not, send them down a flow to fill out more details.
if (req.user.isCompleteProfile()) {
res.redirect('/home');
} else {
res.redirect('/complete-profile');
}
});
app.get('/complete-profile', function(req, res) {
res.render('profile-form', { user: req.user });
});
app.post('/update-profile', function(req, res) {
// Grab the missing information from the form and update the profile.
res.redirect('/home');
});
Slight clarification. The test "if (req.user.isCompleteProfile())" could be:
if (req.user.isCompleteProfile)
ie, you create a field 'isCompleteProfile' when you are making the user record in the twitter step, and mark it true or false, depending on what you know of the user
or: it is a call to a function, thus
if (isCompleteProfile(req))
in this case, you have a separate function which tests the state of the user you have just created/modified, thus:
function isCompleteProfile(req) {
if (typeof req.user.local.email === "undefined") return false;
else return true;
}
And, I'd echo the praise for Jared and this marvellous tutorial on authentication in passportjs.
When a user comes to my site, i used to open a new window to authenticate the user and ask for permission through my app(call it as UseCase1). But when a user is already logged-in i was trying to fetch the logged-in user info through PHP SDK so that i need not open a new window and check for the same(You will be avoiding opening a new window that closes after a while since the user is already logged in). But the getUser() method doesn't return me anything. The same method works fine when i go through the UseCase1(open new window which closes automatically).
Below is the code i am trying to use:
$facebook = new Facebook(array(
'appId' => $appId,
'secret' => $appSecret,
'oauth' => true
));
$me = $facebook->getUser();
if ($me) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
//code to redirect to login url
// USECASE1
// use $facebook->getUser() one USECASE1 is over
// now the user info is generated properly
}
}
All the times the user is going through USECASE1(but with an empty window since user is logged in and already authenticated the app) even though he is already logged-in and already authenticated the app previously.
Any idea why this is happening
In your code, if the user is getting to 'USECASE1', then it shows that '$me' is being set, because it is getting to your try/catch.
Using $me = $facebook->getUser(); is not a test for whether a user has accepted permissions for your application yet.
I suspect that the reason for the 'FacebookApiException' Exception being thrown is because you haven't got your user permissions yet.
I'd suggest reading the authentication flow and the example PHP SDK authentication flow, see the following links:
http://developers.facebook.com/docs/reference/php/facebook-api/
http://developers.facebook.com/docs/authentication2/