Save Facebook credentials on React Native and Firebase - facebook

I'm really new to React Native. My intention is that by storing the credentials provided by FBSDK's loginWithReadPermissions, the user won't have to log in each time the app launches, but just one time after it is first installed. Maybe store it somewhere I can check the credentials in componentWillMount().
My first question is: does the FBSDK do this automatically? If not, how can I do this?
I have this code for Facebook Auth:
facebookAuthentication(callback){
LoginManager.logInWithReadPermissions(['public_profile', 'user_likes', 'email']).then(
function(result) {
if (result.isCancelled) {
alert('Inicio de sesiĆ³n cancelado');
} else {
AccessToken.getCurrentAccessToken().then((accessTokenData) =>{
const credential = Firebase.auth.FacebookAuthProvider.credential(accessTokenData.accessToken);
Firebase.auth().signInWithCredential(credential).then((result) =>{
return callback;
}, (error) =>{
console.log('Error en firebase' + error);
});
}, (error) =>{
console.log('ACCESS TOKEN ERROR: ' + error);
});
}
},
function(error) {
console.log('Login failed with error: ' + error);
}
);
}
The code works perfectly, thanks in advance.

With React Native you can use Asyncstorage, which is basically what localstorage is for the web realm: a key-value pair mini-database.
Actually, you can retrieve the currently logged in user using Firebase's firebase.auth().currentUser. Maybe you can check on app startup if it returns a valid user object.

Related

Unsuccessful debug_token response from Facebook: The App_id in the input_token did not match the Viewing App

I'm implementing facebook authentication in my Ionic app and I keep getting the above error.
facebookLogin() {
return this.facebook.login(['email'])
.then((res: FacebookLoginResponse) => {
console.log('root', res);
if (res.status === 'connected') {
console.log('res', res);
const credential = firebase.auth.FacebookAuthProvider
.credential(res.authResponse.accessToken);
console.log('credential', credential);
this.afAuth.auth.signInWithCredential(credential)
.then((response) => {
this.getUserdetail(res);
console.log(response);
}).catch((error) => {
console.log('facebookLogin', error);
});
}
}).catch((error) => {
console.log(error);
alert('error:' + error);
});
}
The console shows me I'm getting the credentials:
But afterwards i get the following error:
"Unsuccessful debug_token response from Facebook: {"error":{"message":"(#100) The App_id in the input_token did not match the Viewing App","type":"OAuthException","code":100,"fbtrace_id":"***********"}}"
One thing I noticed is in the config.xml there was already an ID. I tried changing that to the app ID provided in the facebook developer console to no avail.
I've also searched for solutions in Stack and one suggested disabling App Secret in the facebook dev console but that option is already disabled.
Any help would be greatly appreciated...I've been stuck on this for a while now.
Thanks

Firebase Facebook authentication : Malformed or expired auth credential

I'm working on a react native ios app using facebook authentication and firebase.
I created my facebook app, copied the secret keys to my firebase facebook auth mode, but when i'm trying to sign in with facebook credential using firebase I'm getting this error : The supplied auth credential is malformed or has expired.
I had a look at this issue : FB login - Firebase.Auth() Error: The supplied auth credential is malformed or has expired which is the quite similar to mine, but the answer didn't help me because my keys are the same in my facebook app configuration than in my firebase facebook auth mode.
Here is the code i'm using when the facebook auth button is pressed :
facebookLogin = () => {
LoginManager.logInWithPermissions(['public_profile', 'email'])
.then(
(result) => {
if (result.isCancelled) {
Alert.alert('Whoops!', 'You cancelled the sign in.');
} else {
AccessToken.getCurrentAccessToken()
.then((data) => {
const credential = firebase.auth.FacebookAuthProvider.credential(data.accessToken);
console.log(credential);
firebase.auth().signInWithCredential(credential)
.then(() => this.props.navigation.replace('Home'))
.catch((error) => {
console.log(error.message);
this.setState({ errorMessage: error.message })
});
});
}
},
(error) => {
Alert.alert('Sign in error', error);
},
);
};
I hope you guys can help me, maybe I mistook when I configured my facebook app.
Thank you in advance.
turns out Facebook Graph API is not supported by firebase yet check this out
the reason why Graph API is not supported

react-native-facebook-login returning errors when I try log user into firebase

I have tried every way I can think and am running into the same issue all day.
I am building a react native mobile application. I am using firebase as my database and react-native-facebook-login package to log the user in.
Currently the package works fine, I enter the fb details and the correct data is being returned and the user is 'logged in', I can console log the result but trying to do anything else returns an error.
I have tried:
Passing an action (Redux) where I do the firebase login, error:
Cannot read property 'loginUser' of undefined
setState to the resulting data, error:
this.setState is not a function
I am not sure exactly how to do the firebase authenticate with credentials but am happy to figure that out later, I just need to be able to access the data in the first place!
My component:
...
class FBLoginWrapper extends Component {
state = { user: null };
render() {
return (
<FBLogin
buttonView={<FBSignInView />}
ref={(fbLogin) => { this.fbLogin = fbLogin }}
loginBehavior={FBLoginManager.LoginBehaviors.Native}
permissions={["email","user_friends"]}
onLogin={function (e) { this.props.loginUser(e); }}
onLoginFound={function (e) { this.setState({ user: e }); }}
/>
);
}
...
If you need more code let me know. I have included two different ways I have tried and failed under [onLogin] and [onLoginFound]. I will use one implementation for both when I have something that works.
Ideally I would like to call the action {this.props.loginUser(e)} but if I have to do it through a setState that is fine too at this point.
you should use the onLoginFinished property if you just need to access the data returned.
This is how I use the LoginButton in one of my apps:
AccessToken is part of the FBSDK package
const FBSDK = require('react-native-fbsdk');
const {
LoginButton,
AccessToken
} = FBSDK;
....
<View>
<LoginButton
publishPermissions={["publish_actions"]}
onLoginFinished={
(error, result) => {
if (error) {
alert("login has error: " + result.error);
} else if (result.isCancelled) {
alert("login is cancelled.");
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
let token = data.accessToken.toString();
global.storage.save({
key: 'loginState',
rawData: {
token: token
},
});
firestack.auth.signInWithProvider('facebook', token, '')
.then((user)=>{
Actions.tabbar({profile:user});
});
}
)
}
}
}
onLogoutFinished={() => alert("logout.")}/>

Handling Facebook/Google login with ngCordovaOauth in Ionic + Firebase

I'm trying to implement Firebase authentication with angularfire signInWithCredential method for my Ionic app. As I'm using Firebase 3.x SDK, the methods signInWithRedirect and signInWithPopup are not yet supported on mobile devices. Thus I'm using the plugin ngCordovaOauth.
var ref = firebase.database().ref().child("users");
$scope.users = $firebaseArray(ref);
$cordovaOauth.facebook("//removed_client_id", [ "public_profile", "email"]).then(function(result) {
var credentials = firebase.auth.FacebookAuthProvider.credential(result.access_token);
$scope.authObj.$signInWithCredential(credentials).then(function(authData) {
var existUser = $scope.users.$getRecord(authData.uid);
if(existUser == null){
$scope.user = {
uid: authData.uid,
displayName: authData.displayName,
avatar: authData.photoURL,
email: authData.email,
contact: "0000000000",
provider: "facebook"
}
firebase.database().ref("users/" + authData.uid).set($scope.user);
}
$rootScope.result = authData;
$state.go("menu.home");
}, function(error) {
console.error("ERROR: " + error);
});
}, function(error) {
console.log("ERROR: " + error);
});
The problem that I'm facing is I have no idea what the structure of 'authdata' is as I couldn't find any documentation for the same. With sigInWithPopup, firebase returns 'result' object; contents of which can be accessed like 'result.user.uid', 'result.user.displayName' or 'result.user.email'. How can I achieve the same here as I'm trying to store the user profile when he logs in for the first time? Any help? I'm testing on android device. Thank you!
signInWithCredential returns a promise that resolves with a firebase.User same as signInWithEmailAndPassword and all other sign in apis.
Check the docs for more info on firebase.User:
https://firebase.google.com/docs/reference/js/firebase.User

Getting all Pages user is Admin of using Graph API

I am trying to get a list of all the pages the logged user an Admin of, but I am getting the error "An active access token must be used to query information about the current user". Here is the code I am using:
function login(){
FB.login(function(response) {
if (response.authResponse) {
$.get("https://graph.facebook.com/me/accounts", function(data) {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function(data) {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
} else {
// not auth / cancelled the login!
}
}, { scope: "manage_pages" });
}
So in this code, after logging in, the call $.get("https://graph.facebook.com/me/accounts") throws the error.
UPDATE:
I am able to get the the list using FB.api("/me/accounts"). So how come I can't get it using this code? What am I doing wrong? Thanks.
Simple: You are not passing a user access token with your direct request:
$.get("https://graph.facebook.com/me/accounts", function(data) { ... });
instead of
var accessToken = "aoidhfgoafhgoidfhg"; // replace with real access token
$.get("https://graph.facebook.com/me/accounts?access_token=" + accessToken, function(data) { ... });
The FB SDK does this internally/automatically. What's not really clear to me is why you don't use the FB SDK here as well, if you're already using it for FB Login. That doesn't make much sense IMHO.