Login button does not work for firebase auth - javascript

I'm a newbie at firebase.
I'm trying to code a simple login page where the user logs in and then is redirected to home.html.
This is my index page:
<html>
<body>
<script src="https://gstatic.com/firebasejs/live/3.1/firebase.js"></script>
<div class="container">
<input id="txtEmail" type="email" placeholder="Email">
<input id="txtPassword" type="password" placeholder="Password">
<button id="btnLogin" class="btn btn-action">Log in</button>
<button id="btnSignUp" class="btn btn-secondary">Sign Up</button>
<button id="btnLogout" class="btn btn-action hide">Log out</button>
</div>
<script src="app.js"></script>
</body>
</html>
And this is my app.js:
(function() {
// Initialize Firebase
const config = {
apiKey: "...",
authDomain: "fir-test-bb3bd.firebaseapp.com",
databaseURL: "https://fir-test-bb3bd.firebaseio.com",
projectId: "fir-test-bb3bd",
storageBucket: "fir-test-bb3bd.appspot.com",
messagingSenderId: "509522467811"
};
firebase.initializeApp(config);
// Get elements
const txtEmail = document.getElementById('txtEmail');
const txtPassword = document.getElementById('txtPassword');
const btnLogin = document.getElementById('btnLogin');
const btnSignUp = document.getElementById('btnSignUp');
const btnLogout = document.getElementById('btnLogout');
// Add login event
btnLogin.addEventListener('click', e => {
// Get email and pass
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(email, pass);
promise.catch(e => console.log(e.message));
});
// Handle Account Status
firebase.auth().onAuthStateChanged(user => {
if (user) {
window.location = 'home.html'; //After successful login, user will be redirected to home.html
// Add signup event
btnSignUp.addEventListener('click', e => {
// Get email and pass
// TODO: CHECK FOR REAL EMAIL
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
// Sign in
const promise = auth.CreateUserWithEmailAndPassword(email, pass);
promise.catch(e => console.log(e.message));
});
// Add a realtime listener
firebase.auth().onAuthStateChanged(firebaseUser => {
if (firebaseUser) {
console.log(firebaseUser);
} else {
console.log('not logged in');
}
});
}
});
});
When i go enter a valid username and password nothing happens, when I enter an invalid username and password nothing happens. When I check the console logs there is absolutely nothing even though it should be stating what is happening.
Any idea?
Thank you again for any help.
UPDATE 1
This is the new login bit...still same problem
//Add login event
btnLogin.addEventListener('click', e => {
//Get email and pass
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(email, pass);
{
promise.then(onResolve, onReject)
onResolve(e => console.log(e.message));
firebase.auth().onAuthStateChanged(user => {
if(user) }{
window.location = 'home.html';
}});

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 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")};
});

Why does my firebase cloud function run multiple times?

I have written a cloud function for firebase admin. It is to reset a user's password. It passes in the user UID and the new pass, but when I run the function, it not only resets that user's password, it makes that the password for every user. Every single user in the database.
Here is the code that calls the function:
resetForm.addEventListener('submit', (e) => {
e.preventDefault();
let newPass = resetForm['reset-password'].value;
const resetPasswordFunction = firebase.functions().httpsCallable('resetPassword');
resetPasswordFunction({docId: docId, newPass: newPass}).then(() => {
const modal = document.querySelector('#modal-reset');
M.Modal.getInstance(modal).close();
resetForm.reset();
});
});
and here is the function:
var functions = require('firebase-functions');
var admin = require("firebase-admin");
var serviceAccount = require("./troop-30-elections-web-app-firebase-adminsdk-obsmr-61cc4bb59e.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://troop-30-elections-web-app.firebaseio.com"
});
exports.resetPassword = functions.https.onCall((data) => {
return admin.auth().updateUser(data.docId, {
password: data.newPass
})
.then(() => {
return {"text": "User Password Successfully Updated"}; // this is what gets sent back to the app
});
});

DisplayName not being set when using Firebase

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!

.signInWithEmailandPassword is not a function

I was following this video from the Firebase Team to add Firebase Auth to my application (https://www.youtube.com/watch?v=-OKrloDzGpU)
I have added the web application script generated for my project in Firebase into the html section of my app and basically copied the other code to do the login and signing up as seen in the code below
But I got this error which I have no idea why its triggering
TypeError: auth.signInWithEmailandPassword is not a function. (In 'auth.signInWithEmailandPassword(email, pass)', 'auth.signInWithEmailandPassword' is undefined)
HTML Code
<!DOCTYPE html> <meta charset="utf-8" />
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/5.7.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.7.0/firebase-auth.js"></script>
<link rel="stylesheet" href="css/styles.css" />
</head>
<body>
<div class="container">
<input id="txtEmail" type="email" required placeholder="Email" />
<input id="txtPassword" type="password" required placeholder="Password" />
<button id="btnLogin" class="button-is-link">Login</button>
<button id="btnSignUp" class="button-is-info">Sign Up</button>
</div>
<script src="js/auth.js"></script>
</body>
</html>
Auth.js
(function() {
// Initialize Firebase
var config = {
apiKey: 'API KEY',
authDomain: 'DOMAIN',
databaseURL: 'DATABASE',
projectId: 'ID',
storageBucket: 'BUCKET',
messagingSenderId: 'ID'
};
firebase.initializeApp(config);
const txtEmail = document.getElementById('txtEmail');
const txtPassword = document.getElementById('txtPassword');
const btnLogin = document.getElementById('btnLogin');
const btnSignUp = document.getElementById('btnSignUp');
btnLogin.addEventListener('click', e => {
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
const promise = auth.signInWithEmailandPassword(email, pass);
promise.catch(e => console.log('e.message'));
});
btnSignUp.addEventListener('click', e => {
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
const promise = auth.createUserWithEmailandPassword(email, pass);
promise.catch(e => console.log('e.message'));
firebase.auth().onAuthStateChange(firebaseUser => {
if (firebaseUser) {
console.log('U are logged in');
} else {
console.log('Not logged in');
}
});
});
})();
The exact method name is signInWithEmailAndPassword, with an upper case "A" at And.
It is the same with createUserWithEmailAndPassword.
run given below command, Before execute make sure to delete "package-lock.json"
npm i #angular/fire#latest --save

Categories

Resources