Reputation: 612
I have a function that selects username from mysql database and return results to post request as following:
function userAuthentication(user){
var deferred = Q.defer();
pool.getConnection(function(err, connection) {
if (err) {
var dbError = new Error('No db connection');
console.log(dbError);
}
else {
var selectUserName = 'SELECT * FROM User WHERE username= '+connection.escape(user)+' ';
connection.query(selectUserName, function(error, rows){
if(error){
console.log(error);
deferred.reject(error);
}
else if(rows.length === 0){
var countError = new Error('No User Found');
console.log ("Database.js -> "+ countError);
deferred.reject(countError);
}else{
deferred.resolve(rows);
}
});
}
connection.release();
});
return deferred.promise;
}
the function userAuthentication
is called from the rout.post request
router.post('/checkAuthentication', function(request, response) {
database.userAuthentication(request.body.username).then(function(data) {
if(data[0].RowDataPacket!=0){
if(bcrypt.compareSync(request.body.password,data[0].password)){
var token = jwt.sign({
username: data[0].username,
}, superSecret,{
expiresInMinutes: 1440
});
console.log(token);
// return the information including token as JSON
response.json({
success: true,
message: 'Token Created',
token: token
});
}
else{
response.json({ success: false, message: 'Authentication failed. Wrong Password.' });
}
}else{
response.json({ success: false, message: 'Authentication failed. User not found.' });
}
});
});
i am trying to create a token when i check if inputed username and password matches the ones in mysqlDb, but unfortunately the token is not created; the line console.log(token)
is not printing any result into the console. what is the part i am missing??? I appreciate your help guys.
Upvotes: 2
Views: 1016
Reputation: 17721
Which jwt
node module are you using?
I suppose it is not node-jsonwebtoken, since it does not support expiresInMinutes
, but only expiresInMinutes
...
However, you should enclose the jwt.sign()
call in a try/catch block, to catch any error it throws...:
try {
var token = jwt.sign(
{
username: data[0].username,
},
superSecret,
{
expiresIn: 1440 * 60,
}
);
} catch(err) {
console.error('error signing json web token:', err);
}
Upvotes: 1