Returns null when logging in with firebase - firebase

When I click the button, the user logs in but then returns null, but the user is logged in. Why does the null value return?
const handleSubmit = async (e) => {
e.preventDefault();
try {
await signIn(email, password,);
onAuthStateChanged(auth, (currentUser) =>{
console.log(currentUser);
if(currentUser && currentUser.emailVerified === false){
toast.error("E-posta Doğrulaması gerekiyor")
logout();
}else if(currentUser && currentUser.emailVerified === true ){
navigate('/account')
toast.success("GİRİŞ BAŞARILI")
} else if(!currentUser){
toast.error("kullanıcı bulunamadı");
}

Related

Getting null on reset password with Firebase in react native

I'm getting null in response when hitting password reset function of firebase.
//login with firebase
const ForgotPasswordRequest = async () => {
try {
setIsLoading(true);
const res = await auth().sendPasswordResetEmail(SignupDetails.email); //email is passing
console.log(res); // getting null here
setIsLoading(false);
} catch (error) {
setIsLoading(false);
if (error.code === 'auth/email-already-in-use') {
alert('That email address is already in use!');
}
if (error.code === 'auth/invalid-email') {
alert('That email address is invalid!');
}
if (error.code === 'auth/user-not-found') {
alert('There is no user record with this email!');
}
console.error(error);
}
};
these are the versions i'm using
"#react-native-firebase/app": "^14.2.1",
"#react-native-firebase/auth": "^14.2.1",
Update: This is happening on success response for the email exists in firebase. While on giving wrong email it is authenticating and giving error object.

Firebase auth().onAuthStateChanged not wait until auth().signInWithCredential finish

I have login code in react native using firebase and google signin auth.
So when new user sign in using google account, I set new data. And if user has signed in before, user go to main page.
My problem is when new user sign in > code start to get signInWithCredential > set new data user, before set data finish, onAuthStateChanged was detect there is change in auth and start to get user document / data. But because it's not finish yet, it throw error 'Can Not Get UID / Undefined UID'.
This is my login page code:
const _signIn = async () => {
setInitializing(true);
try {
await GoogleSignin.hasPlayServices();
const userInfo = await GoogleSignin.signIn();
const credential = auth.GoogleAuthProvider.credential(
userInfo.idToken,
userInfo.accessToken,
);
await auth()
.signInWithCredential(credential)
.then(response => {
const uid = response.user.uid;
const data = {
uid: uid,
email: userInfo.user.email,
fullname: userInfo.user.name,
bio: 'Halo!! ..',
username: uid.substring(0, 8),
};
const usersRef = firestore().collection('users');
usersRef
.doc(uid)
.get()
.then(firestoreDocument => {
if (!firestoreDocument.exists) {
usersRef
.doc(data.uid)
.set(data)
.then(() => {
setInitializing(false); return;
})
.catch(error => {
setInitializing(false);
Alert.alert(JSON.stringify(error.message));
});
} else {
setInitializing(false);
return;
}
})
.catch(error => {
Alert.alert(JSON.stringify(error.message));
console.log('Error getting document:', error);
return;
});
});
} catch (error) {
if (error.code === statusCodes.SIGN_IN_CANCELLED) {
setInitializing(false);
Alert.alert('Sign in canceled');
} else if (error.code === statusCodes.IN_PROGRESS) {
setInitializing(false);
Alert.alert('Signin in progress');
} else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
setInitializing(false);
Alert.alert('PLAY_SERVICES_NOT_AVAILABLE');
} else {
setInitializing(false);
Alert.alert(JSON.stringify(error.message));
}
}};
And this is my index page code to check auth user:
useEffect(() => {
try {
NetInfo.fetch().then(state => {
if(state.isConnected === false){
Alert.alert('No Internet Connection Detected');
setInitializing(false);
return;
}
});
setInitializing(true);
await auth().onAuthStateChanged(user => {
if (user) {
const usersRef = firestore().collection('users');
usersRef
.doc(user.uid)
.get()
.then(document => {
const userData = document.data().uid;
setisLogin(userData);
})
.then(() => {
setInitializing(false);
})
.catch(error => {
setInitializing(false);
Alert.alert(JSON.stringify(error.message));
});
} else {
setInitializing(false);
}
});
} catch (error) {
Alert.alert(error);
} }, []);
How to wait auth().signInWithCredential finish? Thankyou.
If you need to perform more actions such read data from database or so after the user logs in, you should ideally unsubscribe from onAuthStateChanged. Essentially it won't trigger when the auth state changes (i.e. user logs in) and let you do your own custom actions. Once your processing is done, then you manually redirect the user to where the onAuthStateChange would have redirected is the user wa s logged in.
const authStateListenter = await auth().onAuthStateChanged(user => {
//...
})
// Unsubscribe auth state observer when _signIn function runs
const _signIn = async () => {
setInitializing(true);
authStateListenter()
}
Calling authStateListener will disable the auth state observer. It's similar to detaching Firestore's listeners.

Firebase logouton page refresh in vue app

I am building a vue.js app using firebase for the backend. I've set up authentication and a route guard. I have also set the persistance of the session to firebase.persistance.LOCAL but, whenever I refresh the page, close the tab or browser and come back, I am being redirected to the login page.
This is my firebase config:
import * as firebase from "firebase";
var firebaseConfig = {
....
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
export const auth = firebase.auth();
export const firestore = firebase.firestore();
export const storage = firebase.storage();
This is how I log users in:
auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL)
.then(function() {
auth
.signInWithEmailAndPassword(self.email, self.password)
.then(function() {
self.$router.push("/management");
})
.catch(function(error) {
self.errors = error;
document.getElementById("signInLoader").style.display =
"none";
});
})
.catch(function(error) {
self.errors = error;
document.getElementById("signInLoader").style.display =
"none";
});
This is my route guard:
import { auth } from "#/firebase/firebase.js";
Vue.use(VueSpinners);
Vue.config.productionTip = false;
router.beforeEach((to, from, next) => {
const currentUser = auth.currentUser;
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
if (requiresAuth && !currentUser) {
next("/signin");
} else if (requiresAuth && currentUser) {
next();
} else {
next();
}
});
new Vue({
store,
router,
render: h => h(App)
}).$mount("#app");
I changed routeguard to watch for auth initialization and then check for currentUser.
router.beforeEach((to, from, next) => {
auth.onAuthStateChanged(function(user) {
const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
if (!requiresAuth) {
next()
} else if (requiresAuth && user) {
next()
} else {
next("/signin");
}
});
});

How can i return the login page after signing up new user using firebase and react native?

Iam building an App with a signup and login feature but can't get to the login page after signing up.
I have tried to use react navigation as below
handleSignUp = () => {
firebase
.auth()
.createUserWithEmailAndPassword(this.state.email, this.state.password)
.then(function() {
// Sign-out successful.
this.props.navigation.navigate("logn")
})
// .then(signout=>{
// })
.catch(error => this.setState({ errorMessage: error.message }));
};
This leads me to the home page.
Register screen movement below member registration section.
handleSignUp = async () => {
const result = await firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode == 'auth/weak-password') {
this.setState({ errorMessage: 'The password is too weak.' })
} else {
this.setState({ errorMessage: errorMessage })
}
});
if (result) {
this.props.navigation.navigate("logn")
}
}

firebase auth return null on signInWithPhoneNumber

I am trying to login with phone number with firebase signInWithPhoneNumber() method for login. In which i have checked whether user auth state has been change or not. If user auth is change then login and redirect to home page. but i m getting auth null
onLoginBtnClicked() {
const { contact, password } = this.props;
const error = Validator('password', password) || Validator('contact', contact);
if (error !== null) {
Alert.alert(error);
} else {
console.log('else');
// this.props.loginUser({ contact, password});
const mobileNo = '+91'+contact;
firebase.auth().signInWithPhoneNumber(mobileNo)
.then(data => console.log(data),
firebase.auth().onAuthStateChanged((user) => {
console.log('user'+user);
if (user && !CurrentUser.isFirstTimeUser) {
const userRef = firebase.database().ref(`/users/`);
userRef.on("value", (snapshot) => {
console.log(snapshot.val());
snapshot.forEach(function(item) {
var itemVal = item.val();
if(itemVal.mobile == contact){
NavigationService.navigate('Home');
}
});
}, (errorObject) => {
console.log("The read failed: " + errorObject.code);
});
//NavigationService.navigate('Home');
}
})
)
.catch(error => console(error.message) );
}
}
There are two things to note here
onAuthStateChanged is a listener which listen for the user auth changes.
signInWithPhoneNumber sends the code to the user's phone, you have to confirm it to authenticate the user.
You need to add the listener in the react lifecycle for the component once it is mounted and remove it when it is unmounted
componentDidMount() {
this.unsubscribe = firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.setState({ user: user.toJSON() });
} else {
// Reset the state since the user has been logged out
}
});
}
componentWillUnmount() {
if (this.unsubscribe) this.unsubscribe();
}
// Send Message here
firebase.auth().signInWithPhoneNumber(mobileNo)
.then(confirmResult => this.setState({ confirmResult })
.catch(error => // handle the error here)
// Authenticate User typed Code here
const { userCode, confirmResult } = this.state;
if (confirmResult && userCode.length > 0) {
confirmResult.confirm(codeInput)
.then((user) => {
// handle user confirmation here or in the listener
})
.catch(error => // handle the error here)
}

Resources