DisplayName not being set when using Firebase - javascript

I am trying to get Firebase to assign users a name based off of what they put into a field. However it appears that the name isnt being updated doesnt do anything.
btnSignUp.addEventListener('click', e => {
//Get Email and Password
const acEmail = email.value;
const acPass = password.value;
const acName = name.value;
const auth = firebase.auth();
//Sign Up
const promise = auth.createUserWithEmailAndPassword(acEmail, acPass);
promise.catch(e => console.log(e.message));
then(function(user) {
user.updateProfile({
displayName: acName
})
}).catch(function(error) {
console.log(error);
});
});
Any help is Appreciated!

Related

Using Firebase v9, how can I add the user to the user collection upon logging in with gmail?

How can I add a user to the users collection logging in with Gmail?
I tried the addUser but it does not work. I'm quite new to Firebase v9
//firebase
import { signInWithPopup, GoogleAuthProvider } from "firebase/auth";
import { auth, signInWithGoogle, db } from "../../Firebase/utils";
import { doc, setDoc, collection } from "firebase/firestore";
const Login = (props) => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const addUser = async () => {
const userRef = doc(db, "users", auth.currentUser);
setDoc(userRef);
};
useEffect(() => {
addUser();
}, []);
const googleHandler = async () => {
signInWithGoogle.setCustomParameters({ prompt: "select_account" });
signInWithPopup(auth, signInWithGoogle)
.then((result) => {
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info.
const user = result.user;
// redux action? --> dispatch({ type: SET_USER, user });
addUser();
console.log(auth.currentUser, "login page");
})
.catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
// ...
});
};
return (
<>
<form>
<Button onClick={googleHandler}>Login with Gmail</Button>
</form>
</>
);
};
export default Login;
These are my package.json just to be sure:
This is what the console.log(auth.currentUser) shows:
UPDATE:
const addUser = async (userId) => {
const userRef = doc(db, "users", userId);
return await setDoc(userRef, { ...data });
};
useEffect(() => {
addUser();
}, []);
const googleHandler = async () => {
signInWithGoogle.setCustomParameters({ prompt: "select_account" });
signInWithPopup(auth, signInWithGoogle)
.then(async (result) => {
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info.
const user = result.user;
// redux action? --> dispatch({ type: SET_USER, user });
// addUser();
const { isNewUser } = getAdditionalUserInfo(result);
if (isNewUser) {
await addUser(user.uid);
} else {
console.log("User already exists");
}
})
.catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
// ...
});
};
The doc() function takes Firestore instance as first argument and the rest are path segments (strings) so you cannot pass currentUser object there. Also there might be a chance that auth.currentUser. You can use isNewUser property to check if the user has just signed up or is logging in again and then add the document. Try refactoring the code as shown below:
signInWithPopup(auth, signInWithGoogle)
.then(async (result) => {
const user = result.user;
const { isNewUser } = getAdditionalUserInfo(result)
if (isNewUser) {
await addUser(user.uid);
} else {
console.log("User already exists")
}
})
const addUser = async (userId) => {
const userRef = doc(db, "users", userId);
return await setDoc(userRef, {...data});
};

How to get Twitter username from Firebase Authentication - Javascript

I'm using firebase twitter authentication for my project. The auth variable returning the credentials does not contain the account's twitter username but everything else.
I need to work with the username, is there a way to work around this?
Users shown in the console look like thisFirebase Console
How do I get the respective identifier of a uid?
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.2/firebase-app.js";
import { getAuth, signInWithPopup, TwitterAuthProvider } from "https://www.gstatic.com/firebasejs/9.1.2/firebase-auth.js";
const app = initializeApp(firebaseConfig);
const provider = new TwitterAuthProvider();
const auth = getAuth();
document.querySelector('button').addEventListener('click', authenticate);
function authenticate() {
signInWithPopup(auth, provider)
.then((result) => {
const credential = TwitterAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
const secret = credential.secret;
const user = result.user;
console.log(result)
}).catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
const email = error.email;
const credential = TwitterAuthProvider.credentialFromError(error);
console.log(error);
});
}
Is there a way to get the username from this 'auth' variable, check below code for ref
import { getAuth } from "https://www.gstatic.com/firebasejs/9.1.2/firebase-auth.js"
const auth = getAuth();
auth.onAuthStateChanged(user => {
if(user){
// window.location.href = "/home/index.html"
}else{
}
})
I think you mean Twitter handle (also called screen name) by "username"
const provider = new TwitterAuthProvider();
const userInfo = await signInWithPopup(auth, provider);
console.log(userInfo._tokenResponse.screenName) // twitter handle
Hello there you can try this:
firebase.auth().signInWithPopup(new firebase.auth.TwitterAuthProvider())
.then((userCredential) => {
// here you get the username
console.log(userCredential.additionalUserInfo.username);
})
.catch((error) => {
console.log("error occurred");
});
or else you can get the info using this if you are having id :
let url = `https://api.twitter.com/1.1/users/show.json?user_id=${the_uid_from_provider_data}`;
fetch(url)
.then(response => {
let data = response.json();
console.log(data);
})
.catch(error => {
// handle the error
});
For me it works like that
const res = await signInWithPopup(auth, provider);
const user = res.user;
const username = user.reloadUserInfo.screenName;
console.log(`username #${username}`);

How do I verify text in a Javascript if then function?

Im trying to write a script that says if you enter the word "dog" in the promo box, then an id will be created in firebase. I'm testing out my script and when I enter "dog" the script doesn't proceed to creating an id and I get the else pop up, "please enter a promo code."
/
/ Get elements
const txtEmail = document.getElementById('email');
const txtPassword = document.getElementById('password');
const btnLogin = document.getElementById('btnlogin');
const btnSignUp = document.getElementById('btnsignup');
const btnLogout = document.getElementById('btnsignout');
const txtPromo = document.getElementById('promo');
// Add login event
btnLogin.addEventListener('click', e => {
console.log("logged in");
// Get email and password
const email = txtEmail.value;
const password = txtPassword.value;
const auth = firebase.auth();
// Sign in
const promise = auth.signinwithemailandpassword(email,password);
promise.catch(e => console.log(e.message));
});
// Add signup event
btnSignUp.addEventListener('click', e => {
if (promo === "dog") {
alert ("Your account has been created. Please login.");
console.log("account created");
// Get email and password
const email = txtEmail.value;
const password = txtPassword.value;
const auth = firebase.auth();
console.log(email);
console.log(password);
//console.log(promo);//
auth.createUserWithEmailAndPassword(email, password)
.then((userCredential) => {
// Signed in
var user = userCredential.user;
console.log(user);
window.location.href = "login.html";
// ...
})
.catch((error) => {
//alert ("The email address is already in use by another account.");//
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorMessage);
// ..
});}
// Sign up
//const promise = auth.createuserwithemailandpassword(email,password);
//promise.catch(e => console.log(e.message));
else {alert ("Please enter a promo code."); console.log("need promo")};
});

Firebase writing data with variable via REST

in my app I am getting the uid of the current user by:
also I get the username from :
console.log gives me the right name.
But when I try to write to my db via:
https://movieapp-8a157.firebaseio.com/users/${username}/${authUser}/posts.json?auth=${token}
It doesnt work. If I remove the ${username} it will write in the correct path. Any ideas? I edited my post for more clearness.
export const postJob = data => {
return async (dispatch, getState) => {
const randomColors = ["#f3a683"];
const colorNumber = Math.floor(Math.random() * 20) + 1;
const bgColor = randomColors[colorNumber];
const val = getState();
const userId = val.auth.userId;
const rules = {
description: "required|min:2"
};
const messages = {
required: field => `${field} is required`,
"description.min": "job description is too short"
};
try {
await validateAll(data, rules, messages);
const token = await firebase
.auth()
.currentUser.getIdToken(true)
.then(function(idToken) {
return idToken;
});
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var providerData = user.providerData;
// ...
} else {
// User is signed out.
// ...
}
});
var user = firebase.auth().currentUser;
const authUser = user.uid;
const username = await firebase
.database()
.ref("users/" + authUser + "/name")
.once("value", function(snapshot) {
console.log("################", snapshot.val());
});
//console.log("#####################", authUser);
const response = await fetch(
`https://movieapp-8a157.firebaseio.com/users/${username}/${authUser}/posts.json?auth=${token}`,
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
titel: data.titel,
fname: data.fname,
description: data.description,
cover: data.cover,
friend: data.friend,
ownerId: userId,
bgColor: bgColor
})
}
);
const resData = await response.json();
Your code that's getting the UID isn't working the way you exepct. The auth state listener is asynchronous and is triggering after the line of code that accessesfirebase.auth().currentUser. That line of code is actually giving you the current user before the sign-in completes. That means it's going to be undefined.
You're then using that undefined value to build a reference to a location in the database. This is causing the actual reference to be something other than what you expect. You should add debug logging to see this yourself.
You should be using the callback to determine when exactly the user is signed in, and only read and write that user's location. This means that you should probably move the lines of code that write the database into the callback, when you know that user is correct, and use user.uid to build the database reference for reading and writing.

Firebase Cloud functions timeout

The following function works well when tested with shell, and data are created in firestore.
When pushed in prod, it returns Function execution took 60002 ms, finished with status: 'timeout'
Any input?
exports.synchronizeAzavista = functions.auth.user().onCreate(event => {
console.log('New User Created');
const user = event.data;
const email = user.email;
const uid = user.uid;
return admin.database().ref(`/delegates`)
.orderByChild(`email`)
.equalTo(email)
.once("child_added").then(snap => {
const fbUserRef = snap.key;
return admin.firestore().collection(`/users`).doc(`${fbUserRef}`).set({
email: email,
uid: uid
}).then(() => console.log("User Created"));
});
});
Edit
I've update my code with the following, but I still getting Function returned undefined, expected Promise or value but I can't identify where my function return undefined. Why my getUser() function does not return anything?
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.synchronizeAzavista = functions.auth.user().onCreate(event => {
console.log('New User Created');//This log
const user = event.data;
const email = user.email;
const uid = user.uid;
console.log('Const are set');//This log
getUser(email).then(snap => {
console.log("User Key is " + snap.key);//No log
const fbUserRef = snap.key;
return admin.firestore().collection(`/users`).doc(`${fbUserRef}`).set({
email: email,
uid: uid
});
}).then(() => console.log("User Data transferred in Firestore"));
});
function getUser(email) {
console.log("Start GetUser for " + email);//This log
const snapKey = admin.database().ref(`/delegates`).orderByChild(`email`).equalTo(email).once("child_added").then(snap => {
console.log(snap.key);//No Log here
return snap;
});
return snapKey;
}
You're not returning a promise from your write to Firestore.
exports.synchronizeAzavista = functions.auth.user().onCreate(event => {
const user = event.data;
const email = user.email;
const uid = user.uid;
return admin.database().ref(`/delegates`)
.orderByChild(`email`)
.equalTo(email)
.once("child_added").then(snap => {
const fbUserRef = snap.key;
return admin.firestore().collection(`/users`).doc(`${fbUserRef}`).set({
email: email,
uid: uid
});
});
});

Categories

Resources