firebase login authentication gives me that email must be a valid string - javascript

It always gives me "first argument (email) must be a valid string" and it doesn't login
i don't know if the problem is in the js code but im pretty sure it's not in the html .
and another question .. do i need the " onAuthStateChanged " function?
<script>
var rightAccount = 0;
var email = $("#inputEmail").val();
var password = $("#inputPassword").val();
SignIn();
function SignIn(email,password) {
firebase.auth().signInWithEmailAndPassword(email, password)
.then((user) => {
authStateListener();
rightAccount = 1;
//Signed in
// ...
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorMessage);
alert(errorMessage);
});
};
function authStateListener() {
// [START auth_state_listener]
firebase.auth().onAuthStateChanged((user) => {
if (user) {
var uid = user.uid;
currentUser = user;
console.log(currentUser.email + " has logged in")
} else {
// ...
}
});
// [END auth_state_listener]
};
if (rightAccount == 1) {
setTimeout(function Redirect() {
window.location.replace("Website/homePage.php");
}, 2000)
}
</script>

You must pass email and password values to function. Otherwise it will be give error.
...
var email = $("#inputEmail").val();
var password = $("#inputPassword").val();
SignIn(email, password); // <-- Here pass them
...

Related

Firebase still isn't saving user info to firestore after auth

I found a tutorial on how to save the user's data under the uid in firestore. My function successfully retrieves the data and authenticates it, but it skips the firestore save function and jumps to the next window. I have two questions, why is it skipping the store in firebase function and why isn't reading the newly authenticated user as the current user when I set it and go to the next window? Sorry for all the similar questions, I'm trying different ways to do this and none have worked for me so far. I have provided my code below.
JS:
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Initialize variables
const auth = firebase.auth();
const db = firebase.firestore().collection("/studiopick/studios/users");
const element = document.querySelector("form");
element.addEventListener("submit", (event) => {
event.preventDefault();
// renamed from newStudio
// don't use alert - it blocks the thread
console.log("debug: retrieving data... please wait");
// Get data
(studioName = document.getElementById("studioName").value),
(email = document.getElementById("email").value),
(password = document.getElementById("password").value),
(firstName = document.getElementById("firstName").value),
(lastName = document.getElementById("lastName").value),
(phoneNumber = document.getElementById("phoneNumber").value);
console.log({ studioName, firstName, email }); // note added braces here
// Validate input fields
if (!validate_email(email) || !validate_password(password)) {
// TODO: replace this alert with updating the form with an error message
alert("Error with email or password");
return false; // cancel submission
}
if (
!validate_field(firstName) ||
!validate_field(lastName) ||
!validate_field(phoneNumber) ||
!validate_field(studioName)
) {
// TODO: replace this alert with updating the form with an error message
alert("One or More Extra Fields is Outta Line!!");
return false; // cancel submission
}
console.log("Info grab successful");
// creates the user, and waits for it to finish being created
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then(function (userCredential) {
usersRef.doc(`${userCredential.user.uid}`).set({
studioName: studioName,
firstName: firstName,
lastName: lastName,
email: email,
phoneNumber: phoneNumber,
uid: userCredential.user.uid,
});
})
.catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode == "auth/weak-password") {
alert("The password is too weak.");
} else {
alert(errorMessage);
}
console.log(error);
// [END_EXCLUDE]
});
const uid = firebase.auth().currentUser;
// once the above tasks succeed, navigate to the dashboard.
window.location.href = "studiodash.html?id=" + uid;
return false;
});
// Validate Functions
function validate_email(email) {
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;
}
}
Ended up figuring it out myself. Hope this helps someone:
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
console.log("firebase ===", firebase);
// Initialize variables
const auth = firebase.auth();
const db = firebase.firestore().collection("/studiopick/studios/users");
const element = document.querySelector("form");
element.addEventListener("submit", (event) => {
event.preventDefault();
// renamed from newStudio
// don't use alert - it blocks the thread
console.log("debug: retrieving data... please wait");
// Get data
(studioName = document.getElementById("studioName").value),
(email = document.getElementById("email").value),
(password = document.getElementById("password").value),
(firstName = document.getElementById("firstName").value),
(lastName = document.getElementById("lastName").value),
(phoneNumber = document.getElementById("phoneNumber").value);
console.log({ studioName, firstName, email }); // note added braces here
// Validate input fields
if (!validate_email(email) || !validate_password(password)) {
// TODO: replace this alert with updating the form with an error message
alert("Error with email or password");
return false; // cancel submission
}
if (
!validate_field(firstName) ||
!validate_field(lastName) ||
!validate_field(phoneNumber) ||
!validate_field(studioName)
) {
// TODO: replace this alert with updating the form with an error message
alert("One or More Extra Fields is Outta Line!!");
return false; // cancel submission
}
console.log("Info grab successful");
// creates the user, and waits for it to finish being created
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then(async (userCredential) => {
console.log("userCredential ===", userCredential);
var usersRef = db;
await usersRef.doc(`${userCredential.user.uid}`).set({
studioName: studioName,
firstName: firstName,
lastName: lastName,
email: email,
phoneNumber: phoneNumber,
uid: userCredential.user.uid,
});
console.log("firebase.auth().currentUser ===", firebase.auth().currentUser.uid);
const uid = firebase.auth().currentUser.uid;
// once the above tasks succeed, navigate to the dashboard.
window.location.href = "studiodash.html?id=" + uid;
})
.catch((error) => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode == "auth/weak-password") {
alert("The password is too weak.");
} else {
alert(errorMessage);
}
console.log(error);
// [END_EXCLUDE]
});
return false;
});
// Validate Functions
function validate_email(email) {
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;
}
}

How to write test cases in Jest for login page

The following code is what I have written in order for the Admin to log in to the system. I am now trying to carry out unit testing and have to test the ValidateLogin for admin in particular. I have chosen jest to do that.
I created a test file:
const LoginController = reqire('./LoginController')
test('login to the system', () => {
expect(true).toBe(true);
})
Instead of checking for true to be true. I want to check for the username and password to be true. Please explain how should I do it.
Following is the code for login:
class User {
username;
password;
email;
firstName;
lastName;
roleName;
constructor(username,password,email,firstName, lastName, roleName){
this.username = username;
this.password = password;
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
this.roleName = roleName;
}
getlogininfo(username, password, callback) {
var sql = "SELECT * FROM User Where username = '" + username +
"' AND password = '" + password + "'";
var Username;
var dataRes;
con.query(sql, function(err, results){
if (err){
throw err;
}
if(results.length>0) { //result is not empty
Username = results[0].username; // Scope is larger than function
dataRes = {
username: results[0].username,
firstName: results[0].firstName,
lastName: results[0].lastName,
roleName: results[0].roleName
}
return callback(dataRes);
} else {
return callback(false);
}
})
}
}
exports.User = User
class LoginController {
ValidateLogin(req, res) {
let user = new User();
var dataRes;
var username = req.body.username
var password = req.body.password
console.log(username + "kekw" + password);
user.getlogininfo(username, password, function(result){
if(result) {
dataRes = result;
var session;
// Login endpoint
if(dataRes.roleName == "useradmin") {
console.log("Call User Admin Dashboard");
res.redirect("/UserAdmin");
}
else if(dataRes.roleName == "manager") {
console.log("Call Manager Dashboard");
res.redirect("/Manager");
}
else if(dataRes.roleName == "staff") {
console.log("Called Staff Dashboard");
res.redirect('/Staff');
}
else if(dataRes.roleName == "customer") {
console.log("Called Customer Dashboard");
res.redirect('/Customer');
}
/*
else if(dataRes.role == "Pharmacist") {
console.log("Called Pharmacist home");
res.redirect('/PharmacistHome');
}
else if(dataRes.role == "Patient") {
console.log("Called Patient home");
res.redirect('/PatientHome');
}*/
}
else {
req.flash('message', 'Wrong Username or Password!')
res.redirect("/?error=true");
return false;
}
});
}
}
//module.exports = LoginController;
exports.LoginController = LoginController;
I want to write test cases for username and password for the useradmin login. How do I do so? Thanks.
Could you please send your complete error code? It would be very helpful to get a solution. Although i think it could be an error with ES6 modules. Check if you have "type": "module" in your package.json. If that's the case you have to import your LoginController with import * from './LoginController'
You wrote „require“ wrong:
Like this: const LoginController = reqire('./LoginController');

Reference.set failed: First argument contains undefined in property 'users.undefined.profileImageUrl'

I am a newbie to firebase and Javascript and I have tried many methods to get the user data store by the user.uid but all I'm getting is the data is being stored under "undefined".
Screenshot of uRef?
https://i.stack.imgur.com/Ga19e.png
Here is screenshots of error
https://i.stack.imgur.com/ZiY4e.png
Reference.set failed: First argument contains undefined in property 'users.undefined.profileImageUrl'
Here is the code:
var displayName;<br>
var userInfo;<br>
var profile_url;<br>
$("#login-btn").click(function(){<br>
userInfo = firebase.auth().currentUser;<br>
if (userInfo) { <br>
firebase.auth().signOut(); <br>
} else { <br>
var email = document.getElementById('login_email').value; <br>
var password = document.getElementById('login_pw').value; <br>
firebase.auth().signInWithEmailAndPassword(email, password).then(function(){
document.getElementById('login_bar').style.display = "none";
document.getElementById('logout_bar').style.display = "inline-block";
document.getElementById('userinfo_bar').style.display = "inline-block";
document.getElementById('secession_bar').style.display = "inline-block";
alert("login success");
location.replace('board.html');
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === 'auth/wrong-password') {
alert('wrong-password.');
}
else {
alert(errorMessage);
}
console.log(errorMessage);
});
}
});
$("#join-btn").click(function(){ <br>
var email = document.getElementById('join_email').value;<br>
var password = document.getElementById('join_pw').value;<br>
var displayName = document.getElementById('join_name').value;<br>
var job = $('input[name=job]:checked').val();<br>
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(user) {<br>
var u_Ref = firebase.database().ref('users/' + user.uid);
userInfo = user;
u_Ref.set({
'email' : email,
'job': job,
'profileImageUrl':profile_url,
'uid' : user.uid,
'username': displayName
});
handleFileSelect();
alert("join success");
}, function(error) {<br>
var errorCode = error.code;<br>
var errorMessage = error.message;<br>
alert(error);<br>
});<br>
if (email.length < 4) {
alert('x');
return;
}
if (password.length < 4) {
alert('x');
return;
}
function initApp() {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
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;
user.updateProfile ({
displayName : displayName,
}). then (function () {
console.log ( 'success');
}). catch (function (error) {
console.log( 'no');
});
userInfo = user;
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION);
document.getElementById('login_bar').style.display = "none";
document.getElementById('logout_bar').style.display = "inline-block";
document.getElementById('userinfo_bar').style.display = "inline-block";
document.getElementById('secession_bar').style.display = "inline-block";
$("#secession_bar").click(function(){
user.delete().then(function(){
alert('success');
userRef= firebase.database().ref('users/' + user.uid);
userRef.remove();
firebase.storage().ref().child('userImages/' + userInfo.uid).delete();
location.reload();
});
});
$("#logout_bar").click(function(){
firebase.auth().signOut();
location.reload();
});
} else {
document.getElementById('login_bar').style.display = "inline-block";
document.getElementById('logout_bar').style.display = "none";
document.getElementById('userinfo_bar').style.display = "none";
document.getElementById('secession_bar').style.display = "none";
}
});
}
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault();
var file = evt.target.files[0];
var metadata = {
'contentType': file.type
};
var storageRef = firebase.storage().ref().child('userImages/' +userInfo.uid);
storageRef.put(file, metadata).then(function(snapshot) {
console.log('Uploaded', snapshot.totalBytes, 'bytes.');
console.log('File metadata:', snapshot.metadata);
snapshot.ref.getDownloadURL().then(function(url) {
console.log('File available at', url);
profile_url = url;
});
}).catch(function(error) {
console.error('Upload failed:', error);
});
}
I fixed it but got the same error
Not undefined here
The error message is quite clear:
First argument contains undefined in property 'users.undefined.profileImageUrl'
You're passing undefined as value in users.undefined.profileImageUrl, which is not allowed. The most likely location that raises this error is:
u_Ref.set({
'email' : email,
'job': job,
'profileImageUrl':profile_url,
'uid' : user.uid,
'username': displayName
});
And here the most likely reason is that profile_url hasn't been initialized yet, since you haven't uploaded an image yet,
The simplest fix is to only set the profileImageUrl if profile_url has a value, which you can most easily do by splitting this into two sets:
u_Ref.set({
'email' : email,
'job': job,
'uid' : user.uid,
'username': displayName
});
if (profile_url) {
u_Ref.child('profileImageUrl').set(profile_url)
}
I guess you'll also want to set the profile_url if the image upload finishes later, so you might want to do something like:
snapshot.ref.getDownloadURL().then(function(url) {
console.log('File available at', url);
profile_url = url;
let user = firebase.auth().currentUser;
if (user && user.uid) {
var u_Ref = firebase.database().ref('users/' + user.uid);
u_Ref.child('profileImageUrl').set(profile_url)
}
});

React async login with social media

I'm trying to add a login with social media on my website, but I got some errors because the case is returning first before my HTTP request (Firebase):
firebase.auth().signInWithPopup
How can I use the async function in some way to the case await until the request is complete?
Here is the code:
login(provider, info) {
switch (provider) {
case this.EMAIL:
return firebaseAuth().signInWithEmailAndPassword(
info.email,
info.password
);
break;
case this.EMAILREGISTER:
break;
case this.GOOGLE:
var providerr = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(providerr).then(function(result) {
// This gives you a Facebook Access Token. You can use it to access the Facebook API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
console.log(result);
// ...
}).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;
console.log(error);
// ...
});
//Right here I need to return the token and user async
break;
}
}
//here is the function who is calling:
handleLogin = () => {
const { email, password } = this.state;
if (!(email && password)) {
notification('error', 'Favor informar o email e senha');
return;
}
this.setState({
confirmLoading: true
});
const self = this;
let isError = false;
Firebase.login(Firebase.Google, '')
.catch(result => {
const message =
......
});
}
You can try using async/await so that it will wait till the data is returned. Something like this, just to get you started:
async login(provider, info) {
try {
switch (provider) {
case this.EMAIL:
return firebaseAuth().signInWithEmailAndPassword(
info.email,
info.password
);
break;
case this.EMAILREGISTER:
break;
case this.GOOGLE:
var providerr = new firebase.auth.GoogleAuthProvider();
// This gives you a Facebook Access Token. You can use it to access the Facebook API.
var result = await firebase.auth().signInWithPopup(providerr);
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
console.log(result);
// ...
break;
}
}
catch(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;
console.log(error);
// ...
}
}
}

Firebase create user with email and password and put data in database

I want to create users with the function createUserWithEmailAndPassword and then put the data of that user into my database but it doesn't work.. the user is added to my authentication tab in firebase but not in my database. I also don't get an error.
registerUser.addEventListener('click', function (user) {
event.preventDefault();
closeRegisterForm();
email = registerEmail.value;
password = registerPassword.value;
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function (event) {
var ref = firebase.database().ref("users").child(user.uid).set({
email: user.email,
uid: user.uid
});
})
.catch(function (error) {
var errorCode = error.code;
var errorMessage = error.message;
});
});
Hi I was having the exact same problem. But i used a local function to solve it. Something like this:
createNewUser(form) {
//create new user with provided data of the form
this.afAuth.auth.createUserWithEmailAndPassword(form.email, form.password)
.then(function(firebaseUser) {
console.log("User " + firebaseUser.uid + " created successfully!");
updateFirestore(form, firebaseUser.uid);
return firebaseUser;
}).catch(function(error) {
alert(error)
});
function updateFirestore(form, uidNewUser) {
//push data into firestore using the uid provided
let data = {};
data['mail'] = form.email;
data['name'] = form.name;
//se empuja el arreglo data en el documento del usuario
this.afs.collection('users').doc(uidNewUser).set(data);
console.log(data, uidNewUser);
}
}
You refer to user.uid and user.email but never define user. The return type of sign in method createUserWithEmailAndPassword is a user but you define it as event. Also make sure you wait for the db write promise to resolve and catch any errors there as Frank advised.
Working for me:
const val = this.signupForm.value;
this.authService.doRegister(val)
.then(res => {
this.msg = 'You have registered successfully!';
this.msgType = 'success';
this.authService.updateUser(val.name, null)
.then(suc => {
const created = firebase.firestore.FieldValue.serverTimestamp();
const user = {
first_name: val.name,
last_name: '',
email_personal: val.email,
created: created,
updated: created
};
this.userCollection = this.afs.collection<User>('users');
this.userCollection.doc(suc).set(user);
}, err => {
// console.log(err);
});
this.router.navigate(['/']);
}, err => {
this.msg = err.message;
})
const [phone, setPhone] = useState()
const [email, setEmail] = useState()
const [password, setPassword] = useState()
const handleSignUp = async () => {
if (!email == ' ' && !password == ' ') {
try {
const result = await auth().createUserWithEmailAndPassword(email, password)
firestore()
.collection('Users')
.doc(result?.user?.uid)
.set({
email: result?.user?.email,
phoneNumber: phone,
uid: result?.user?.uid,
displayName: result?.user?.email.split('#')[0],
})
.then(() => {
alert('User added!');
});
} catch (error) {
if (error.code === 'auth/email-already-in-use') {
Alert.alert('That email address is already in use!');
}
else if (error.code === 'auth/invalid-email') {
Alert.alert('That email address is invalid!');
}
else {
Alert.alert(error)
}
}
} else {
Alert.alert("Please Enter Your All Field");
}
}

Categories

Resources