Save data to firebase realtime database if OTP verification is done - reactjs

enter code here
Submit=e=>{
e.preventDefault();
let data="";
this.setUpRecaptcha();
// window.alert("Appointment Done Successfully at time "+this.state.curTime+" ! Go to the home page");
var phoneNumber = this.state.contact;
console.log(phoneNumber)
var appVerifier = window.recaptchaVerifier;
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
.then(function (confirmationResult) {
// SMS sent. Prompt user to type the code from the message, then sign the
// user in with confirmationResult.confirm(code).
window.confirmationResult = confirmationResult;
var code = window.prompt("enter OTP")
confirmationResult.confirm(code).then(function (result) {
// User signed in successfully.
var user = result.user;
alert("OTP is verified!!!");
this.data="doneit";
// ...
}).catch(function (error) {
// User couldn't sign in (bad verification code?)
// ...
alert("OTP verification failed");
});
}).catch(function (error) {
// Error; SMS not sent
// ...
alert("cann't send OTP use another Contact number")
});
//Data storage code
if(this.data=='doneit'){
firebase.database().ref("appoinment").push(
{
name:this.state.name,
email:this.state.email,
contact:this.state.contact,
age:this.state.age,
gender:this.state.gender,
Appointdate:this.state.Appointdate,
Description:this.state.Description,
date:this.state.curTime
}
);
alert(" Data saved successfully");
window.location.reload(false);
}
else{
alert("failed");
}
};
My code is as shown above. I want execution in such a way that if after submitting form Submit() will be called. Then it will check for OTP verification. If it is successful then only data will be stored at firebase realtime database
List item

Why don't you put the logic to save the data after the confirmation promise:
Submit=e=>{
e.preventDefault();
let data="";
this.setUpRecaptcha();
// window.alert("Appointment Done Successfully at time "+this.state.curTime+" ! Go to the home page");
var phoneNumber = this.state.contact;
console.log(phoneNumber)
var appVerifier = window.recaptchaVerifier;
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
.then(function (confirmationResult) {
// SMS sent. Prompt user to type the code from the message, then sign the
// user in with confirmationResult.confirm(code).
window.confirmationResult = confirmationResult;
var code = window.prompt("enter OTP")
confirmationResult.confirm(code).then(function (result) {
// User signed in successfully.
var user = result.user;
alert("OTP is verified!!!");
this.data="doneit";
firebase.database().ref("appoinment").push({
name:this.state.name,
email:this.state.email,
contact:this.state.contact,
age:this.state.age,
gender:this.state.gender,
Appointdate:this.state.Appointdate,
Description:this.state.Description,
date:this.state.curTime
});
alert(" Data saved successfully");
window.location.reload(false);
// ...
}).catch(function (error) {
// User couldn't sign in (bad verification code?)
// ...
alert("OTP verification failed");
});
}).catch(function (error) {
// Error; SMS not sent
// ...
alert("cann't send OTP use another Contact number")
});
};

Related

WalletConnect :- Rainbow always show MATIC when transfer other coins by WalletConnect sendTransaction in react native

I am developing react native mobile application where user can transfer their amount by external wallet (Rainbow, MetaMask).
I am using 'polygon-rpc' network for my users.
The thing is working as expected but when execute transfer method by my contract by WalletConnect sendTransaction(txObj) library it navigate me to connected wallet and prompted the confirmation pop, where it show the my currency in MetaMask, but in Rainbow it always show Matic instead of POZ.
However it works well in Metamask and show the POZ, instead of MATIC.
I am using this code to procced transaction by WalletConnect external wallet
let toAddress = pozPouchFundWallet; // end address to transfer amount
let decimals = BigNumber(18);
let amount1 = new BigNumber(amountValue);
let value = amount1.times(new BigNumber(10).pow(decimals));
let contract = new Web3js.eth.Contract(App_ABI, POZ_TOKEN!);
try {
let dataa = await contract.methods
.transfer(toAddress, value.toString())
.encodeABI();
let txObj = {
// gas: Web3js.utils.toHex(100000),
data: Web3js.utils.toHex(dataa),
from: userWallet,
to: POZ_TOKEN, // Contractor token address
};
try {
const transactionHash = await connector
.sendTransaction(txObj)
.catch((_err: any) => {
Toast.show({
autoHide: true,
text1: t('topUpPoz.transactionFailed'),
type: 'error',
});
});
console.log('transactionHash is =', transactionHash);
resolve(transactionHash);
} catch (error) {
console.log('the connector error is = ', error);
reject(error);
}
} catch (err) {
console.log('contact error is = ', err);
reject(err);
}

SOFTWARE_TOKEN_MFA 400 error with the MFA integration in cognito pool with reactjs

Please refer to the following image.
I was able to successfully integrate the MFA with my Cognito pool and I am getting the OTP as well. Once the OTP is submitted I get the following error message as a 400 bad request. It seems MFA integration is working since once I entered the wrong code as the OTP then it shows the error message.
Once entered the correct OTP that I received into my mobile only I get this error message. Could someone please help me to sort out this issue?
I am expecting to get rid of this 400 Bad request error message which is returned by cognito endpoint call. Please find the below code for my cognito integration with the ReactJs project.
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function(result) {
console.log("RESULT SUCCESS: ", result);
const accessToken = result.getAccessToken().getJwtToken();
console.log("ACCESS TOKEN: ", accessToken);
cognitoUser.getSession(function(err, session) {
if (err) {
console.log(err);
return;
}
// console.log('session validity: ' + session.isValid());
const totpMfaSettings = {
PreferredMfa: true,
Enabled: true
};
cognitoUser.setUserMfaPreference(null, totpMfaSettings, function(
err,
result
) {
if (err) {
console.log(err);
}
console.log("call result " + result);
});
});
},
onFailure: function(err) {
alert(err.message || JSON.stringify(err));
},
mfaSetup: function(challengeName, challengeParameters) {
console.log("MFA SETUP");
cognitoUser.associateSoftwareToken(this);
},
associateSecretCode: function(secretCode) {
const challengeAnswer = prompt("Please input the TOTP code.", "");
cognitoUser.verifySoftwareToken(
challengeAnswer,
"My TOTP device",
this
);
},
selectMFAType: function(challengeName, challengeParameters) {
var mfaType = prompt("Please select the MFA method.", ""); // valid values for mfaType is "SMS_MFA", "SOFTWARE_TOKEN_MFA"
cognitoUser.sendMFASelectionAnswer(mfaType, this);
},
totpRequired: function(secretCode) {
var challengeAnswer = prompt("Please input the TOTP code.", "");
cognitoUser.sendMFACode(challengeAnswer, this, "SOFTWARE_TOKEN_MFA");
},
mfaRequired: function(codeDeliveryDetails) {
var verificationCode = prompt("Please input verification code", "");
cognitoUser.sendMFACode(verificationCode, this);
},
newPasswordRequired: userAttributes => {
// XXXXXXXX
// This is somethign we need to fetch from an input
cognitoUser.completeNewPasswordChallenge("XXXXXXXX", {}, {
onSuccess: result => {
// login
console.log(result)
}
});
// };
}
});

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)

Angularjs : adding a new record using forum and controller

I am new to Angular and I am trying to add data from forum into the database, to do so i need the id of the current user which i get with no problem, only in my post method I rely entirely on the data that i get from the forum, but in the forum i wouldn't of course ask for the id to be filled so I need to add it automatically to my controller and i don't know how to do so : here is the function that I use in my controller :
app.addFT = function () {
//Get the current user Id
Auth.getUser().then(function (data) {
console.log(data.data.email);
Compte.getComptebymail(data.data.email).then(function(result)
{
console.log(result.data.col.IdCollaborateur);
lecollaborateur.push(result.data.col);
$scope.lecollaborateur = lecollaborateur;
});
});
console.log(app.addData);
//we connect it to the back end of the application
FT.createFT(app.addData).then(function (data) {
if(data.data.success){
//create success message
app.loading = false;
app.successMsg = data.data.message + '...Redirection';
//Redirect to show projet
$timeout(function () {
$location.path('/FeuillesTempsListe');
}, 2000);
}else{
//create an error message
app.loading = false;
app.errorMsg = data.data.message;
}
});
};
app.addData is the data the user fills in the view : I get the name,description,...but I don't know how to pass the Id to app.addData other then using the forum, I tried :
app.addData.Id=lecollaborateur.Id; but it's not working , any suggestions ?
You need call createFT only after the success call of getComptebymail.
So that you will have id in the app.addData.
app.addFT = function() {
//Get the current user Id
Auth.getUser().then(function(data) {
console.log(data.data.email);
Compte.getComptebymail(data.data.email).then(function(
result) {
console.log(result.data.col.IdCollaborateur);
lecollaborateur.push(result.data.col);
$scope.lecollaborateur = lecollaborateur;
app.addData.Id = lecollaborateur.Id;
console.log(app.addData);
//we connect it to the back end of the application
FT.createFT(app.addData).then(function(data) {
if (data.data.success) {
//create success message
app.loading = false;
app.successMsg = data.data.message +
'...Redirection';
//Redirect to show projet
$timeout(function() {
$location.path(
'/FeuillesTempsListe'
);
}, 2000);
} else {
//create an error message
app.loading = false;
app.errorMsg = data.data.message;
}
});
});
});
};

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

Resources