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")};
});
Related
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});
};
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}`);
Background: Login works perfectly, the data is organized like [![this][1]][1]
[1]: https://i.stack.imgur.com/f9Cjq.png
Anytime I log into one of the 2 accounts I made and go to the settings page, it only shows one specific user's info. Lastly, under the .collection("userInfo"), I added .doc(user.uid) and it said that the forEach function was invalid.
Here's the code. Can anyone tell me what I'm doing wrong?
var auth = firebase.auth().currentUser;
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
db = firebase.firestore()
db
.collection("userInfo")
.get()
.then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
// console.log(user.uid, " => ", doc.data());
console.log(user.uid)
var email = doc.data().email;
var bio = doc.data().bio;
var downloadURL = doc.data().downloadURL;
document.getElementById("email").placeholder = email;
document.getElementById("bio").placeholder = bio;
myimg.src = downloadURL;
}
})
var auth = firebase.auth().currentUser;
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
db = firebase.firestore();
db.collection("userInfo").doc(user.uid).get()
.then(function (doc) {
if(doc.exists) {
var email = doc.data().email;
var bio = doc.data().bio;
var downloadURL = doc.data().downloadURL;
document.getElementById("email").placeholder = email;
document.getElementById("bio").placeholder = bio;
myimg.src = downloadURL;
}
});
}
});
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!
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
});
});
});