How to preserve user logged in using Parse JS and Facebook SDK - javascript

I'm using Parse Server + Parse JS Sdk to handle user login through Facebook. Everything works fine until I refresh web browser. What data should I store after login process is done? I belive that FB AccessToken is important to keep Facebook Session, but what about Parse Session.
Current code:
login: function (callback) {
console.log('loggin in...')
Parse.FacebookUtils.logIn('user_likes,email', {
success: function (parseUser) {
if (!parseUser.existed()) {
console.log('signed up and logged in!')
} else {
console.log('logged in!')
}
console.log('parse user is: ', parseUser.id)
if (callback) { callback() }
},
error: function (parseUser, error) {
console.log('login cancelled: ', error.message)
}
})
}

You don't need to manually store anything. You can use the parse function:
Parse.User.current()
To see if there is already a user logged-in.
We made this function:
function userAuthenticated(){
if(Parse.User.current() === null){
return false;
}
if(Parse.User.current().authenticated()){
return true;
}
else{
return false
}
}

Related

How to detect the user's firebase authentication login status in a vue js project?

I am trying to detect the userstate. If the user is logged in I want to set the data "userstate" to true. I am using vuefire and firebase into my vue project. I tried the way shown below, but it does not work
data() {
return {
userstate:false
};
},
watch:{
userstate:{
firebase.auth().onAuthStateChanged(function(user){
if(user){
this.userstate= true;}
else{
this.userstate=false;
}
})}
In Firebase you can check whether the user is signed in or not by using a function provided by the firebase which is auth().currentUser
// user will return true which means user EXISTS!
let user = firebase.auth().currentUser;
if (user) {
this.userstate = true; // If it exists
} else {
this.userstate = false; // If it doesn't
}
There are cases when the above mentioned method returns null / undefined for the user. So this solution is for your existing solution. So in that case try modifying your existing function to this:
async function IsLoggedIn() {
try {
await new Promise((resolve, reject) =>
firbase.auth().onAuthStateChanged(
user => {
if (user) {
// Yes User is signed in.
resolve('User is there');
} else {
// No user is not signed in.
reject('There is no user');
}
},
// Prevent console errors
error => reject(error)
)
)
return true
} catch (error) {
return false
}
}
Also since you intend to watch for the auth state change you can simply register the listener right after you initialize Firebase, you do not necessarily have to insert it in a VueJS watch block, you can insert it in your main.js for example, and if you are using a store like VueX you can update the state in the store and pull that information from any component of the VueX application.
firebase.initializeApp(configOptions);
firebase.auth().onAuthStateChanged(user => {
if (user) {
this.userstate = true;
} else {
this.userstate = false;
}
});

How to properly use FB.logout/getLoginStatus

I have a webpage where when the user logins in, I execute FB.login:
FB.login(
(response) => {
if (response && response.authResponse) {
console.log(response.authResponse);
} else {
throw new Error('Login failed');
}
},
{ scope: 'permissions,that,I,ask,for' }
);
Running that code, I successfully get back an authResponse with status: "connected". I don't save the tokens in the response in any way.
When the user goes to logout, I call FB.logout:
FB.logout((response) => console.log('Logged out', response));
This gives me the error FB.logout() called without an access token. Now, there are many SO questions (here and here for example) and blog posts that deal with how to handle that error. Specifically, most of them recommend wrapping your logout call in a FB.getLoginStatus call, the idea being that the FB SDK needs to have an internal copy of the access token.
FB.getLoginStatus((response) => {
if (response && response.status === 'connected') {
FB.logout((logoutResponse) => console.log('Logged out, logoutResponse));
}
});
However, when I do that, the response coming back from FB.getLoginStatus has status: "unknown".
How can the status be unknown when 1) I just called FB.login, and then 2), I literally just called FB.getLoginStatus?
What do I need to do to get FB.logout to work properly?
(Tested in a Chrome 66 Incognito tab with no script blockers of any kind running.)
Here is the FB.init call we use:
FB.init({
appId: env.FACEBOOK_APP_ID,
version: 'v2.9',
});
If it's helpful: we wrap all async FB.* API calls with a Promise so that we can chain off of when they finish. For example:
return new Promise((resolve, reject) => {
FB.login((response) => {
if (response && response.authResponse) {
resolve(response);
} else {
reject(new Error('FB.Login failed'));
}
});
});

Issue with Wizcorp phonegap facebook plugin

We are trying to integrate the Wizcorp PhoneGap facebook plugin (https://github.com/Wizcorp/phonegap-facebook-plugin) to support the login process in a new Ionic app.
The login with Facebook seems to work just fine for a new user. The problem is when the users sign off and try to log back in he get the error:
Facebook error: Session was closed and not closed normally
what are we doing wrong here ?
Here's the code that we are using right now:
function fbLogin() {
facebookConnectPlugin.login(['email'], function (response) {
alert("Login Successfull");
alert(JSON.stringify(response));
}, function (error) {
alert("Login ERROR");
alert(JSON.stringify(error));
})
}
function getDetails() {
facebookConnectPlugin.getLoginStatus(function (response) {
if (response.status === 'connected') {
alert("You're connected!");
var userID = response.authResponse.userID;
facebookConnectPlugin.api('/' + response.authResponse.userID + '?fields=id,name,picture.width(400).height(400)', [], function (result) {
alert(JSON.stringify(result));
})
} else if (response.status === 'not_authorized') {
alert("Not Autherized!");
} else {
alert("You're not loggin into Facebook!");
}
});
}
function fbLogout() {
facebookConnectPlugin.logout(function (response) {
alert("Logout success");
alert(JSON.stringify(response));
}, function (error) {
alert("Logout ERROR");
alert(JSON.stringify(error));
})
}
We have checked this link:
https://github.com/Wizcorp/phonegap-facebook-plugin/blob/master/TROUBLESHOOTING.md#no-reply-from-login
however when we try to implement the code below - we get an error
Tyeperror cordova.getActivity is not a function
PackageInfo info = cordova.getActivity().getPackageManager().getPackageInfo("com.goapes.golearn", PackageManager.GET_SIGNATURES);
The above link tells us that we need another Hash Key in our Facebook App Dashboard, so is there another way of obtaining this Hash?
I think you better to try this plugin. Because I developed a app using this plugin and it's in production now. :)
here check this

authWithOAuthPopup Error on Web Platform

I am trying to use Firebase's Facebook authentication on a webpage, but I get this error:
Login failed Error: Invalid authentication credentials provided.
at Error (native)
at http://45.55.203.213/js/firebase.js:160:367
at e (http://45.55.203.213/js/firebase.js:140:400)
Here's my Javascript code:
var ref = new Firebase("https://fantasy-smash-bros.firebaseio.com/");
function FBLogin() {
ref.authWithOAuthPopup("facebook", function(error, authData) {
if (error) {
console.log("Login failed", error);
} else {
loginWithAuthData(authData);
}
});
}
function loginWithAuthData(authData) {
username = authData.facebook.displayName;
avatarURL = authData.facebook.cachedUserProfile.picture.data.url;
userID = authData.facebook.id;
}
function attemptLogin() {
var user = ref.getAuth();
if (user) {
loginWithAuthData(user);
} else {
$("#fb-login").click(function () {
FBLogin();
});
}
}
$(document).ready(function () {
attemptLogin();
});
Note: I have imported firebase.js. Here's a copy of the Javascript I used.
I believe I have setup everything correctly: adding Firebase's callback URL to my Facebook app's whitelist, enabling Facebook authentication on the Firebase app. But I am still stumped on what to do. Any help would be greatly appreciated.

Facebook on PhoneGap/Cordova -- File protocol?

Have searched everywhere for this without luck. I'm getting this error when running PhoneGap app on device (works fine in browser):
Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.
This is because I haven't added the host to the facebook app configuration. BUT, PhoneGap/Cordova accesses the app through the file:/// protocol, so there's no domain for me to add to Facebook.
Potential options: 1) Figure out how to use a cordova native plugin (this is hard because we're using Parse), 2) Switch Cordova to use localhost instead of file:// (not sure how to do this).
I've been down this road and ultimately went with option #1. Since we're not really dealing with a website there is no domain to add. Cordova needs to use file:// I don't think there is any way around it. The trick with using the plugin is keeping the login status in sync with Parse (use Parse.FacebookUtils.logIn). He's some code that should help you out. This is how I check the login status:
try {
console.log("Trying to get FB login status");
return FB.getLoginStatus(function(response) {
var accessToken, currentView, expDate, facebookAuthData, uid, user;
console.log(response);
if (response.status === "connected") {
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
console.log("Logged in!");
user = Parse.User.current();
if (user != null) {
console.log("we have a user");
} else {
console.log("we don't have a user... need to login with parse");
expDate = new Date(response.authResponse.expirationTime);
facebookAuthData = {
id: response.authResponse.userID + "",
access_token: response.authResponse.accessToken,
expiration_date: expDate.toISOString()
};
Parse.FacebookUtils.logIn(facebookAuthData, {
success: function(_user) {
return console.log("Logged in with Parse!");
},
error: function(error1, error2) {
return console.log("Unable to create/login as Facebook user");
}
});
}
} else {
// not logged in to fb...
}
});
} catch (e) {
return console.log(e);
}
Here's how I handle logins:
return FB.Event.subscribe("auth.authResponseChange", function(response) {
var expDate, facebookAuthData;
if (response.status === "connected") {
console.log(response.status);
try {
expDate = new Date(response.authResponse.expirationTime);
facebookAuthData = {
id: response.authResponse.userID + "",
access_token: response.authResponse.accessToken,
expiration_date: expDate.toISOString()
};
return Parse.FacebookUtils.logIn(facebookAuthData, {
success: function(_user) {
//return window.location.hash = "loginsuccess";
},
error: function(error1, error2) {
console.log("Unable to create/login to as Facebook user");
}
});
} catch (ex) {
return console.log("parse login error " + ex);
}
} else if (response.status === "not_authorized") {
// handle not auth event
} else {
// take them home?
}
});
}

Categories

Resources