Firebase.child() Fails - angularjs

For some reason it gives me the error
Uncaught Error: Firebase.set failed:
First argument contains undefined in property
'User Info.fcd90e70-3774-4098-8615-cedd85759757.Username'
I dont know what the reason is...
Here is registrationController.js:
NOTE: Ref is a Factory that gets my Ref for firebase..
app.controller('regController', ["$scope","AuthService","Ref", function($scope, AuthService, Ref){
//////////CHECKING FOR EMPTYNESS OF A VALUE/////////
function isEmpty(value){
return (value == null || value.length === 0);
}
/////////////////////////////////////////////////////
$scope.createUser = function(){
var username = $scope.usernameModel;
var email = $scope.emailModel;
var password = $scope.passwordModel
if(isEmpty(username) == false && isEmpty(email)== false && isEmpty(password)==false){
Ref.createUser({
email: email,
password: password
}, function(error, userData) {
if (error) {
switch (error.code) {
case 'EMAIL_TAKEN':
sweetAlert("Oops...", "This User is Already Created. Try Logging In", "error");
break;
case 'INVALID_EMAIL':
sweetAlert("Oops...", "The Email You Entered is Invalid", "error");
break;
case 'INVALID_PASSWORD':
sweetAlert("Oops...", "The Password You Entered is Invalid", "error");
break;
default:
sweetAlert("Oops...", "Error Creating this user : " + error, "error");
break;
}
}
else{
AuthService.User.email = $scope.emailModel;
AuthService.User.password = $scope.passwordModel;
AuthService.User.uid = userData.uid;
AuthService.User.username = $scope.usernameModel;
Ref.child("User Info").child(AuthService.User.uid).set({
Username: $scope.username,
Email: AuthService.User.email,
Password: AuthService.User.password,
UID: AuthService.User.uid
});
swal("Congratz!", "You are sucessfully authenticated", "success")
}
})
}
else{
if(true)
return false
else
return true;
}
}
}])

Related

Catch exception in LWC thrown from Apex in Salesforce

I have the below code to throw an exception from Apex
#AuraEnabled()
public static void associateAccount(string userId, string accountSAPNumber) {
if(String.isBlank(userId) || string.isBlank(accountSAPNumber)) {
throw new AuraHandledException('Please specify both User Email2 and SAP Number2');
}
List<user> users = [SELECT Id, Name,Email FROM User WHERE Email =: userId AND IsActive = true AND Profile.Name ='OEA Customer'];
if(users == null || users.size() <= 0) {
NoDataFoundException noUsersFound = new NoDataFoundException();
noUsersFound.setMessage('No users found with the specified email address: ' + userId);
throw noUsersFound;
}
Id accountRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('OEA Customer Location').getRecordTypeId();
accountSAPNumber = '%' + accountSAPNumber;
List<Account> accounts = [SELECT Id FROM Account WHERE RecordTypeId =:accountRecordTypeId AND SAP_Number__c like :accountSAPNumber];
if(accounts == null || accounts.size() <= 0) {
NoDataFoundException noAccountFound = new NoDataFoundException();
noAccountFound.setMessage('No accounts found with the specified SAP Number: ' + accountSAPNumber);
throw noAccountFound;
}
else if(accounts.size() > 1) {
SearchException moreThan1Account = new SearchException();
moreThan1Account.setMessage('More than 1 account found with the specified SAP Number: ' + accountSAPNumber);
throw moreThan1Account;
}
OEA_NewContactFormController.accountMethod(userId, accountSAPNumber);
}
I am not able to catch this exception in my LWC Controller using the below
continueButtonClicked() {
associateAccount({
userId: this.searchKey,
accountSAPNumber: this.accountNumber,
})
.then((result) => {
try {
console.log("return from remote call " + result);
this.modalPopUpToggleFlag = false;
} catch (error) {
console.log('some error');
}
})
.error((error) => {
console.log("some error in code");
/*if (Array.isArray(error.body)) {
console.log(
"error message :" + error.body.map((e) => e.message).join(", ")
);
} else if (typeof error.body.message === "string") {*/
//console.log("error message :" + error);
//}
})
.finally(() => {
console.log("finally message :");
});
}
This always gives me an error on the console as "Uncaught (in promise)" and with the details of the exception. How can I catch this exception in a handled way.
The correct syntax is .then().catch().finally(), while you wrote .then().error().finally().
Moreover associateAccount returns void, so there will be no result received from then. There is also no reason to wrap this.modalPopUpToggleFlag = false; in a try-catch, only if your never defined modalPopUpToggleFlag there could be an error.
continueButtonClicked() {
associateAccount({
userId: this.searchKey,
accountSAPNumber: this.accountNumber,
})
.then(() => {
console.log("return from remote call);
this.modalPopUpToggleFlag = false;
})
.catch((error) => {
console.log("some error in code:", error);
});
}
Here is a good reading about Using Promises in Javascript

undefined is not an object (evaluating 'storeDataFactory.createUser(user).then

the function runs and console.log shows the user object on the backend. I don't understand why it's telling me there is an issue here, and really need some guidance.
vm.register = function() {
//check that passwords match
if(vm.password != vm.passwordRepeat) {
vm.registerError = "Passwords must match.";
return;
} else {
var username = vm.username;
// console.log("Valid form. Checking for existing user",username);
storeDataFactory.userExists(username).then(function(response){
//if user exists, return error
if(response.data.length > 0) {
vm.registerError = "A user with email " + username + " already exists. Please login.";
return;
} else {
//if no user exists
if(response.data.length == 0) {
// console.log("No user exists. Continue with registration.");
}
//assign info to user object
var user = {
username: vm.username,
password: vm.password,
name: vm.name,
phone: vm.phone
};
**storeDataFactory.createUser(user).then(function(response){**
vm.user = response.data;
console.log("Created user", vm.user);
if(response.data.length > 0) {
console.log("Created user", vm.user);
vm.registerMessage = "Successful registration, please login";
vm.registerError = null;
vm.user = response.data;
}
}).catch(function(error){
console.log(error);
vm.registerError = "There was an error creating your account.";
vm.registerMessage = null;
});
}
});
}
};
The backend code:
module.exports.register = function(req, res) {
console.log('registering user', req.body);
//create the user object with hashed pass
User
.create({
username: req.body.username,
name: req.body.name,
phone: req.body.phone,
password: bcrypt.hashSync(req.body.password, bcrypt.genSaltSync(10))
}, function(err, user) {
if (err) {
console.log("Error creating account");
res
.status(400)
.json(err);
} else {
console.log("Account created!", user);
res
.status(201)
.json(user);
}
});
};
Account created! and the user object are logged on the backend. It just won't display that damn Successful Registration! Please login. message.
storeDataFactory code:
/* global angular */ angular.module('rumbleApp').factory('storeDataFactory', storeDataFactory);
function storeDataFactory($http) {
return {
userExists: userExists,
createUser: createUser
};
function userExists(username) {
return $http.get('/api/users/userExists/' + username).then(complete).catch(failed);
}
function createUser(user) {
$http.post('/api/users/register', user).then(complete).catch(failed);
}
function complete(response) {
return response;
}
function failed(error) {
console.log(error.statusText);
return "There was an error with the API call.";
}
}
Are you sure you're returning from storeDataFactory.createUser()? Can you post the code for that method?
Sounds like the code is executing, but you're not returning anything from it (hence why it thinks it's undefined)

How to display login error message one after another

I am supposed to check if my login has an error it will display "invalid username. then, the second login will display " server busy" and third login will redirect to link dashboard.html
However, my codes below ignore the error message and continue to dashboard.html.
How am i supposed to loop the statement so that the error will display accordingly.
postData.data._class = postData.clazz;
$timeout(function (data,status) {
$scope.isLoading = false;
if ($scope.hasError = false){
$scope.errorMessage = "Invalid username or password. Error code = " + status;
console.log($scope.errorMessage)
}
}, 2000);
$timeout(function (data,status) {
$scope.isLoading = false;
if ($scope.hasError = true){
$scope.errorMessage = "Server busy please try again later. Error code = " + status;
console.log($scope.errorMessage)
}
}, 2000);
$timeout(function (data,status) {
$scope.isLoading = false;
if ($scope.hasError = true){
$window.location.href = "/dashboard.html";
}
}, 2000);
If my understanding is correct, then you want to have 3 different results when user triggers the login function with error scenario that can be due to invalid credentials or some other issue.
If that is correct, then you can do something like following
You will need to maintain a counter that defines the attempt.
$scope.counter = 0; // This should be outside the event handler function
$timeout(function (data,status) {
$scope.isLoading = false;
if ($scope.hasError){
if($scope.counter == 0) {
$scope.errorMessage = "Invalid username or password. Error code = " + status;
console.log($scope.errorMessage);
$scope.counter++;
} else if($scope.counter == 1) {
$scope.errorMessage = "Server busy please try again later. Error code = " + status;
console.log($scope.errorMessage);
$scope.counter++;
} else {
$window.location.href = "/dashboard.html";
}
}
}, 2000);
Please note: $scope.hasError = true is assignment and NOT comparison.

Firebase setting user data on registration

I want to create an new user in my firebase. This is the code I´m using:
function createUser(email, password, username) {
ref.createUser({
email: email,
password: password
}, function(error) {
if (error === null) {
$activityIndicator.stopAnimating();
$scope.padding_error = null;
$scope.error = null;
logUserIn(email, password);
} else {
$activityIndicator.stopAnimating();
console.log(error.code);
switch (error.code) {
case "INVALID_EMAIL":
$scope.padding_error = "10";
$scope.error = "Falsche E-Mail Adresse oder falsches Passwort";
$scope.$apply();
case "INVALID_PASSWORD":
$scope.padding_error = "10";
$scope.error = "Falsche E-Mail Adresse oder falsches Passwort";
$scope.$apply();
case "EMAIL_TAKEN":
$scope.padding_error = "10";
$scope.error = "Diese E-Mail Adresse ist schon registriert";
$scope.$apply();
}
}
});
}
I want to store the username in addition to email and password somewhere in my firebase. How is this possible instantly after user registration?
If the registration is succesful you can simply push the email and password variables to firebase. See code below.
function createUser(email, password, username) {
ref.createUser({
email: email,
password: password
}, function(error) {
if (error === null) {
... Registration successful
$activityIndicator.stopAnimating();
$scope.padding_error = null;
$scope.error = null;
##NEWCODE HERE##
emailRef = new Firebase("<YOURFIREBASEURL>/accounts/"+username+"/email")
passRef = new Firebase("<YOURFIREBASEURL>/accounts/"+username+"/password")
emailRef.set(email)
passRef.set(password)
logUserIn(email, password);
} else {
... Something went wrong at registration
}
}
});
}

express res.send http code and text catch up by backbone.js

i try to programming a register with express and backbone.js. the express part looks like that
app.post('/signup', function (req, res) {
var name = req.param("name", null);
var country = req.param("country", null);
var email = req.param("email", null);
var cemail = req.param("cemail", null);
var password = req.param("password", null);
if (email !== cemail ||
!validate.Email(email) ||
email == null) {
console.log("There is something wrong with email address");
res.send(400, "Please check your email address.");
return;
};
if (password == null || !validate.Password(password)) {
console.log("There is something wrong with password");
res.send(400, "Password doesn't match security requirements");
return;
};
if (name == null || country == null) {
console.log("Some fields is not filled with value.");
res.send(400);
return;
};
signup(name, country, email, password);
res.send(200);
});
if an user give invalid email address, then it gonna respond with http code 400 and some text. Now my question is, how can i catch up this text, on the backbone.js site. it is possible or not. Frontend backbone.js code
$.post('/signup', {
name: $('input[name=name]').val(),
country: $('input[name=country]').val(),
email: $('input[name=email]').val(),
cemail: $('input[name=cemail]').val(),
password: $('input[name=password]').val()
}, function(data) {
console.log(data);
}).error(function(){
console.log("Sign up error");
});
return false;
the $.post error callback will be passed the response object and that will contain the text error message.
.error(function(response){
console.log("Sign up error", response.responseText);
});

Resources