Can't write firebase database, getting empty error - javascript

Been trying to write to my Firebase Realtime Database with something as simple as this in my react-native app:
newTips = () => {
firebase.database().ref('users/').set({
tips: "tips"
}).then((data)=>{
//success callback
console.log('data ' , data)
}).catch((error)=>{
//error callback
console.log('error ' , error)
})
}
But it is not writing and I am getting this yellow message in Expo. Any idea what the issue is? Auth works perfectly however.

Fixed this by chaning from Firebase Realtime to Firestore. Works perfectly.
newTips = () => {
let user = firebase.auth().currentUser;
let name, email, photoUrl, uid, emailVerified;
firebase.auth().onAuthStateChanged(user => {
if (user) {
email = user.email;
// User is signed in.
console.log('Logged in user: ' + email)
firestore.collection("tips").add({
user: user.email,
tips: "bla bla"
})
.then(function(docRef) {
console.log("Document written with ID: ", docRef.id);
})
.catch(function(error) {
console.error("Error adding document: ", error);
});
} else {
// User is signed out.
console.log('No user signed in')
}
})
}

Related

How to add a user to Firestore database after signing up through Firebase Authentication?

Upon sign up, I want to add a user to a "users" collection using the corresponding userID. Under this userID would be the user's data, such as name, email, posts, etc...
Here is my code:
I get no errors, and the user is created and is visible in firebase auth. However the user is not added to the firestore database.
firebase.initializeApp(config);
const auth = firebase.auth();
const db = firebase.firestore();
auth.createUserWithEmailAndPassword(email, pass).then(cred => {
const userId = cred.user.uid;
const userData = {
firstName: firstName,
lastName: lastName,
email: email
};
db.collection("users").doc(userId).set(userData).then(() => {
console.log("User successfully added to the DB!");
})
.catch((e) => {
console.log("Error adding user to the DB: ", e);
});
}).then(() => {
console.log('User created! - ' + email);
}).catch(e => {
console.log(e.message);
txtErrMsg.classList.remove('hide');
txtErrMsg.innerHTML = e.message;
});
It just seems like I am not able call the DB inside of the auth.createUserWithEmailAndPassword(email, pass) function. If I put the db.collection("users").doc(userId).set(userData) call with some dummy data outside of the auth.createUserWithEmailAndPassword(email, pass) function, then the data appears in the firestore DB.
FYI: I have console logged the parameters (userId and userData), and they appear as expected.

Getting "undefined" from error.email when trying to link multiple auth providers in firebase

I'm trying to link multiple auth providers to one account using firebase. The user is trying to create an account with the same address as the Google OAuth account which is already on firebase.
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then(async result => {
if (result.additionalUserInfo.isNewUser) {
firebase
.database()
.ref('/users/' + result.user.uid)
.set({
email: email,
profile_picture: image,
first_name: firstName,
last_name: lastName,
created_at: Date.now()
})
.then(snapshot => console.log("do something"))
} else {
firebase
.database()
.ref('/users/' + result.user.uid)
.update({
last_logged_in: Date.now()
})
.then(snapshot => console.log("do something"))
}
})
.catch(error => {
if (error.code === 'auth/email-already-in-use' || error.code === 'auth/credential-already-in-use' || error.code === 'auth/account-exists-with-different-credential') {
const pendingCred = error.credential
const email = error.email
firebase
.auth()
.fetchSignInMethodsForEmail(email)
.then(methods => {
switch (methods[0]) {
case 'password':
// email and password logic
break;
case 'facebook.com':
// facebook logic
break;
default:
break;
}
})
return;
}
})
The problem is I'm getting the proper error message:
[Error: The email address is already in use by another account.]
and the proper error.code:
auth/email-already-in-use
but, pendingCred or error.email come back undefined.
Update
I took the advise and tried the following:
firebase.auth()
.EmailAuthProvider
.credential(email, password)
.then(result => console.log("result", result))
.catch(error => console.log(error))
I'm getting the error:
[TypeError: undefined is not an object (evaluating '_firebase.default.auth().EmailAuthProvider.credential')]
You are using createuserwithEmailAndPassword which does not contain error.email or error.credential. According to the documentation to get the error you can either use error.message or error.code:
firebase.auth().createUserWithEmailAndPassword(email, password)
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
});
According to the documentation, the error.email and error.credential is used if you get the following error code:
auth/credential-already-in-use
auth/account-exists-with-different-credential
https://firebase.google.com/docs/reference/js/firebase.auth.Auth#error-codes_5
https://firebase.google.com/docs/reference/js/firebase.auth.Auth.html#sign-inwith-credential
The email was in error.customData.email for me.

Firebase Function/ Express: Can't set headers after they are sent

I've mostly utilised the Hapi framework to build RESTful APIs. For this project I'm using Express and I'm a bit lost as to why this is happening.
When I test the POST endpoint using Postman, the first request is fine, but I would get an error when I make the second request.
Error: Can't set headers after they are sent.
The code for the route handler is below:
const login = (req, res) => {
const validation = authScema.loginPayload.validate(req.body)
if (validation.error) {
return res.status(400).send(validation.error.details[0].message)
}
const { email, password } = req.body
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.catch(error => {
// Handle Errors here.
if (error) {
return res.status(400).send('Invalid login details.')
}
})
firebase.auth().onAuthStateChanged(user => {
if (user) {
const userObject = {
email: user.email,
uid: user.uid
}
const token = jwt.sign(userObject, secret)
return res.status(200).send(token)
}
})
}
I don't understand why headers are resent since in every branch, I return. It should have exited the function, right?
Turns out, signInWithEmailAndPassword
is a promise that returns the user in the happy path
So, the following is the final code:
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then(user => {
const userObject = {
email: user.email,
uid: user.uid
}
const token = jwt.sign(userObject, secret)
res.status(200).json({ token })
})
.catch(error => {
if (error) {
res.status(400).json({ message: 'Invalid login details.' })
}
})
The onOnAuthStateChanged is not necessary in this case.

React Native & Firebase : user info not being stored in database

I'm trying to create a new user and store their information in firebase database. I successfully create the user but the user information isn't getting stored in firebase.
The function that is running is handleAuthWithFirebase
The console.log("Storing user") is showing up in the console so I'm not sure why firebase.database().ref().set isn't running.
Here is my code
export function handleAuthWithFirebase (newUser) {
return function (dispatch, getState) {
dispatch(authenticating());
console.log(newUser);
console.log('Signing up user');
var email = newUser.email;
var password = newUser.password;
firebase.auth().createUserWithEmailAndPassword(email, password).catch(error => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
}).then(() => {
const user = firebase.auth().currentUser;
// Set user in Firebase
console.log("Storing user")
firebase.database().ref('/users/' + user.uid).set({
name: newUser.displayName,
username: newUser.username,
email: newUser.email
})
}).then(() => {
const user = firebase.auth().currentUser;
dispatch(isAuthed(user.uid))
})
}
}
The problem is that you're missing a child object, so you have to specify it after ref. It would be more helpful if you can post the tree of your database as well, but before try this and figure out yout child.
firebase.database().ref('myRef').child('myChild').set({
name: newUser.displayName,
username: newUser.username,
email: newUser.email
})
Here's what I got working, for those coming across this post.
firebaseApp.auth()
.createUserAndRetrieveDataWithEmailAndPassword(this.state.email, this.state.password)
.then(response => {
firebaseApp.database().ref('users').child(response.user.uid).set({
firstName: this.state.firstName,
lastName: this.state.lastName,
username: this.state.username,
email: this.state.email
});
response.user.sendEmailVerification().then(response => {
AlertIOS.alert('Message', 'Sending email verification to '+this.state.email)
});
this.setState({authenticating: false})
}, error => {
AlertIOS.alert('Error', error.message);
this.setState({authenticating: false})
})

parse-server js can't login user, even though registration goes through and logs user in

I'm currently building a parse-server app with vuejs + vuex on the front end.
I am able to register an account(and once registered the user is logged in) with this code:
REGISTER_USER (state, username, email, password) {
var user = new Parse.User()
user.set('username', username)
user.set('password', password)
user.set('email', email)
user.signUp(null, {
success: function (user) {
state.currentUser = user
},
error: function (user, error) {
state.registerError = error
}
})
}
but if I log the user out and try to log them in with:
LOGIN_USER (state, email, password) {
Parse.User.logIn(email, password, {
success: function (user) {
state.currentUser = user
},
error: function (user, error) {
state.loginError = error
console.log('error logging in: ' + JSON.stringify(error) + ' userobject: ' + JSON.stringify(user))
console.log('current user: ' + JSON.stringify(Parse.User.current()))
}
})
}
I get {"code":101,"error":"Invalid username/password."}
I've confirmed that the proper username and password is reaching the function, but then it goes south somehow. any help would be greatly appreciated.
Finally figured it out. There are 2 available methods for login, tried the other one and worked perfectly
https://parse.com/docs/js/api/classes/Parse.User.html#methods_logIn
var user = new Parse.User()
user.set('username', username)
user.set('password', password)
user.logIn({
success: function (user) {
this.username = ''
this.password = ''
dispatch('SET_CURRENT_USER', user)
},
error: function (user, error) {
// console.log('login errors: ' + JSON.stringify(error) + 'for user: ' + JSON.stringify(user))
// state.loginErrors = error
}
})

Categories