Cannot register user info to firebase database when creating a new user - javascript

I am working on a signup form and I can create a new user using firebase auth, but the part where I register informations like the name, email... in a database is not working.
On the firebase side, I created a firestore database and a realtime database, and I don't see anything on them.
I tried to use the firebase documentation but it's still not working so I am probably missing something.
Thanks for your help!
PS: I hidded my firebase config here but it's filled on my code
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js'
import { getAuth, createUserWithEmailAndPassword } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js'
import { getFirestore, doc, getDoc, getDocs, collection } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-firestore.js";
import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-database.js";
const firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
const app = initializeApp(firebaseConfig);
//const db = getFirestore();
const auth = getAuth();
const db = getDatabase();
submitData.addEventListener('click', (e) => {
e.preventDefault()
var name = document.getElementById('full_name').value
var email = document.getElementById('email').value;
var password = document.getElementById('psw').value;
// do verification
// Move on with Auth
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user
alert("user created")
//add to firebase database
function writeUserData( name, email) {
set(ref(db, 'users/' + userId), {
username: name,
email: email,
});
}
})

Related

Firebase firestore not working react native

I have a react native project configured with firebase and the firestore db is not working. It doesnt show any errors either.
Here is my firebase config file:
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth'
import 'firebase/compat/firestore';
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "",
databaseURL: "",
};
let app;
if (firebase.apps.length === 0) {
app = firebase.initializeApp(firebaseConfig);
app.firestore().settings({ experimentalForceLongPolling: true });
} else {
app = firebase.app();
app.firestore().settings({ experimentalForceLongPolling: true });
}
const db = app.firestore();
const auth = app.auth();
export {db, auth }
Here is my code that i use to authenticate user than save it to firestore:
const signup = dispatch => async (email, password) => {
try {
await auth.createUserWithEmailAndPassword(email, password).then(async resp => {
});
await db.collection('users').add({
email: 'asdas',
uid: 'asdsda',
coins: 0,
}).catch(error => {
console.log(error);
});
} catch (error) {
console.log(error);
alert(error.message);
}
};
Firestore rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read,write: if
request.time < timestamp.date(2022, 9, 21);
}
}
}
The authentication part works perfectly but the firestore code doesnt execute. Any idea why this is happening?

firebase + next dont save data in realtime database

Hello i have big problem, the firebase realtime database dont save data
for example
const createUserProfile = (email,user,username) => {
console.log(email);
console.log(user)
const db = getDatabase();
console.log(db)
const dbRef = ref(db, 'users/' + user.uid);
set(dbRef, {
username,
email,
createDate: getDate()
});
};
In realtime conf i have write true and read true
what i can do? its next js
all data is okay,
console.log(db) response is
and realtime database dont update
This is probably because you don't pass the Firebase app instance to the getDatabase() method.
See here in the doc that you need to do
import { initializeApp } from 'firebase/app';
import { getDatabase } from "firebase/database";
// TODO: Replace with your app's Firebase project configuration
const firebaseConfig = {
apiKey: "API_KEY",
authDomain: "PROJECT_ID.firebaseapp.com",
// The value of `databaseURL` depends on the location of the database
databaseURL: "https://DATABASE_NAME.firebaseio.com",
// ...
};
const app = initializeApp(firebaseConfig);
// Get a reference to the database service
const db = getDatabase(app); // <= See how we pass the app object

how can i login with facebook account?

i wanted to create a login with facebook button, so i created this code:
import { getAuth, signOut,
onAuthStateChanged, FacebookAuthProvider, signInWithPopup } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-auth.js";
const firebaseConfig = {
apiKey: "AIzaSyC3GLIN5TBmCDoTfy0dEOgOdvVvqNw-ric",
authDomain: "auth-project-38aaa.firebaseapp.com",
projectId: "auth-project-38aaa",
storageBucket: "auth-project-38aaa.appspot.com",
messagingSenderId: "431888894254",
appId: "1:431888894254:web:71bb9b250fbb8a21edd2bf",
measurementId: "G-6BBPCJ3814"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
// login with facebook
const facebookProvider = new FacebookAuthProvider();
const signInWithFacebook = document.querySelector('#facebook-icon');
signInWithFacebook.addEventListener('click', (e) => {
e.preventDefault();
signInWithPopup(auth, facebookProvider).then((result) => {
const user = result.user;
const credential = FacebookAuthProvider.credentialFromResult(result);
const accessToken = credential.accessToken;
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
const email = error.email;
const credential = FacebookAuthProvider.credentialFromError(error);
});
});
when i try to login with facebook it gives me this error message:
Facebook has detected that firebase sign in isn't using a secure connection to transfer information.
can you help to solve this problem, please?
For these tests you must run them with an SSL connection, if you are testing on localhost you are probably not using SSL.

uid not getting saved in firebase database

import React from 'react'
import firebase from 'firebase';
const config = {
apiKey: "***",
authDomain: "***",
databaseURL: "***",
projectId: "***",
storageBucket: "***",
messagingSenderId: "***",
appId: "***",
measurementId: "***"
};
const fire = firebase.initializeApp(config);
export default class SignUp extends React.Component {
state = { email: '', password: '', userName: '', errorMessage: null };
constructor(props) {
super(props);
}
handleSignUp = () => {
const { userName, email, password } = this.state;
firebase.
auth()
.createUserWithEmailAndPassword(this.state.email, this.state.password)
.then(authUser => {
this.props.fire.database().ref('/users/')
.child(authUser.user.uid)
.set({
userName,
email,
});
})
.then(() => this.props.navigation.navigate('message'))
.catch(error => this.setState({ errorMessage: error.message }))
}
}
my db is not getting updated with username and email.
1.New with database handling and react so mostly
must be using database functions incorrectly
2.Please check handlesignup function
3.Data of firebase authentication is getting update properly
uid and user mail are displayed properly
4.part where uid is saved which is not working
.then(authUser => {
this.props.fire.database().ref('/users/')
.child(authUser.user.uid)
.set({
userName,
email,
});
})
If you do
firebase.auth()
you should similarly do
firebase.database().ref('/users/')
.child(authUser.user.uid)
.set({...})
since firebase is "a global namespace from which all Firebase services are accessed", see https://firebase.google.com/docs/reference/js/firebase

Could not link another auth method - firebase auth

I am signing in user using mobile number and then i want him to enter email and password later. (after logging in)
I am trying to link email,password Auth method to current PhoneAuth method.
But it's giving me an error:
Cannot read property 'link' of undefined
Here is code:
import { firebaseAuth,fire, messaging } from '../../config/constants';
var credential = fire.auth.EmailAuthProvider.credential(email, password);
fire.auth.currentUser.link(credential).then(function(user) {
console.log("Account linking success", user);
}, function(error) {
console.log("Account linking error", error);
});
And in config/constants
import firebase from 'firebase'
require("firebase/firestore");
const config = {
apiKey: "AIzxxxxxxxxxxxxxxxxxxKXI",
authDomain: "payxxxxxxxxxxxxja1.firebaseapp.com",
databaseURL: "https://payxxxxxxxxxxja1.firebaseio.com",
projectId: "payxxxxxxxxxxxxja1",
storageBucket: "payxxxxxxxxxxxja1.appspot.com",
messagingSenderId: "281xxxxx5xxxxx6"
}
firebase.initializeApp(config)
export const fire = firebase
export const ref = firebase.database().ref()
export const firebaseAuth = firebase.auth
export const messaging = firebase.messaging();
I think something is wrong with fire.auth or fire.auth()
Thanks
link has been removed in favor of linkWithCredential starting with Firebase JS version 4.0.0: https://firebase.google.com/support/release-notes/js#4.0.0
Also make sure the current user is ready:
firebase.auth().onAuthStateChange(user => {
if (user) {
// currentUser is not null.
} else {
// currentUser is null.
}
});

Categories

Resources