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

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

Related

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');

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

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
...

firebase - 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".
var displayName;
var userInfo;
var profile_url;
$("#login-btn").click(function(){
userInfo = firebase.auth().currentUser;
if (userInfo) {
firebase.auth().signOut();
} else {
var email = document.getElementById('login_email').value;
var password = document.getElementById('login_pw').value;
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(){
var email = document.getElementById('join_email').value;
var password = document.getElementById('join_pw').value;
var displayName = document.getElementById('join_name').value;
var job = $('input[name=job]:checked').val();
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(user) {
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) {
var errorCode = error.code;
var errorMessage = error.message;
alert(error);
});
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 spotted a thing in your code, createUserWithEmailAndPassword method returns a promise which is of type UserCredential, an object that contains a structure of credential and user, So you've made a mistake in there by asking of property uid of user (the returned promise) which is non-existence.
it should looks like this:
firebase.auth().createUserWithEmailAndPassword(email, password).then(function(credential) {
var userInfo = creadential.user;
var u_Ref = firebase.database().ref('users/' + userInfo.uid);
u_Ref.set({
'email' : email,
'job': job,
'profileImageUrl':profile_url,
'uid' : userIfo.uid,
'username': displayName
});

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

How to upload and assign profile picture to user during registration with Firebase?

I found a nice script via the Youtube tutorial of Firebase itself on how to upload a picture, however, the code works for an signed in user and I would like to do this on the sign up page.
I am under Ionic Framework so here is the code of the tutorial :
//Upload Profile Picture
//Altered code from: Firebase Youtube Channel.
//Get Elements
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
//Listen for file
fileButton.addEventListener('change', function(e){
//Get File
var file = e.target.files[0];
//Create a Storage Ref
var storageRef = firebase.storage().ref('profilePictures/' + file.name);
//Upload file
var task = storageRef.put(file);
var user = firebase.auth().currentUser;
//Update Progress Bar
task.on('state_changed',
function progress(snapshot){
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) *100;
uploader.value = percentage;
//if percentage = 100
//$(".overlay").hide();
},
function error(err){
},
function complete(){
}
);
});
//Display Profile Picture
function showUserDetails(){
var user = firebase.auth().currentUser;
var name, photoUrl;
if (user != null) {
name = user.displayName;
photoUrl = user.photoURL;
document.getElementById('dp').innerHTML=photoURL;
document.getElementById('username').innerHTML=name;
}}
And here is the code of my sign up controller :
.controller('signupController', ['$scope', '$state', '$document', '$firebaseArray', 'CONFIG', function($scope, $state, $document, $firebaseArray, CONFIG) {
$scope.doSignup = function(userSignup) {
//console.log(userSignup);
if($document[0].getElementById("cuser_name").value != "" && $document[0].getElementById("cuser_pass").value != ""){
firebase.auth().createUserWithEmailAndPassword(userSignup.cusername, userSignup.cpassword).then(function() {
// Sign-In successful.
//console.log("Signup successful");
var user = firebase.auth().currentUser;
var database = firebase.database();
//Upload Profile Picture
//Altered code from: Firebase Youtube Channel.
//Get Elements
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
user.sendEmailVerification().then(function(result) { console.log(result) },function(error){ console.log(error)});
firebase.database().ref().child('/accounts/' + user.uid).set({
name: userSignup.displayname,
email: userSignup.cusername,
password: userSignup.cpassword,
description: "No description for this user",
facebook: "",
twitter: "",
}).then(function() {
// Update successful.
$state.go("login");
}, function(error) {
// An error happened.
console.log(error);
});
}, function(error) {
// An error happened.
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode);
if (errorCode === 'auth/weak-password') {
alert('Password is weak, choose a strong password.');
return false;
}else if (errorCode === 'auth/email-already-in-use') {
alert('Email you entered is already in use.');
return false;
}
});
}else{
alert('Please enter email and password');
return false;
}//end check client username password
};// end $scope.doSignup()
}])
As you can see, I would like to integrate the first tutorial's code in the sign up and still attribute it to my user's storage with his UID but I can not find a way to do so... Any idea ?
// The code below has not been tested but it should work or at least give
//you an idea of how to approach your issue
.controller('signupController', ['$scope', '$state', '$document', '$firebaseArray', 'CONFIG', function($scope, $state, $document, $firebaseArray, CONFIG) {
$scope.doSignup = function(userSignup) {
//console.log(userSignup);
if($document[0].getElementById("cuser_name").value != "" && $document[0].getElementById("cuser_pass").value != "" && $document[0].getElementById("fileButton").value != ""){
firebase.auth().createUserWithEmailAndPassword(userSignup.cusername, userSignup.cpassword).then(function() {
// Sign-In successful.
//console.log("Signup successful");
var user = firebase.auth().currentUser;
var database = firebase.database();
//Upload Profile Picture
//Altered code from: Firebase Youtube Channel.
//Get Elements
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
user.sendEmailVerification().then(function(result) { console.log(result) },function(error){ console.log(error)});
//Get File
var file = fileButton.value; // or however way the file path can be obtained
var storageRef = firebase.storage().ref('profilePictures/' + file.name);
//Upload file
var task = storageRef.put(file);
var user = firebase.auth().currentUser;
//Update Progress Bar
task.on('state_changed',
function progress(snapshot){
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) *100;
uploader.value = percentage;
//if percentage = 100
//$(".overlay").hide();
},
function error(err){
},
function complete(){
//Obtain the URL for the uploaded photo
var photoURL = task.snapshot.downloadURL;
firebase.database().ref().child('/accounts/' + user.uid).set({
name: userSignup.displayname,
email: userSignup.cusername,
photoURL: photoURL //add a photoURL attribute and assign it to the URL of the newly uploaded file
password: userSignup.cpassword,
description: "No description for this user",
facebook: "",
twitter: "",
}).then(function() {
// Update successful.
$state.go("login");
}, function(error) {
// An error happened.
console.log(error);
});
}
);
});
}, function(error) {
// An error happened.
var errorCode = error.code;
var errorMessage = error.message;
console.log(errorCode);
if (errorCode === 'auth/weak-password') {
alert('Password is weak, choose a strong password.');
return false;
}else if (errorCode === 'auth/email-already-in-use') {
alert('Email you entered is already in use.');
return false;
}
});
}else{
alert('Please enter email and password');
return false;
}//end check client username password
};// end $scope.doSignup()
}])

Categories

Resources