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

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.")}/>

Related

React Native Facebook SDK ShareDialog asks to login again

I'm currently doing a project using react native where I need to let users to login using facebook. So I use React-native-fbsdk LoginButton component to let users to login and get the access token. Also part of the project needs let users to share links to their profiles.
In order to do that, I followed as GitHub repo of Facebook which says how to add ShareDialog. After adding both LoginButton and ShareDialog, I ran the app. Login was successful and I got the access token. But when I try to share a link, it asks me to login again. If I login with ShareDialog, it let me to share post and everything as expected.
But if I logout with LoginButton after login with ShareDialog too, both components perform logout successfully. Problem is Login does not handle for both components with single login.
Below is my code.
render() {
return (
<View style={styles.container}>
<LoginButton
publishPermissions={["publish_actions"]}
onLoginFinished={
(error, result) => {
if (error) {
alert("Login failed with error: " + error.message);
} else if (result.isCancelled) {
alert("Login was cancelled");
} else {
alert("Login was successful with permissions: " + result.grantedPermissions)
}
}
}
onLogoutFinished={() => alert("User logged out")}/>
<TouchableHighlight onPress={this.shareLinkWithShareDialog}>
<Text style={styles.shareText}>Share link with ShareDialog</Text>
</TouchableHighlight>
</View>
);
}
shareLinkWithShareDialog = () => {
const shareLinkContent = {
contentType: 'link',
contentUrl: 'https://www.sample.com/',
contentDescription: 'Test Sharing Description'
};
var tmp = this;
ShareDialog.canShow(shareLinkContent).then(
(canShow) => {
if (canShow) {
return ShareDialog.show(shareLinkContent);
}
}
).then(
(result) => {
if (result.isCancelled) {
alert('Share cancelled');
} else {
alert('Share success with postId: ' + result.postId);
}
},
(error) => {
alert('Share fail with error: ' + error);
}
);
}
Please help me here. I cannot identify what's wrong with this.
Note
I checked this using a Test User of Facebook and it also has all relevant permissions including manage_pages and test user has it's own Test Page too.
I got a similar problem and that was because I hadn't installed facebook app on my phone. Seems like your code is fine.
However I haven't used Test Page and Test User options in facebook but I hope they are no different than a normal user when it comes to functionalities. Just try to install the facebook app and run your app. Should be fine.

axios and mongo - trying to delete using the mapped _id as the perimeter. It responds with 200 but object remains in the db

Trying to make a simple CRUD app using react, axios and mongoose.
Here is my axios:
deleteUser(id) {
axios.delete(`${rootUrl}/api/users/${this.state.id}`, {
params: { id }
})
.then(response => {
// this.setState({ users: response.data });
console.log('deleteUser response', response, this.state);
});
}
Here is the relevant API route:
router.delete('/users/', (req, res) => {
const { id } = req.body;
User.findByIdAndDelete(id, (error, data) => {
if (error) {
console.log('error in deleting!');
throw error;
} else {
console.log('user has been deleted', data);
res.status(204).json(data);
}
});
});
It returns
DELETE /api/users/?id=5b34e5b5dfef8b4sd234567 204 47.816 ms - -
But when I GET users, the deleted user remains.
Here is the render I am mapping state into. I think I am pulling the id in properly but I am not sure what else to try:
{this.state.users.map(user => {
return (
<div className="Users1" key={user._id}>
<Card>
<CardBody>
<CardTitle>{user.username}</CardTitle>
<CardText>{user._id}</CardText>
<Button onClick={() => this.deleteUser(user._id)}
key={user._id}
type="button"
color="danger"
>
X
</Button>
</CardBody>
</Card>
</div>
);
})}
and here is state:
state = {
users: [],
id: ''
};
I had a similar problem. I had success by looking at the req.query property on the API server, rather than req.body:
const { id } = req.query;
I figured it out by dumping the entire req object to the console.
On the client side, my request did not include the id in the URL. I just included it in the params object. This seemed to help. So the equivalent call in your code would look something like this:
axios.delete(`${rootUrl}/api/users/`, {
params: { id }
})
I hope this helps. I'm still just learning React Native, so I'm hardly an expert. But I wanted to share what worked for me in case it helps others.

Save Facebook credentials on React Native and Firebase

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.

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.

Getting user app token using react-native facebook SDK

I've gotten facebook login working using the new https://github.com/facebook/react-native-fbsdk, however I can't seem to get the user token which is usually returned in the response. Anyone found a way to get this information? The other SDK's https://github.com/magus/react-native-facebook-login returns it on the login request but the new FB sdk doesn't, and the documentation on the github page doesn't mention it anywhere.
Found the answer after some more digging. You need to use the fbsdkcore to access the user token. Heres how you use it.
var FBSDKCore = require('react-native-fbsdkcore');
var {
FBSDKAccessToken,
} = FBSDKCore;
var Login = React.createClass({
render: function() {
return (
<View>
<FBSDKLoginButton
onLoginFinished={(error, result) => {
if (error) {
alert('Error logging in.');
} else {
if (result.isCanceled) {
alert('Login cancelled.');
} else {
FBSDKAccessToken.getCurrentAccessToken((token) => {
console.log(token.tokenString);
})
}
}
}}
onLogoutFinished={() => console.log('Logged out.')}
readPermissions={[]}
publishPermissions={['publish_actions']}/>
</View>
);
}
});
You don't need a third party module (react-native-fbsdkcore)
The package (react-native-fbsdk) has instructions on it's Github page: https://github.com/facebook/react-native-fbsdk#usage
After you've logged the user in, you can fetch the access credentials as follows:
import { AccessToken } from 'react-native-fbsdk';
AccessToken.getCurrentAccessToken().then(data => {
console.log(data.accessToken.toString())
})