Vuevalidate async validation results to a loop - vuejs2

Am using Vue Validate
i have the following in my vuevlidate
validations: {
user_form: {
email: {required,email, isUnique(value) {
// standalone validator ideally should not assume a field is required
if (value === '') return true;
// simulate async call, fail for all logins with even length
return new Promise((resolve, reject) => {
this.$http.post("v1/user-management/users/email-registeredi",{email:value}).then((res)=>{
console.log("res is ", res);
resolve(true);
},(err)=>{
reject(false)
})
})
}},
role: {required},
password: {required}
}
},
The above creates an endless loop of http requests especially when it gets an error
Where am i going wrong

In case vue validate is not handling reject promise well and creating infinite loop.
You can try, async await for Vue validate's isUnique with try and catch returning false on error,
something like this.
validations: {
user_form: {
email: {
required,
email,
async isUnique (value) {
if (value === '') return true
try{
const response = await this.$http.post("v1/user-management/users/email-registeredi",{email:value})
return true;
}
catch(e){
return false;
}
}
}
}

You don't need to use "new Promise" because vue-resource already do that. Try this:
validations: {
user_form: {
email: {required,email, isUnique(value) {
// standalone validator ideally should not assume a field is required
if (value === '') return true;
// simulate async call, fail for all logins with even length
return this.$http.post("v1/user-management/users/email-registeredi",{email:value}).then((res)=>{
console.log("res is ", res);
return true;
},(err)=>{
return false;
});
}},
role: {required},
password: {required}
}
},

Related

Return Values from a callback SQL function in node.js

Currently I'm working on a node.js application, with a register function. For this function I need to check a username is already taken or not. Unfortunately the SQL module in node just accepts a callback function from which I cannot send any booleans back.
Here is some code from my controller module:
async function createUser(req, res) {
try {
const salt = await bcrypt.genSalt(); //standard ist 10
const hashedPassword = await bcrypt.hash(req.body.password, salt);
const newUser = {
userName: req.body.username,
userPassword: hashedPassword
};
const userExists = model.checkIfUserExists(newUser.userName);
if (userExists == false){
// create new user
} else {
// Send json back "user already exists
}
res.status(201).json(newUser);
} catch {
res.status(500);
}
}
And here is the code of the model:
function checkIfUserExists(Username){
console.log("Checking if user exists");
let sql = "select * from users where user_name = ?";
db_conn.query(sql, Username, (err, result) => {
if (err){
throw err;
}
console.log(result);
if (result.length > 0){
return true;
} else {
return false;
}
});
}
Unfortunately the "checkIfUserExists" method never returns back a true or false which leads to the "userExists " variable to be null.
I'd like to know how to do return the bollean there or how to solve the problem in a more elegant way.
Please help me to fix this code. Thanks :)
You can either pass a callback to checkIfUserExists or use promises. If I were you, and since you are already using async/await, I would make your return of checkIfUserExists be a promise. So...your code could become
function checkIfUserExists(Username) {
return new Promise((resolve,reject) => {
console.log("Checking if user exists");
let sql = "select * from users where user_name = ?";
db_conn.query(sql, Username, (err, result) => {
if (err) {
throw err;
}
console.log(result);
if (result.length > 0) {
resolve()
} else {
reject()
}
});
})
}
Then, your code that calls this function would be:
async function createUser(req, res) {
try {
const salt = await bcrypt.genSalt(); //standard ist 10
const hashedPassword = await bcrypt.hash(req.body.password, salt);
const newUser = {
userName: req.body.username,
userPassword: hashedPassword
};
await model.checkIfUserExists(newUser.userName).catch(() => {
// Send json back "user already exists
});
// create user
res.status(201).json(newUser);
} catch {
res.status(500);
}
}
First check your catch statement and also add await before model.checkIfUserExists(newUser.userName)
async function createUser(req, res) {
try {
const salt = await bcrypt.genSalt(); //standard ist 10
const hashedPassword = await bcrypt.hash(req.body.password, salt);
const newUser = {
userName: req.body.username,
userPassword: hashedPassword
};
const userExists = await model.checkIfUserExists(newUser.userName);
if (userExists == false){
// create new user
} else {
// Send json back "user already exists
}
res.status(201).json(newUser);
} catch(ex) {
res.status(500);
}
}
return promise from this function:
function checkIfUserExists(Username){
return new Promise((resolve, reject) => {
console.log("Checking if user exists");
let sql = "select * from users where user_name = ?";
db_conn.query(sql, Username, (err, result) => {
if (err){
return reject(err);
}
console.log(result);
if (result.length > 0){
return resolve(true);
} else {
return resolve(false);
}
});
})
}

stuck on 400 bad request, method might be incorrect?

Hello im currentenly stuck and im not quite sure whats wrong
my postman login is all fine but my backend dont accept anything so im pretty sure there is something wrong with my method
export default {
data() {
return {
loading: false,
error: null,
login: {
email: "",
password: "",
}
}
},
methods: {
UserLogin: function() {
this.loading = true;
this.axios.post('http://localhost:3000/login', {user: this.login})
.then((res) =>{
this.$cookies.set('jwt', res.data.jwt);
this.$cookies.set('isAdmin', res.data.isAdmin);
this.$router.push('/dashboard');
}).catch(err => {
//fejl
this.error = err.response.data.message;
});
this.loading = false;
},
CheckForNullInObject: function(obj) {
for (let key in obj) {
if(obj[key] == null || obj[key] == "") return false;
}
return true;
}
}
and my backend
router.post('/', async (req, res) => {
if(!req.body.email || !req.body.password) {
res.status(400).json({
message: "missing values1"
});
return
}
always hits the missing values1 no matter what I write
You've POSTed the login data under user, but your backend code doesn't read that property.
Either update your frontend to send the data directly (without user):
this.axios.post('http://localhost:3000/login', { ...this.login })
Or update the backend to read the data from user:
if(!req.body.user.email || !req.body.user.password)

NodeJS: bcrypt is returning false even when the password is correct

I am having trouble with the bcrypt.compare portion of my code. My route is able to hash the password and store the password in the database. The database is able to store 255 characters and I have verified that the password is 60 characters long. Every time I compare the password to the hashed password on the db, I get a false returned on from bycrypt.compare.
Has anyone encountered this and know what I may be doing wrong?
Auth Route for creating the user in the database:
app.post('/register/local', async (req, res) => {
const hashedPassword = await bcrypt.hash(req.body.password, 10) || undefined
const existingLocalUser = await db.User.findOne({ where: { email: req.body.email } }) || undefined
if (!existingLocalUser) {
try {
const newUser = await db.User.create({
given_name: req.body.given_name,
family_name: req.body.family_name,
email: req.body.email,
password: hashedPassword,
}
)
res.redirect('/login')
} catch {
res.redirect('/register')
}
} else if (existingLocalUser.dataValues.google_id) {
const updateUser = await db.User.update(
{ password: hashedPassword },
{ where: { email: req.body.email } }
)
} else {
console.log("You already have an account. Please login.")
res.redirect('/login');
}
})
Local Strategy from Passport:
passport.use(new LocalStrategy( async (username, password, done) => {
const existingLocalUser = await User.findOne({ where: { email: username }})
if (!existingLocalUser) {
console.log("No user exisits")
return done(null, false)
}
console.log("password", password)
console.log("existingLocalUser.password", existingLocalUser.password)
await bcrypt.compare(password, existingLocalUser.dataValues.password, function(error, result) {
if (error) {
return done(error)
} else if (result) {
return done(null, existingLocalUser)
} else {
return done(null, false)
}
})
}
));
bcrypt.compare(password, existingLocalUser.password, function(error, result) {
if (error) {
return done(error)
} else if (result) {
return done(null, existingLocalUser)
} else {
return done(null, false)
}
})
You are trying to use callback and await together, kindly remove await and stick to callbacks or you refactor and use async-await alone
As #cristos rightly pointed out the problem could be that you are mixing up async/await and callbacks. Stick to one pattern.
Here's how your code would be with async/await,
try {
const result = await bcrypt.compare(password, existingLocalUser.password);
if (result) {
return done(null, existingLocalUser);
} else {
return done(null, false);
}
} catch (error) {
return done(error);
}
Also on another note, are you sure you are comparing the correct values?
Going by the code sample you have provided I can see that you are logging,
console.log("password", password)
console.log("existingLocalUser.password", existingLocalUser.password)
However, the values compared in bcrypt.compare() is different,
bcrypt.compare(password, existingLocalUser.dataValues.password)
I figured out why it wasn't working... React or Redux was masking the password with asterisks so changing it to a sting of asterisks which gets hashed..

socket.io callback is not recevied in vue.js method?

Using this vue.js method to login users:
loginUser: function () {
socket.emit('loginUser', {
email: this.email ,
password: this.password
}, function() {
console.log('rooms in callback are:', rooms);
});
}
On the server the loginUser event is handled by:
socket.on('loginUser', (newuser,callback)=> {
var body = _.pick(newuser, ['email', 'password']);
console.log('body is:', body);
User.findByCredentials(body.email, body.password).then((user) => {
return user.generateAuthToken().then((token) => {
if (token) {
console.log('token was found');
let rooms = ['Cats', 'Dogs', 'Birds'];
callback(rooms);
} else {
socket.emit('loginFailure', {'msg' : 'Login failure'});
}
}).catch((e) => {
throw e;
});
}).catch((e) => {
socket.emit('loginFailure', {'msg' : 'Login failure'});
throw e;
});
});
I can see 'token was found' printed out in the console but does not recieve the rooms being printed in the browser console. I receive no errors either.
I'm wondering whetehr it is due to how vue.js methods work? And if so, if there is a way around it?
You forgot to specify rooms as argument in the callback
loginUser: function () {
socket.emit('loginUser', {
email: this.email ,
password: this.password
}, function(rooms) { // need to have rooms argument
console.log('rooms in callback are:', rooms);
});
}

How to use transaction by sequelize in my node js

While converting legacy long sql procedure to sequelizer, I met trouble to make transaction to my async functions.
I read sequelizer's transaction documents. But failed to understand clearly.
Here is my code.
const models = require('../models/models.js');
const sequelize = models.Sequelize;
async function isExistFeeHist(dansokSeqNo) {
log.debug("isExistFeeHist()");
let feeHist = await models.FeeHist.findOne({
where: {
DansokSeqNo: dansokSeqNo,
FeeStatus: {[Op.ne]: null}, //is not null
DelYN: false
}
});
return !!feeHist;
}
async function isPaid(dansokSeqNo) {
...
}
async function getNextDansokHistSerialNo(dansokSeqNo) {
...
}
async function getVBankSeqNo(dansokSeqNo) {
...
}
async function updateVBankList(dansokSeqNo, vBankSeqNo) {
...
}
//check if can cancel
async function checkCancelable(dansokSeqNo) {
log.debug("checkCancelable() ", dansokSeqNo);
if (await isExistFeeHist(dansokSeqNo)) {
let e = {status:400, message: 'already imposed dansokSeqNo ' + dansokSeqNo };
return Promise.reject({status:400, message: e.message });
}
if (await isPaid(dansokSeqNo)) {
let e = {status:400, message: 'already paid dansokSeqNo ' + dansokSeqNo };
return Promise.reject({status:400, message: e.message });
}
return Promise.resolve();
}
....
async function doCancel(dansokSeqNo, cancelCauseCode, histMemo) {
try {
await checkCancelable(dansokSeqNo);
//// <== Here I want to start transaction
let nextDansokSerialNo = await getNextDansokHistSerialNo(dansokSeqNo);
let dansokHist = await insertNewDansokHist(dansokSeqNo, nextDansokSerialNo, cancelCauseCode, histMemo);
await updateDansokHist(dansokSeqNo, cancelCauseCode);
let vBankSeqNo = await getVBankSeqNo(dansokSeqNo);
if (vBankSeqNo > 0) {
await updateVBankList(dansokSeqNo, vBankSeqNo);
let vBankList = await getVBankList(dansokSeqNo);
}
// <== Here I want to commit transaction
} catch (e) {
// <== Here I want to rollback transaction
return Promise.reject({status:e.status, message: e.message });
}
}
exports.cancelDansok = function (req, res) {
res.setHeader("Content-Type", "application/json; charset=utf-8");
...
jwtAcessAuth(accessToken)
.then((decoded) => {
log.info("jwt success, ", decoded);
worker = decoded.loginName;
return doCancel(dansokSeqNo, cancelCauseCode, histMemo);
})
.then(() => {
res.status(200).json({ message: 'cancelDansok success.' });
})
.catch(e => {
return res.status(e.status).json(e);
});
};
My function is assembled with several async functions. And it need to bind one transaction.
What is the best practice to use transaction in my several async await functions?
Here is the best example provided by Sequlize for Transaction :
All you need to care is pass transaction to next level of chaining
return sequelize.transaction(function (t) {
// chain all your queries here. make sure you return them.
return User.create({
firstName: 'Abraham',
lastName: 'Lincoln'
}, {transaction: t}).then(function (user) {
return user.setShooter({
firstName: 'John',
lastName: 'Boothe'
}, {transaction: t});
});
}).then(function (result) {
// Transaction has been committed
// result is whatever the result of the promise chain returned to the transaction callback
}).catch(function (err) {
// Transaction has been rolled back
// err is whatever rejected the promise chain returned to the transaction callback
});
For more details : Transactions