How do I add data in firebase? - javascript

Well, I am creating a news feed website. Each user will be able to upload its own events. I am trying to create a section in my firebase database of the users, but I am not able of send variables to the arguments.
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(){
var user = firebase.auth().currentUser;
console.log(user);
if (user) {
// User is signed in.
user.updateProfile({displayName: document.getElementById("name").value});
var user_id = user.id;
var user_email = user.email;
var user_display_name = user.displayName;
//Saving info in the data base.
var database = firebase.database();
database.ref('users/' + user_id).set({
displayName: user_display_name,
id: user_id,
email: user_email
});
window.location = "index.html"
} else {
alert("Something went wrong.");
}
UPDATED VERSION:
window.onload = function(){
var createButton = document.getElementById("createButton");
var signin_button = document.getElementById("signin_button");
createButton.onclick = function(){
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(result){
console.log('result', result);
if (result) {
// User is signed in.
result.updateProfile({displayName: document.getElementById("name").value});
var user_info = {id: result.uid, email: result.email, display_name: result.displayName};
console.log('user_info', user_info);
// Storing user info into database.
var database = firebase.database();
console.log('user id', user_info.id);
database.ref().child('usersss/' + user_info.id).push({
displayName: user_info.display_name,
id: user_info.id,
email: user_info.email
});
window.location = "index.html"
} else {
alert("Something went wrong.");
}
})
.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 if (errorCode == 'auth/email-already-in-use') {
alert('The email is already in use.');
} else if (errorCode == 'auth/invalid-email') {
alert('The email is not valid.');
}else if (errorCode == 'auth/operation-not-allowed') {
alert('This operation is not allowed.');
}else{
alert(errorMessage);
}
console.log(error);
})
}
signin_button.onclick = function(){
window.location = "login.html";
}
}

If nothing exists at 'users/' + user_id you need to use 'push' instead of 'set'. For example:
database.ref().child('/users/' + user_id).push({
//your code
try that.
Here's an action generator I use to log a user into firebase:
export var startLoginWithEmailAndPassword = (email, password) => {
firebase.auth().signInWithEmailAndPassword(email, password).then((result) => {
//handle success
console.log('worked', result);
}).catch((error) => {
//handle error
console.log('error', error);
});
}
In the above case, the 'result' object will have the user details.

Related

Trying to put data in database but get error "firebase is not defined"

I'm trying to make a basic login/signup system with firebase. So far I've been able to fix all the other bugs. The program first creates a user with Firebase Authentication then puts the user data in the Firebase Database. I've managed to get the Authentication working but the database part just makes firebase spit out, "firebase is not defined".
Here's the code:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-app.js";
import { getAuth, createUserWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-auth.js";
import { getDatabase } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-database.js";
const firebaseConfig = {
apiKey: "AIzaSyCQjuF9A4Km_M7Eo5gnd1B6nmDRRYSle2c",
authDomain: "badge-world.firebaseapp.com",
projectId: "badge-world",
storageBucket: "badge-world.appspot.com",
messagingSenderId: "186421361260",
appId: "1:186421361260:web:852bcaa237f86a76b1f649"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const database = getDatabase(app);
document.getElementById ("signup-button").addEventListener("click", register);
document.getElementById ("login-button").addEventListener("click", login);
function register() {
let email = document.getElementById('email').value
let password = document.getElementById('password').value
let username = document.getElementById('username').value
if (validate_email(email) == false || validate_password(password) == false) {
alert("Incorrect Fields. Remember password has to have more than 6 characters and there must be a valid email.")
}
if(validate_field(username) == false) {
alert("Username missing")
}
createUserWithEmailAndPassword(auth, email, password)
.then(function (){
var user = auth.currentUser
var rootRef = firebase.database().ref();
var user_data = {
email : email,
password : password,
username: username,
last_login : Date.now
}
rootRef.child('users/' + user.uid).set(user_data)
alert("User Created!")
})
.catch(function(error) {
var error_code = error.code
var error_message = error.message
alert(error_message)
})
}
function login() {
}
// Validate Functions
function validate_email(email) {
let expression = /^[^#]+#\w+(\.\w+)+\w$/
if (expression.test(email) == true) {
// Email is good
return true
} else {
// Email is not good
return false
}
}
function validate_password(password) {
// Firebase only accepts lengths greater than 6
if (password < 6) {
return false
} else {
return true
}
}
function validate_field(field) {
if (field == null) {
return false
}
if (field.length <= 0) {
return false
} else {
return true
}
}
and here's the database part that seems to be causing the issue:
.then(function (){
var user = auth.currentUser
var rootRef = firebase.database().ref();
var user_data = {
email : email,
password : password,
username: username,
last_login : Date.now
}
rootRef.child('users/' + user.uid).set(user_data)
alert("User Created!")
})
.catch(function(error) {
var error_code = error.code
var error_message = error.message
alert(error_message)
})
Any help is appreciated!
You are using Firebase Modular SDK that uses a functional syntax and not the firebase. namespaced one. The problem is this line:
var rootRef = firebase.database().ref();
There is a top level function ref() to get a DatabaseReference now. Try refactoring the code as shown below:
import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-database.js";
// declared while initializing
const database = getDatabase(app)
set(ref(database, 'users/' + user.uid), user_data)
.then(() => {
console.log("data added")
})
.catch((e) => console.log(e))
The documentation has examples of both the syntaxes so make sure you are referring to modular tab.

Firebase Auth returning undefined for createUserWithEmailAndPassword

I have a function that creates a new user through Firebase Auth, and for awhile I had it working but now it's returning undefined. I tried using async await to wait for an input with no help, and I'm not really sure what could be going wrong. I can't include my Firebase auth code on here, but I put the rest of the code on CodePen:
https://codepen.io/TheNomadicAspie/pen/ZEKYwWJ
And here are the relevant function:
function newUserSubmitEmail() {
traceFunction()
new_user_dict['email'] = input_text.value.trim()
console.log('newUserSubmitEmail email is ', new_user_dict['email'])
question.innerText = "What password would you like to use?"
input_text.value = ''
right_button.onclick = newUserSubmitPassword
}
function newUserSubmitPassword() {
traceFunction()
new_user_dict['password'] = input_text.value.trim()
console.log('newUserSubmitPassword password is ', new_user_dict['password'])
question.innerText = "Ok, and enter it one more time just to make sure there's no typos."
input_text.value = ''
right_button.onclick = newUserVerifyPassword
}
function newUserVerifyPassword() {
traceFunction()
if (new_user_dict['password'] === input_text.value) {
newUserSubmitEmailAndPassword()
} else {
question.innerText = "Those passwords didn't match. Let's try again."
console.log('newUserVerifyPassword old password was ', new_user_dict['password'], ' new password is ', input_text.value)
input_text.value = ''
right_button.onclick = newUserSubmitPassword
}
}
async function newUserSubmitEmailAndPassword() {
traceFunction()
console.log('newUserSubmitEmailAndPassword email is ', new_user_dict['email'], ' password is ', new_user_dict['password'])
input_text.value = ''
firebase.auth().createUserWithEmailAndPassword(await new_user_dict['email'], await new_user_dict['password']).then((userCredential) => {
console.log('newUserSubmitEmailAndPassword User created successfully')
userCreatedSuccessfully()
})
.catch(async (error) => {
var errorCode = await error.code
var errorMessage = error.message
question.innerText = errorCode
console.log('newUserSubmitEmailAndPassword Error creating user. Error code: ', errorCode, ' ', errorMessage)
if (errorCode === 'auth/email-already-in-use') {
newUserEmailInUse()
} else if (errorCode === 'auth/invalid-email') {
newUserTryEmailAgain()
} else if (errorCode === 'auth/operation-not-allowed') {
errorPleaseRefresh()
} else if (errorCode === 'auth/weak-password') {
newUserTryPasswordAgain()
}
})
}
Any ideas?
Maybe it's because you use the await in the wrong place. The code is written with async/await like this:
try {
const userCredentials = await firebase
.auth()
.createUserWithEmailAndPassword(
new_user_dict["email"],
new_user_dict["password"]
);
console.log(
"newUserSubmitEmailAndPassword User created successfully",
userCredentials.user
);
// comment out this
//userCreatedSuccessfully();
} catch (error) {
var errorCode = await error.code;
var errorMessage = error.message;
question.innerText = errorCode;
console.log(
"newUserSubmitEmailAndPassword Error creating user. Error code: ",
errorCode,
" ",
errorMessage
);
if (errorCode === "auth/email-already-in-use") {
newUserEmailInUse();
} else if (errorCode === "auth/invalid-email") {
newUserTryEmailAgain();
} else if (errorCode === "auth/operation-not-allowed") {
errorPleaseRefresh();
} else if (errorCode === "auth/weak-password") {
newUserTryPasswordAgain();
}
}

Issue in signup and redirecting to home page using firebase and js

when i am siging up my code is redirecting me to homepage but the data is not getting stored in realtime database.
function SignUp(){
var name = document.getElementById("fname").value;
var email = document.getElementById("email").value;
var phone = document.getElementById("phone").value;
var password = document.getElementById("password").value;
var password2 = document.getElementById("password2").value;
if(password == password2) {
auth.createUserWithEmailAndPassword(email, password).then((res) => {
database.ref('User/'+auth.currentUser.uid).set({
name: name,
phone:phone,
password: password2,
});
}).catch((error) => {
console.log(error);
alert(error.message);
});
}
else{
alert("password didnt match");
document.querySelector('.form_container').reset();
}
window.location.href = "index.html";
}
This is redirecting me to my home page.But the data is not getting stored into the real-time database.
Thanks in advance.
const auth = firebase.auth();
var database = firebase.database();
function SignUp(){
var name = document.getElementById("fname").value;
var email = document.getElementById("email").value;
var phone = document.getElementById("phone").value;
var password = document.getElementById("password").value;
var password2 = document.getElementById("password2").value;
if(password == password2) {
auth.createUserWithEmailAndPassword(email, password).then((res) => {
database.ref('User/'+auth.currentUser.uid).set({
email:email,
name: name,
phone:phone,
password: password2,
});
document.getElementById('success').style.display='block';
}).catch((error) => {
console.log(error);
alert(error.message);
});
}
else{
alert("password didnt match");
document.querySelector('.form_container').reset();
}
}
function success(){
window.location.href = "../index.html";
}
In the signup form
<div class="success_container" id="success">
<div class="animate success">
<p>successfully signed up</p>
<button type="button" onclick="success()">back to site</button>
</div>
</div>
Add this code and that lets your job done.
Thanks

Firebase Firestore custom ID not creating new document after creating user properly

I created a sample registration form in my Vue App to automatically create a Firestore document with the User UID attached to it with a custom document ID.
The user gets created successfully but the document doesn't get created and doesn't display any error on the console even after using the catch() error method.
register() {
//Generate pin
function generateQuickGuid() {
return Math.random()
.toString(36)
.substring(2, 15);
}
let ref = fs.doc(generateQuickGuid());
ref.get().then(doc => {
if (doc.exists) {
console.log("Pin Exists");
} else {
console.log("pin doesnt exists");
// then add user to firestore
if (
this.email &&
this.password &&
this.displayName &&
this.category
) {
auth
.createUserWithEmailAndPassword(this.email, this.password)
.then(cred => {
ref
.set({
Name: this.displayName,
address: "close to understanding, firebase, auth",
phone: "09808763987",
category: this.category,
alias: pin,
user_id: cred.user.uid
})
.catch(e => {
console.log(e);
});
console.log("User Added");
})
.catch(error => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
console.log(errorCode, errorMessage);
});
}
}
});
}
register() {
//Generate pin
function generateQuickGuid() {
return Math.random()
.toString(36)
.substring(2, 15);
}
let ref = fs.doc(generateQuickGuid());
ref.get().then(doc => {
if (doc.exists) {
console.log("Pin Exists");
} else {
console.log("pin doesnt exists");
// then add user to firestore
if (
this.email &&
this.password &&
this.displayName &&
this.category
) {
AuthResult authResult = auth
.createUserWithEmailAndPassword(this.email, this.password)
.catch(error => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
console.log(errorCode, errorMessage);
});
ref.set({
Name: this.displayName,
address: "close to understanding, firebase, auth",
phone: "09808763987",
category: this.category,
alias: pin,
user_id: authResult.getUser().getUid()
})
.catch(e => {
console.log(e);
});
}
}
});
}
Try this

Google Firebase Authentication with Expo not returning anything

I am Creating an expo app in which a user can login using Gmail.
I followed this firebase documentation to implement that functionality but whenever I click on login, it doesn't neither save the data in the database nor return any error.
This is my firebase function:
isUserEqual = (googleUser, firebaseUser)=> {
if (firebaseUser) {
var providerData = firebaseUser.providerData;
for (var i = 0; i < providerData.length; i++) {
if (providerData[i].providerId === firebase.auth.GoogleAuthProvider.PROVIDER_ID &&
providerData[i].uid === googleUser.getBasicProfile().getId()) {
// We don't need to reauth the Firebase connection.
return true;
}
}
}
return false;
}
onSignIn = (googleUser)=> {
console.log('Google Auth Response', googleUser);
// We need to register an Observer on Firebase Auth to make sure auth is initialized.
var unsubscribe = firebase
.auth()
.onAuthStateChanged(function(firebaseUser) {
unsubscribe();
// Check if we are already signed-in Firebase with the correct user.
if (!this.isUserEqual(googleUser, firebaseUser)) {
// Build Firebase credential with the Google ID token.
var credential = firebase.auth.GoogleAuthProvider.credential(
googleUser.idToken,
googleUser.accessToken
);
// Sign in with credential from the Google user.
firebase.auth()
.signInAndRetrieveDataWithCredential(credential)
.then(function(result) {
console.log('User signed in');
})
.catch(function(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;
// ...
});
} else {
console.log('User already signed-in Firebase.');
}
}.bind(this)
);
};
signInWithGoogleAsync = async() => {
try {
const result = await Expo.Google.logInAsync({
behavior: 'web',
androidClientId: '929952027781-5ao9pp7n5n0sj2n70i5tp7klfro88bgp.apps.googleusercontent.com',
iosClientId: '929952027781-7obs66o3kr59kdhp6ll0c9598ue3u8aa.apps.googleusercontent.com',
scopes: ['profile', 'email'],
});
if (result.type === 'success') {
this.onSignIn(result);
return result.accessToken;
} else {
return {cancelled: true};
}
} catch(e) {
return {error: true};
}
}
And this is my login button:
<TouchableOpacity style={styles.AuthOptionGmail} onPress={() => signInWithGoogleAsync()}>
<Ionicons color='#ffffff' style = {styles.BtnIcon} name="logo-google" size={25}/>
<Text style={{fontSize:16,color:'#ffffff', textAlign:'center'}}>Login with Gmail</Text>
</TouchableOpacity>
Can anyone tell me where I messed up please????
with Expo sdk 32 and above following worked for me , just install "expo-google-app-auth"
import * as Google from "expo-google-app-auth";
signInWithGoogleAsync = async () => {
console.log("signInWithGoogleAsync");
try {
//clientId
const { type, accessToken, user, idToken } = await Google.logInAsync({
behavior: "web",
androidClientId:
"your id",
iosClientId:
"your id",
scopes: ["profile", "email"]
});
if (type === "success") {
console.log("accessToken" + accessToken);
console.log("idToken" + idToken);
console.log(user);
return accessToken;
} else {
return { cancelled: true };
}
} catch (e) {
console.log(e);
return { error: true };
}
};

Categories