React native google sign in stuck on white loading screen - react-native

I am trying to use #react-native-google-signin/google-signin to login on react-native but after clicking to login button and selecting my account (on an real android device), the following blank loading screen opens and nothing else happens. This is how I am trying to achieve the login.
const SignupContainer = ({ navigation }) => {
useEffect(async () => {
GoogleSignin.configure({
webClientId:
'<webClientId>',
offlineAccess: true, // if you want to access Google API on behalf of the user FROM YOUR SERVER
forceCodeForRefreshToken: true, // [Android] related to `serverAuthCode`, read the docs link below *.
iosClientId:
'iosClientId',
})
await isSignedIn()
}, [])
const signInWithGoogle = async () => {
try {
console.log('hello 1')
await GoogleSignin.hasPlayServices()
console.log('hello 2')
const { user } = await GoogleSignin.signIn()
console.log('hello 3')
console.log({user: user})
loginWithGoogle({ user })
} catch (error) {
if (error.code === statusCodes.SIGN_IN_CANCELLED) {
console.log('User Cancelled the Login Flow')
} else if (error.code === statusCodes.IN_PROGRESS) {
console.log('Signing In')
} else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
console.log('Play Services Not Available or Outdated')
} else {
console.log('Some Other Error Happened')
}
}
}
}
Hello 1 and Hello 2 get logged but Hello 3 is never reached.
This is the screen I get stuck on

Related

React Native Facebook User Photos is Denied

I have a react native app and i can login with facebook. However I can't get the users photo. First of all FB hash key is correct and my app is in live mode. I sent the app to APP REVIEW and the photos are always denied by team and they are telling me they can't get the photos of the users. I use "react-native-fbsdk-next": "^4.3.0" and we use our own api url for photos, not using Graph Api of FB. There is [user_photos] as well beside public_profile. Does anyone know the reason for this ? After I login to Facebook, i try to upload photo via FB and it displays a pop up saying " facebook photos permission is denied. This permission allows your app to read photos of Facebook". Why facebook team denies user photo access ? what else should do to make it work ? My login code implementation is below. I could not find anything on Google regarding this kind of issue. Please help
export const facebookLogin = snackBarBottomMargin => {
return async dispatch => {
try {
const result = await LoginManager.logInWithPermissions([
'public_profile',
'user_photos',
]);
if (!result.isCancelled) {
const data = await AccessToken.getCurrentAccessToken();
if (data && data.accessToken) {
await storage.storeData(
PREFERENCES.FB_ACCESS_TOKEN,
JSON.stringify(data),
);
return data;
} else {
console.log('Facebook result fetch token error cancelled');
return false;
}
} else {
console.log('Login cancelled');
return false;
}
} catch (error) {
dispatch(
showSnackbar(strings.login.facebookLoginError, snackBarBottomMargin),
);
return false;
}
};
};
export function handleFetchFBPhotos(accessToken, after) {
return async dispatch => {
function onSuccess(success) {
dispatch(fetchMediaSuccess(success));
console.log('success', success);
return success;
}
function onError(error) {
dispatch(fetchMediaFailed(error));
console.log('error', error);
return error;
}
try {
dispatch(fetchMediaRequest(true));
const config = {
baseURL: Config.FACEBOOK_BASE_URL,
params: {
type: 'uploaded',
fields: 'images',
after,
},
headers: {Authorization: `Bearer ${accessToken}`},
};
const response = await axios.get(FACEBOOK_PHOTOS, config);
if (response.data && response.data.data) {
console.log('response.data', response.data);
console.log('response.data.data', response.data.data);
console.log('onSuccess(response.data)', onSuccess(response.data));
return onSuccess(response.data);
}
} catch (error) {
const errorObj = getErrorResponse(
error,
Config.FACEBOOK_BASE_URL + FACEBOOK_PHOTOS,
);
console.log('onError(errorObj.message)', onError(errorObj.message));
return onError(errorObj.message);
}
};
}

facebook login working on development mode or server mod, when create a build, it's not working on any devices. react native app

feature unavailable facebook login in currently unavailable for this app, since we are updating additionl details for this app. please try again later
working only on my system and device, not working in others,
how to resolve this issue,please help
FacebookSignIn = async () => {
// Attempt login with permissions
try {
const result = await LoginManager.logInWithPermissions(['public_profile', 'email']);
console.log("fb login", result)
if (!result.isCancelled) {
await AccessToken.getCurrentAccessToken()
.then(async res => {
console.log("token", res);
// Create a Firebase credential with the AccessToken
const facebookCredential = auth.FacebookAuthProvider.credential(res.accessToken);
console.log("token", res);
// Sign-in the user with the credential
this.setState({ loder: true })
await auth().signInWithCredential(facebookCredential)
.then(response => {
console.log("Login Data", response);
const data = {
"name": response.additionalUserInfo.profile.first_name,
"email": response.additionalUserInfo.profile.email,
"user_type": 0
}
console.log(data);
fetchPostMethod('/facebook-sign-up', data)
.then(async response => {
this.setState({ loder: false })
if (response.status == 200) {
if (response.data.user_type == 0) {
try {
let user = JSON.stringify(response?.data?.user_type)
await AsyncStorage.setItem('SignINToken', response?.data?.token);
await AsyncStorage.setItem('UserType', user);
this.logmodl();
} catch (e) {
console.log("Login error", e)
}
} else {
this.user();
}
console.log("SignIn Successful", response);
} else {
this.field();
}
})
.catch(response => {
this.setState({ loder: false })
console.log("SignIn faild", response.message);
})
this.setState({ FacebookUserInfo: response });
})
.catch(error => {
console.log('Login Data Error', error);
})
})
.catch(error => {
console.log('Something went wrong obtaining access token ', error);
})
}
} catch (error) {
console.log("ERROR WHILE LOGIN! ", error);
}
}
feature unavailable facebook login in currently unavailable for this app, since we are updating additionl details for this app. please try again later
working only on my system and device, not working in others,
how to resolve this issue,please help
Pay attention! For enable Facebook login for other users you need visit the Facebook developer site
and enable work mode for application, moving this switch

Is User already have Permissions FB SDK react native

I have a simple Question i just want to know that is user first time trying to logged in or else.
I am using react native fb SDK and Im enable to find any way.
I already try but not getting success.
AccessToken.getCurrentAccessToken()
Thanks
This is my login facebook function:
Step is:
Get permission
User login
Get token
My code:
import { LoginManager, AccessToken } from 'react-native-fbsdk';
const loginFacebook = () => {
setTypeLogin(TYPE_LOGIN.FACEBOOK)
if (Platform.OS === "android") {
LoginManager.setLoginBehavior("web_only")
}
LoginManager.logInWithPermissions(['public_profile', 'email']).then(
function (result) {
if (result.isCancelled) {
} else {
AccessToken.getCurrentAccessToken()
.then((data) => {
setAccessToken(data.accessToken)
prepareCallApi()
})
.catch(error => {
console.log(error)
})
}
},
function (error) {
console.log('Login fail with error: ' + error);
},
);
};

Implementing authentication flow with react-navigation and redux

I do't know what is happening here. I made simple app with 2 screens, on login success i want to change screen on HomePage. I am using redux, redux-saga and axios with react-native
My submit function on login screen is:
async submit() {
if(this.state.email.length == 0 || this.state.password.length == 0) {
alert("Filed is required")
} else {
if(typeof this.state.email !== 'undefined') {
if(!this.state.email.match(/[^#]+#[^.]+\..+/)) {
alert("E-mail format wrong!")
} else {
console.log('ok auth');
let user = {
email: this.state.email,
password: this.state.password
}
this.props.login(user)
}
}
}
}
Login saga write token in AsyncStorage, on login success and it works fine
export function* loginUser(action) {
const response = yield call(login_api, action.payload)
if(!response || !response.data) {
console.log('wrong login 1: ', response);
//status 422 Unprocessable Entity
return yield put(login_failure('Internal server error for login user'))
}
if(response.status === 200) {
deviceStorage.saveItem('token', response.data.token)
return yield put(login_success(response.data, response.data.token))
} else {
console.log('wrong login 2');
return yield put(login_failure('Error for login user'))
}
}
On login success, reducer returns token i Login.js and then I want to redirect in HomePage. I want to logout user every time when he comes on login page, because I use componentDidMount()
async componentDidMount() {
await deviceStorage.deleteToken('token')
}
componentWillReceiveProps(nextProps) {
console.log('enxtProps: ', nextProps.token.length);
if(nextProps.token.length > 0) {
//TOKEN EXISTS!!! length = 365
this.props.navigation.navigate('HomePage')
} else {
console.log('Error login');
}
this.setState({
token: nextProps.token
})
}
this.props.navigation.navigate('HomePage') in componentWillReceiveProps doesn't redirect on HomePage.
Can someone tell me why?
I have a couple of suggestions for your code.
In Login-Saga wait until token saved
deviceStorage.saveItem('token', response.data.token)
change to
yield deviceStorage.saveItem('token', response.data.token)
Don't use componentWillReceiveProps. It is marked as unsafe in react & remove after version 17. Use componentDidUpdate as below.
componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props)
if (this.props.token !== prevProps.token && this.props.token.length > 0) {
this.props.navigation.navigate('HomePage')
} else {
console.log('Error login');
}
}

React-Native-FBSDK login doesn't return email

I'm trying to use the default <'LoginButton ... > for login in the app through Facebook login, but I can't manage to get the user's email.
This is my button:
<LoginButton
publishPermissions={["email"]}
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")}
/>
And this is how i try to get the user's details:
async FBGraphRequest(fields, callback) {
const accessData = await AccessToken.getCurrentAccessToken();
console.log("token= ", accessData.accessToken )
// Create a graph request asking for user information
const infoRequest = new GraphRequest('/me', {
accessToken: accessData.accessToken,
parameters: {
fields: {
string: fields
}
}
}, this.FBLoginCallback.bind(this));
// Execute the graph request created above
new GraphRequestManager().addRequest(infoRequest).start();
}
async FBLoginCallback(error, result) {
if (error) {
this.setState({
showLoadingModal: false,
notificationMessage: "facebook error"
});
} else {
// Retrieve and save user details in state. In our case with
// Redux and custom action saveUser
this.setState({
id: result.id,
email: result.email,
name: result.name
});
console.log("facebook login",result)
}
}
The console.log("facebook login",result) line returns me only the account name and id, but there is no field for te email...
What am I doing wrong?
PS.: I've also tryed to use a "custom function", but it doesn't work too (for the email, the login worked and i get only the user details like name and id):
async facebookLogin() {
// native_only config will fail in the case that the user has
// not installed in his device the Facebook app. In this case we
// need to go for webview.
let result;
try {
this.setState({showLoadingModal: true});
LoginManager.setLoginBehavior('NATIVE_ONLY');
result = await LoginManager.logInWithReadPermissions(['public_profile', 'email']);
} catch (nativeError) {
try {
LoginManager.setLoginBehavior('WEB_ONLY');
result = await LoginManager.logInWithReadPermissions(['email']);
} catch (webError) {
// show error message to the user if none of the FB screens
// did not open
}
}
console.log("facebook result 1: ", result)
// handle the case that users clicks cancel button in Login view
if (result.isCancelled) {
this.setState({
showLoadingModal: false,
notificationMessage: I18n.t('welcome.FACEBOOK_CANCEL_LOGIN')
});
} else {
// Create a graph request asking for user information
this.FBGraphRequest('id, email, name', this.FBLoginCallback);
}
}
.
.
.
<LoginButton
publishPermissions={["email"]}
onPress={
this.facebookLogin()
}
onLogoutFinished={() => alert("User logged out")}
/>
this are the field request by the app. I need to insert also the user's Email:
!!!RESOLVED!!!
the <'LoginButton ...> props for the permission is "permissions", not "readPermission"...
so the button code is:
<LoginButton
permissions={['public_profile', 'email', 'user_birthday', ]}
onClick={this.facebookLogin}
/>
// imports
import {
Settings,
AccessToken,
LoginManager,
AuthenticationToken,
Profile,
GraphRequest,
GraphRequestManager,
} from 'react-native-fbsdk-next';
//put this lines in useEffect
Settings.setAppID('2920461228193006');
Settings.initializeSDK();
LoginManager.setLoginBehavior('web_only');
// put this method on button press
LoginManager.logInWithPermissions(['public_profile', 'email'])
.then(async data => {
if (!data.isCancelled) {
console.log(data, 'this is data');
if (Platform.OS === 'ios') {
let token =
await AuthenticationToken.getAuthenticationTokenIOS();
console.log(token, 'ios token');
} else {
let token = await AccessToken.getCurrentAccessToken();
console.log(token, 'android token');
}
const infoRequest = new GraphRequest(
'/me?fields=email,name,first_name,last_name',
null,
(err, res) => {
console.log({err, res}, 'this is');
if (Object.keys(res).length != 0) {
doSocialLogin({
registerBy: 2,
token: res.id,
user: {
firstName: res.first_name,
email: res.email,
lastName: res.last_name,
},
});
}
},
);
new GraphRequestManager().addRequest(infoRequest).start();
}
})
.catch(err => {
console.log(err, 'this is fb error');
});