i just started implementing redis with node. during an implementation of authentication method i need to check whether the token exist in redis, if not update the new token in redis and in my mongo db for that i need to write a big callback block and not getting result properly. how can we make the redis get red of callbacks. how can we make it synchronous. sample code is below.
module.exports.authenticate = function(request, response) {
var reply = {};
if(UserSchema) {
var UserModel, attributes;
/** Registering User Model; **/
mongoose.model('user', UserSchema);
UserModel = mongoose.model('user');
attributes = request.params;
UserModel.findOne(attributes, "_id name email token", function(error, user) {
if(!error && user) {
var token;
//delete user.password;
token = user.token;
/** Checking token exists in redis; **/
redisClient.get(token, function(error, value) {
if(value === null && error === null) {
/** Creating new token; **/
token = require('crypto').createHash('md5').update("" + (new Date()).getTime()).digest("hex");
user.token = token;
/** Storing new token on redis; **/
setTokenOnRedis(token);
/** Updating token in the user model; **/
UserModel.update({ _id : user._id}, { token : token }, function(error, user) {
if(error !== null && user === null) {
deleteTokenOnRedis(token);
/** Error message; **/
reply = {
error : true,
code : "AUTH#001",
msg : "User authentication failed, Please check user credentials."
}
response.send(reply);
}else if(error === null && user !== null) {
reply = user;
response.send(reply);
}
});
}else if(value !== null) {
reply = user;
response.send(reply);
}else {
/** Error message; **/
reply = {
error : true,
code : "AUTH#001",
msg : "User authentication failed, Please check user credentials."
};
response.send(reply);
}
});
}else {
/** Error message; **/
reply = {
error : true,
code : "AUTH#001",
msg : "User authentication failed, Please check user credentials."
}
}
});
}else {
/** Error message; **/
reply = {
error : true,
code : "AUTH#001",
msg : "User authentication failed, Please check user credentials."
}
response.send(reply);
}
};