How do I fix firebase auth/netwok-request-failed when opened by social media browsers? - firebase

I recently had a bug to solve for a customer on my webapp. It is givng a
Firebase: Error(auth/network-request-failed)
However I also realize upon selecting 'Ok' on the alert, the browser redirects the user to login with their account, however has a my FIREBASE_AUTH_DOMAIN - {projectID}.firbaseapp.com .
This only occurs when user visit the login/signUp link via social media browser.
So I changed the signInWithPopUp -> signInWithRedirect.
And now I still get the error if I am redirected to the login/signUp page. How I do fix this?
const loginGoogle = async () => {
closeSnackbar();
const provider = new GoogleAuthProvider();
signInWithRedirect(auth, provider)
.then(() => {
createUserDoc(); //creates a userProfile document
enqueueSnackbar(
`Welcome ${
!auth.currentUser.displayName ? "" : auth.currentUser.displayName
}`,
{ variant: "success" }
);
})
.catch((error) => {
alert(error.message);
});
router.push(redirect || "/shop");
};

Related

Display the user-disconnected page in NextJs

I'm looking for a way to show to user, like WhatsApp web, a page that when connection is poor or user has no internet, says "Your internet connection is down".
How to do this in Next Js ?
You have to add this custom hook to your _app.js file :
function useNetwork(){
const [isOnline, setNetwork] = useState(window.navigator.onLine);
useEffect(() => {
window.addEventListener("offline",
() => setNetwork(window.navigator.onLine)
);
window.addEventListener("online",
() => setNetwork(window.navigator.onLine)
);
});
return isOnline;
};
Add your logic :
const isOnline = useNetwork();
////////////////////////
useEffect(()=>{
if(!isOnline){
// show your going offline message here
}
},[isOnline])

React Native: firebase auth/network-request-failed error when trying to create a new user, but not on login?

So I have a simple React Native application where I added firebase into. I've added a firestore and setup Authorization on my firebase account. When trying to login with the set account, the login succeeds using the following code:
const onButtonPress = () => {
setErrorMessage(null);
const auth = getAuth();
signInWithEmailAndPassword(auth, email, password)
.then((res) => {
navigation.navigate('Main'); // When going to the same Stack.Screen you're already on, it won't do anything
})
.catch((error) => {
setErrorMessage('Error: ' + error.message);
});
}
However, when I try to register in the same manner, it fails with the following error:
Firebase: Error (auth/network-request-failed)
This is my register code:
const onButtonPress = () => {
if (!email || !password || !passwordRepeat) {
setErrorMessage('Please fill in the entire form');
} else if (password === passwordRepeat) {
const auth = getAuth();
createUserWithEmailAndPassword(auth, email, password)
.then((res) => {
setErrorMessage(null);
navigation.navigate('Main');
})
.catch((error) => {
setErrorMessage('Error: ' + error.message);
});
} else {
setErrorMessage('Error: passwords don\'t match');
}
}
The "funny" thing is, when I try to login with a wrong account/password combination with my login-code, it gives the same error.
So since login works, but not with wrong account/pw combination and getting the same error as Register, I'm guessing my database setup etc is correct (since I can login), but during the create-account, something goes wrong?
Does anyone know what could be causing this and how I can fix it so that I can create new users in my app?
EDIT: I'm also using Expo in this application and using "expo start" to test it on my personal Android device.
I was facing the same issue up until now, turns out I using onChange in the instead of onChangeText, and using it to set the state for the email and password, which in turn was setting the email and password as an object instead of a string.
Example:
<TextInput
placeholder="Password"
value={password}
onChange={newText => {setPassword(newText)} //This should be onChangeText
placeholderTextColor="black"
style={styles.textInput}
secureTextEntry
/>
Try to console.log() the values for your email and password before creating the user, perhaps you're doing something similar.

How to properly persist login state using FireBase in React Native EXPO?

I used email and password to sign in through Firebase. However, once I reload the app, I need to sign in again. Is there a way to automatically log user in once the app is reloaded?
I am using EXPO managed project with functional structure btw, not with class structure.
if you're still facing this problem.
Here's how I've done it.
Here's my App.js
const [loggedIn, setLoggedIn] = useState(false);
useEffect(() => {
return firebase.auth().onAuthStateChanged(setLoggedIn);
}, []);
if (loggedIn) {
return <HomeScreen />
} else {
<Login />
}
Here's the login code.
I have a simple form with email and password and a button, when pressed, this functions is called.
const handleLogin = async () => {
await firebase
.auth()
.signInWithEmailAndPassword(email, password)
.catch((err) => {
setVisible(true);
setModalMessage(err.message);
});
};
Let me know if this worked.

Nuxt SSR auth guard with Firebase auth

I'm trying to implement auth guards in Nuxt with Firebase Auth, but I keep running in to problems. At the moment I'm able to login, but the correct page isn't loaded after login, after login the user should be redirected to the '/profile-overview' page but that doesn't happen. When I navigate away from the 'profile' page to another page and then go back I do automatically go to the 'profile-overview' page. So the login works, there is just something wrong with the navigation / refresh of the page after login. Also when I refresh the page the user is logged out again, I would except the user to still be logged in then?
My code so far:
Page:
loginGoogle () {
this.$store.dispatch('signInWithGoogle').then(() => {
console.log('reload')
location.reload()
//window.location.reload(true)
}).catch((e) => {
this.title = 'Google login failed'
this.message =
"Something went wrong, please try again later. If this problem keeps happening please contact: jonas#co-house.be " + "Error: " + e.message;
this.dialog = true;
})
},
Middleware:
export default function ({ store, redirect, route }) {
console.log('user state' + store.state.user)
console.log('route ' + route.name)
store.state.user != null && route.name == 'profile' ? redirect('/profile-overview') : ''
store.state.user == null && isAdminRoute(route) ? redirect('/profile') : ''
}
function isAdminRoute(route) {
if (route.matched.some(record => record.path == '/profile-overview')) {
return true
}
}
Plugin:
import { auth } from '#/services/fireInit.js'
export default context => {
const { store } = context
return new Promise((resolve, reject) => {
auth.onAuthStateChanged(user => {
if (user) {
return resolve(store.commit('setUser', user))
}
return resolve()
})
})
}
Store (function to login only:
signInWithGoogle ({ commit }) {
return new Promise((resolve, reject) => {
auth.signInWithPopup(GoogleProvider).then((result) => {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
return resolve(store.commit(state.user, result.user))
// ...
}).catch((error) => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
})
})
},
Does anyone have any idea what I could be doing wrong, or some documentation / tutorial I could read?
Thanks in advance.
You need to init your user on server in nuxtServerInit. See this repo for example implementation https://github.com/davidroyer/nuxt-ssr-firebase-auth.v2

Firebase Google login not staying persistence

I am developing an application, with an feature of Google Login through Firebase. I am trying to login via Google with the help of an library, known as react-native-google-signin. It is well known library in the field of ReactNative for Google Login.
My problem is not with this library, but the problem is that while I am using react-native-google-signin library with firebase to login via google. Firebase User is not staying persistence, I mean to say that when I am opening app after close FirebaseUser is getting null. Below the code I am using to login via firebase,
GoogleSignin.signIn().then(data => {
const credentials = firebase.auth.GoogleAuthProvider.credential(data.idToken, data.accessToken);
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
.then() => {
return firebase.auth().signInWithCredential(credentials);
}).catch(error => {
console.log('Error', error);
})
}).then(user => {
console.log('user', firebase.auth().currentUser);
}).catch(error => {
console.log('Error', error);
})
I also checked Firebase Docs, tried by using setPersistence() method but still I am getting null user after open app again.
You can try this
when you first time open your app you get user null, but after login one time then reopen your app and you will get previously logged in user in your console
async _setupGoogleSignin() {
try {
await GoogleSignin.hasPlayServices({ autoResolve: true });
await GoogleSignin.configure({
webClientId: 'YOUR WEBCLIENTID',
offlineAccess: false
});
const user = await GoogleSignin.currentUserAsync();
console.log("user",user); // HERE YOU GET LOGGED IN USER IN YOUR CONSOLE FIRST TIME IT WILL BE NULL BUT AFTER YOU GET PREVIOUSLY LOGGED IN USER
this.setState({user});
}
catch(err) {
console.log("Play services error", err.code, err.message);
}}
then
_signIn() {
GoogleSignin.signIn()
.then((user) => {
console.log(user);
this.setState({user: user});
const credential = firebase.auth.GoogleAuthProvider.credential(user.idToken, user.accessToken);
// console.log(credential);
return firebase.auth().signInAndRetrieveDataWithCredential(credential);
})
.catch((err) => {
console.log('WRONG SIGNIN', err);
})
.done();}
it is worked for me...
hope it will help you...

Resources