node.js post api returns old response - javascript

I am using express post api for login a user, the problem is it returns the previous post response.
I dont know what wrong thing I am doing.
Here is my app.js
var express = require('express');
var session = require('express-session');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var csrf = require('csurf');
// var lusca = require('lusca');
var db = require('./db.config');
var index = require('./routes/index');
var auth = require('./routes/auth');
var users = require('./routes/users');
var admin = require('./routes/admin');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// app.use(cookieParser());
//this or other session management will be required
app.use(session({
secret: 'Qwaszx',
resave: true,
saveUninitialized: true
}));
app.use(express.static(path.join(__dirname, 'public')));
/**
* CSRF
*/
// app.use(lusca({
// csrf: true,
// csp: { /* ... */},
// xframe: 'SAMEORIGIN',
// p3p: 'ABCDEF',
// hsts: {maxAge: 31536000, includeSubDomains: true, preload: true},
// xssProtection: true,
// nosniff: true,
// referrerPolicy: 'same-origin'
// }));
/**
* CSRF Token
*/
app.use(csrf());
app.use(function (req, res, next) {
res.cookie('XSRF-TOKEN', req.csrfToken());
res.locals._csrf = req.csrfToken();
next();
});
/**
* Routes
*/
app.use('/', index);
app.use('/auth', auth);
app.use('/users', users);
app.use('/admin', admin);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
and my auth.js route file is under routes directory which is as below:
where I am posting login and getting old response all the time time I do not quit the server and restart it.
var express = require('express');
var router = express.Router();
var userModel = require('../model/user.model');
var session = require('express-session');
var auth = require('../middleware');
/**
* Get register API
*/
router.get('/register', auth.Auth, function(req, res, next) {
res.render('auth/register', { title: 'Register a new user' });
});
/**
* Post register API
*/
router.post('/register', auth.Auth, function (req, res, next) {
if(req.body.password === req.body.c_password ){ //password match
userModel.create(req.body).then(function (result){//Create user
res.redirect('/auth/login');
}).catch( function (err) {
res.redirect('/auth/register');
});
}
else{
res.redirect('/auth/register');
}
});
/**
* Get login API
*/
router.get('/login', auth.Auth, function (req, res, next) {
res.render('auth/login');
});
/**
* Post login API
*/
router.post('/login', auth.Auth, function (req, res, next) {
userModel.login(JSON.stringify(req.body)).then( function(resp) {
// console.log(resp);
req.session.user = {
user_id : resp.user_id,
user_type : resp.user_type,
};
// res.send(resp);
res.json(resp);
// res.redirect('/auth/login')
}).catch(function (err){
// console.log(err);
res.json(err);
// res.redirect('/auth/login')
});
});
/**
* Logout API
*/
router.get('/logout', function (req, res, next) {
return userModel.logout(req.session.user.user_id).then(function (result) {
// console.log("result = " + result);
delete req.session.user;
res.redirect('/auth/login');
}).catch(function(err){
// console.log(err);
res.redirect('/');
});
});
module.exports = router;
now my model file where I put database interface is user.model.js is uder model directory which is shown below:
var connection = require('../db.config');
var randomstring = require("randomstring");
var passwordHash = require('password-hash');
var q = require('q');
var deferred = q.defer();
model = {};
model.index = index;
model.create = create;
model.show = show;
model.login = login;
model.logout = logout;
model.adminLogin = adminLogin;
module.exports = model;
/**
* Show all users
*/
function index(){
connection.query('SELECT * FROM users as U JOIN logs as L ON U.id = L.user_id WHERE U.user_type != "1" ORDER BY L.id DESC', function(error, response){
if(error) deferred.reject(error);
if(response.length > 0){
// console.log(response);
deferred.resolve(response);
}
else{
deferred.resolve([]);
}
});
return deferred.promise;
}
/**
* Create a new user
*
* #param {*array} data
*/
function create(data){
var hashedPassword = passwordHash.generate(data.password);
var user = {
'email' : data.email,
// 'user_name' : data.user_name,
'mac_add' : data.mac_add,
'password' : hashedPassword,
'verification_code' : randomstring.generate(10),
'_token' : data._csrf,
}
//Check user is already exists or not
connection.query('SELECT * FROM users WHERE email = "' + user.email + '" LIMIT 0,1', function(error, result) {
if(error) {
deferred.reject(error);
}
if(result[0]){
deferred.reject('Email ' + result[0].email + ' is already taken. Please try with another email.');
}
else{
return createUser();
}
});
//Create User
function createUser() {
connection.query('INSERT INTO users SET ? ', user , function (error, response){
if(error) {
console.log(error);
deferred.reject(error);
}
else{
console.log(response);
deferred.resolve(response);
}
});
}
return deferred.promise;
}
/**
* Show user details
*
* #param {*number} id
*/
function show(id){
connection.query('SELECT * FROM users WHERE id = "' + id + '"', function(error, response) {
if(error) deferred.reject(error);
if(response[0]) deferred.resolve(response[0]);
});
return deferred.promise;
}
/**
* Login user using email, password and mac address
*
* #param {* array} data
*/
function login(data){
var userData = JSON.parse(data);
connection.query('SELECT * FROM users WHERE email = "' + userData.email + '" LIMIT 0,1', function(error, response) {
if(error) deferred.reject(error);
//check if user exists
if(response.length > 0){
if(passwordHash.verify(userData.password, response[0].password)){//password matching
// Validate that an address is a mac address
if(response[0].user_type === 0){
console.log(response[0]);
deferred.resolve(response[0]);
// if ( require('getmac').isMac(response[0].mac_add) ) {
// // var res = JSON.parse(result[0]);
// return createLog(response[0].id, response[0].user_type);
// }
// else{
// deferred.reject('Unauthorized System!');
// }
}
// else{
// var result = {
// 'user_id' : response[0].id,
// 'user_type' : response[0].user_type,
// }
// deferred.resolve(result);
// }
}
else{
deferred.reject('Invalid credential');
}
}
else{
deferred.reject('User not found');
}
});
/**
* Create user logs
*
* #param {*numeric} user_id
*/
function createLog(user_id, user_type){
var log = {
'user_id' : user_id,
// 'in_time' : new Date(),
}
result = {
'user_id' : user_id,
'user_type' : user_type,
}
connection.query('INSERT INTO logs SET ? ', log, function(err, resp) {
if(err) deferred.reject(err);
if(resp) deferred.resolve(result);
});
}
return deferred.promise;
}
/**
* Logout out time entry
*
* #param {*number} user_id
*/
function logout(user_id){
//Get row id of current log from logs table
connection.query('SELECT id FROM logs where user_id = "' + user_id + '" ORDER BY id DESC LIMIT 0,1', function(err, resp){
if(err) deferred.reject(err);
if(resp[0]){
// console.log(result[0].id);
return updateLog(resp[0].id); //updating time
}else{
deferred.reject("No logs");
}
});
function updateLog(id){ // update the out time
// var out_time = new Date();
// console.log(out_time);
connection.query('UPDATE logs SET signature = "shift end", status = "1" WHERE id = ' + id, function(error, response) {
if(error) deferred.reject(error);
if(response) deferred.resolve(response);
});
// console.log(query.sql);
}
return deferred.promise;
}
/**
* Admin Login
*
* #param {*array} data
*/
function adminLogin(data){
var userData = JSON.parse(data);
connection.query('SELECT * FROM users WHERE email = "' + userData.email + '" AND user_type = "1" LIMIT 1', function(error, response) {
if(error) deferred.reject(error);
//check if user exists
if(response.length > 0){
if(passwordHash.verify(userData.password, response[0].password)){//password matching
// console.log("admin response = " + response[0]);
deferred.resolve(response[0]);
}
else{
deferred.reject('Invalid Credential');
}
}
else{
deferred.reject('Unauthorized user');
}
});
return deferred.promise
}
Now I want to know what wrong thing I am doing.
If I am hanging the node server and restarting it again then it works fine otherwise it returns same error or success response with the different credentials.
Thanks

Thanks Robert your answer was correct exactly. Thanks so much.
The soulution was to make seperate promise for each and every function.
I was using deferred = q.defer(); at the top of the page as globaly
So I have to remove it from here and put it seperately in each function.
Like
function index(){
deferred = q.defer();
....
......
return deferred.promise;
}
this was the correct solution thanks alot robert
Thanks

Related

Port Errors running node.js application

i cloned an node.js application and , to set up, i did an npm install and npm install -g nodemon , i wanted to run it locally on port 3000, so in my app.js file i added
app.listen(3000, () => console.log('Server running on port 3000!'))
and then i tried to run it by using node app.js but i am getting this errors
this is my app.js file
var express = require('express');
var engine = require('ejs-locals');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fileUpload = require('express-fileupload');
var request = require('request');
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectID;
var routes = require('./routes/index');
var testgrid = require('./routes/testgrid');
var hsdes_query = require('./routes/hsdes_query');
var find_coverage = require('./routes/find_coverage');
var url = "mongodb://127.0.0.1:27017/onegrid_int";
var config = require('./config');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('ejs', engine);
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(fileUpload());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var manual_ti_payload_template = {
"attributes": [],
"blackList": "string",
"description": "string",
"endDate": "2019-02-03T21:28:12.567Z",
"id": "string",
"itemId": "string",
"key": "string",
"name": "ascii string",
"namespace": "ascii string",
"ownerIdsid": "string",
"planningAttributes": [],
"resources": [],
"resourcesVersions": [],
"startDate": "2019-02-03T21:28:12.567Z",
"type": "manualitem",
"version": 0,
"whiteList": "string"
}
app.post('/updategtaproc', function(req, res){
console.log("updategtaproc", req.body)
var username = "Lab_FMVPOSumit";
var password = "bdzxl12$";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
request.post( {
url : 'http://gta.intel.com/procedures/api/v1/procedures/' + req.body.name,
headers : {
"Authorization" : auth
},
json: {"description": req.body.description, "steps":req.body.steps}
}, function(error, response, body) {
console.log("updategtaproc response",error, body);
res.send(body)
});
});
app.post('/createnupdategtaproc', function(req, res){
console.log("createnupdategtaproc", req.body)
var username = "Lab_FMVPOSumit";
var password = "bdzxl12$";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var ti_payload = Object.assign({}, manual_ti_payload_template);
ti_payload.name = req.body.expected;
ti_payload.description = req.body.description;
ti_payload.ownerIdsid = username;
ti_payload.namespace = "vtt-gve-gqe"
console.log(ti_payload)
request.post( {
url : 'https://gta.intel.com/api/tp/v1/testitems',
headers : {
"Authorization" : auth
},
json: ti_payload,
}, function(error, response, body) {
console.log("updategtaproc response",error, body);
if (body && body.itemId) {
console.log("Test case created successfully", body.itemId);
var itemId = body.itemId;
request.post( {
url : 'http://gta.intel.com/procedures/api/v1/procedures/' + body.itemId,
headers : {
"Authorization" : auth
},
json: {"description": req.body.description, "steps":req.body.steps}
}, function(error, response, body) {
console.log("updategtaproc response",error, body);
console.log("Test Procedure Uploaded Successfully");
body['itemId'] = itemId
res.send(body)
});
} else {
console.log("Failed to Create Test Case");
res.send({"message":"Failed To Create Test Case"})
}
});
});
app.post('/getgriditems/:id', function(req, res){
MongoClient.connect(url, function(err, db) {
if(err){
console.log('onegrid_int//getgriditems/:id unable to connect to mongodb')
}
else
{
var collection_name = (req.params.id).toLowerCase() + "-" + "griditems"
var collection = db.collection(collection_name);
var objectIdArr = [];
for (var key in req.body) {
if (req.body.hasOwnProperty(key)) {
item = req.body[key];
try {
objectIdArr.push(ObjectId(String(item)));
}
catch (err)
{
// Invalid Object ID
}
}
}
collection.find({"_id" : {"$in" : objectIdArr }}).toArray(function(err, griditems) {
if(err)
{
console.log('onegrid//getgriditems/:id unable to get grid items')
}
else
{
var paths = []
for ( var r in griditems){
//console.log('path :', result[r]['path'])
paths.push(griditems[r]['path'].join(",") + ',' + griditems[r]['testItem']['itemId'])
}
console.log("paths", paths)
var global_result_collection = db.collection("onegrid-global-results");
global_result_collection.find({"full_path" : {"$in" : paths }}).toArray(function(err, results) {
if(err)
{
console.log('onegrid//getgriditems/:id unable to get test results')
}
else
{
var metadata = {}
metadata['griditems'] = griditems
metadata['results'] = results
console.log("test_results", results)
res.send(metadata);
db.close();
}
});
}
});
}
});
});
app.post('/get_all_tags', function(req, res){
MongoClient.connect(url, function(err, db) {
if(err){
console.log('onegrid/manual_tests/unable to connect to mongodb')
}
else
{
var collection = db.collection('user_tags');
collection.find().toArray(function(err, tags) {
if(err)
{
console.log('onegrid/manual_tests/error getting documents from collection')
}
else
{
var tag_type_ar = tags.map(a => a.type_tag);
//console.log('onegrid/manual_tests/number_of_docs/', tests.length)
//console.log('onegrid/manual_tests/tags/', tags_name)
res.send(tag_type_ar);
db.close();
}
});
}
});
});
app.post('/getsettags', function(req, res){
//console.log('body: ' + JSON.stringify(req.body));
var url = "mongodb://127.0.0.1:27017/onegrid";
MongoClient.connect(url, function(err, db) {
if(err){
console.log('onegrid/getsettags/unable to connect to mongodb')
}
else
{
var objectId = ObjectId(req.body.id);
var collection = db.collection('gve_manual_testitems');
if(req.body.op == 'set_add') {
collection.findOne({ _id : objectId }, function(err, result) {
if(err)
{
console.log('onegrid/getsettags/set/unable to get test item id', objectId)
}
else
{
//console.log('onegrid/getsettags/set/test item id current tag value', result['tags'])
if(result['tags'] && result['tags'].indexOf(req.body.newtag) != -1) {
res.send(result);
db.close();
}
else {
if(result['tags'])
{
result['tags'].push(req.body.newtag)
}
else
{
result['tags'] = [req.body.newtag];
}
collection.updateOne({ _id : objectId }, { $set: { "tags" : result['tags'] } }, function(err, result) {
if(err)
{
console.log('onegrid/getsettags/set/unable to set tags')
}
else
{
console.log('tags added successfully to test item');
var test_tags = result;
if(!req.body.skip_tag_source_update) {
var user_tags = db.collection('user_tags');
var type_tag = req.body.newtag;
var type = req.body.newtag.split(":")[0]
var tag = req.body.newtag.split(":")[1]
var tag_obj = {'type':type, 'tag': tag, 'type_tag' : type_tag}
user_tags.insertOne(tag_obj, function(err, result) {
if(err)
{
console.log('onegrid/getsettags/set unable to add to user tag')
}
else
{
console.log('tags added to user_tags')
res.send(test_tags);
db.close();
}
});
}
else
{
res.send(test_tags);
db.close();
}
//var newtag = req.body.newtag;
//var tag_type = newtag.split(":")[0];
//var tag_name = newtag.split(":")[1];
//console.log(tag_type,tag_name)
}
});
}
}
});
}
if(req.body.op == 'set_remove') {
collection.findOne({ _id : objectId }, function(err, result) {
if(err)
{
console.log('onegrid/getsettags/set/unable to get test item id', objectId)
}
else
{
//console.log('onegrid/getsettags/set/test item id current tag value', result['tags'])
result['tags'].splice(result['tags'].indexOf(req.body.newtag),1);
//console.log('onegrid/getsettags/set/test item id current tag value', result['tags'])
collection.updateOne({ _id : objectId }, { $set: { "tags" : result['tags'] } }, function(err, result) {
if(err)
{
console.log('onegrid/getsettags/set/unable to set tags')
}
else
{
console.log('tags removed successfully')
//collection = db.collection('user_tags');
//var newtag = req.body.newtag;
//var tag_type = newtag.split(":")[0];
//var tag_name = newtag.split(":")[1];
//console.log(tag_type,tag_name)
res.send(result);
db.close();
}
});
}
});
}
if(req.body.op == 'get') {
collection.findOne({ _id : objectId }, function(err, result) {
if(err)
{
console.log('onegrid/manual_tests/unable to get tags')
}
else
{
//console.log('tags retrieved successfully ', result['tags'])
if(result['tags'])
res.send(result['tags'].join(","));
else
res.send("");
db.close();
}
});
}
}
});
});
app.post('/gettestprocs/:id', function(req, res){
console.log('gettestprocs body: ' + (req.body.itemId));
//var url = "mongodb://127.0.0.1:27017/og1";
MongoClient.connect(url, function(err, db) {
if(err){
console.log('onegrid/manual_tests/unable to connect to mongodb')
}
else
{
var collection_name = (req.params.id).toLowerCase() + "-" + "testprocs"
var collection = db.collection(collection_name);
collection.findOne({ "id" : req.body.itemId },function(err, result) {
if(err)
{
console.log('onegrid/manual_tests/unable to get tags')
}
else
{
console.log('test proc:', result)
res.send(result);
db.close();
}
});
}
});
});
app.post('/gettestprocsbyitemid', function(req, res){
//console.log('gettestprocs body: ' + (req.body));
var url = "mongodb://127.0.0.1:27017/onegrid_int";
MongoClient.connect(url, function(err, db) {
if(err){
console.log('onegrid/manual_tests/unable to connect to mongodb')
}
else
{
console.log(req.body)
/*if(String(req.body.grid_type) == "MANUAL"){
collection_name = "n_gve_manual_testprocs"
} else if(String(req.body.grid_type) == "OLD_MANUAL") {
collection_name = "gve_manual_testprocs"
} else if(String(req.body.grid_type) == "SURFACE") {
collection_name = "gve_surface_testprocs"
}
else if(String(req.body.grid_type) == "AUTO") {
}*/
//var tp = testplans.filter(function(x){return x.itemId == req.params.id})[0];
var collection_name = (req.body.testplan_id).toLowerCase() + "-" + "testprocs"
var collection = db.collection(collection_name);
collection.findOne({"id" : String(req.body.proc_id) },function(err, result) {
if(err)
{
console.log('onegrid/manual_tests/unable to get tags')
}
else
{
console.log('test proc:', result)
res.send(result);
db.close();
}
});
}
});
});
app.use('/', routes);
app.use('/testgrid', testgrid);
app.use('/hsdes_query', hsdes_query);
app.use('/find_coverage', find_coverage);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.listen(3000, () => console.log('Server running on port 3000!'))
module.exports = app;
another app.js in C:\projects\New Project\onegrid\web\node_modules\ejs-locals\example
var express = require('express')
, engine = require('../')
, app = express();
// use ejs-locals for all ejs templates:
app.engine('ejs', engine);
app.set('views',__dirname + '/views');
app.set('view engine', 'ejs'); // so you can render('index')
// render 'index' into 'boilerplate':
app.get('/',function(req,res,next){
res.render('index', { what: 'best', who: 'me', muppets: [ 'Kermit', 'Fozzie', 'Gonzo' ] });
});
app.get('/foo.js', function(req,res,next){
res.sendfile('foo.js');
})
app.get('/foo.css', function(req,res,next){
res.sendfile('foo.css');
})
app.listen(3000);
what am i doing wrong , i just want to run it on localhost 3000. ?
Your terminal shows you running node server.js but your file is called app.js.

Everyauth is not working in express 4

I'm using nodejs, express 4 and everyauth for social network authentication. I'm having some problem where I click Accept from Google and and redirects back to my / I get
_http_outgoing.js:335
throw new Error('Can\'t set headers after they are sent.');
I'm using electrolyte as a DI as well but I don't think that would be an issue. Here's my code
index.js
var express = require('express'),
http = require('http'),
bootable = require('bootable');
var app = bootable(express());
app.phase(bootable.initializers('etc/init', app));
app.phase(bootable.routes(__dirname + '/routes.js', app));
app.phase(function listen(done) {
http.createServer(app).listen(process.env.PORT || 3000, function(err) {
if (err) { return done(err); }
var addr = this.address();
console.log('server listening on http://' + addr.address + ':' + addr.port);
done();
});
});
module.exports = app;
routes.js
var IoC = require('electrolyte');
module.exports = function routes() {
this.get('/', IoC.create('handlers/homepage'));
this.get('/api/foursquare', IoC.create('handlers/api/foursquare'));
//this.get('/auth/google/callback', IoC.create('handlers/auth/google_auth_callback'));
}
handlers/homepage
exports = module.exports = function() {
function render(req, res, next) {
res.render('index');
};
return [render];
};
google.js
var everyauth = require('everyauth'),
GoogleUser = require('../../app/models/google_user'),
mongoose = require('../../app/db/mongo');
require('dotenv').load();
module.exports = function() {
everyauth.google
.appId(process.env.GOOGLE_CLIENT_ID)
.appSecret(process.env.GOOGLE_CLIENT_SECRET)
.scope('https://www.googleapis.com/auth/plus.login') // What you want access to
.handleAuthCallbackError( function (req, res) {
// If a user denies your app, Google will redirect the user to
// /auth/facebook/callback?error=access_denied
// This configurable route handler defines how you want to respond to
// that.
// If you do not configure this, everyauth renders a default fallback
// view notifying the user that their authentication failed and why.
})
.findOrCreateUser( function (session, accessToken, accessTokenExtra, googleUserMetadata) {
console.log('come back from google');
console.log(session);
// find or create user logic goes here
// Return a user or Promise that promises a user
// Promises are created via
// var promise = this.Promise();
/*
var googleUser = new GoogleUser(mongoose);
var johndoe = new googleUser({
accessToken: 'accessToken',
expires: new Date(),
refreshToken: 'refreshToken',
email: 'john#doe.com',
createdAt: new Date()
});
var promise = this.Promise();
promise.resolve(johndoe);
return promise;
*/
}).redirectPath('/');
};
mongo.js
var mongoose = require('mongoose')
require('dotenv').load();
var uristring = process.env.MONGOLAB_URI;
mongoose.connect(uristring, function (err, res) {
if (err) {
console.log ('ERROR connecting to: ' + uristring + '. ' + err);
} else {
console.log ('Succeeded connected to: ' + uristring);
}
});
exports = module.exports = mongoose
You will get Can't set headers after they are sent. if your code is like this
if (err) {
res.send(err);
}
else if(!user) {
res.send(info);
}
res.send(user);
In the above code, if user is undefined it sends the info as response and it again comes to next statement i.e res.send(user);. So it cannot set headers to the response which is already sent.
You can prevent this by
if (err) {
res.send(err);
}
else if(!user) {
res.send(info);
}
else {
res.send(user);
}
or
if (err) {
return res.send(err);
}
else if(!user) {
return res.send(info);
}
return res.send(user);

MEANJS mongoose model in request object

I've just started with meanjs. When I've taken a look at it server side module user profile controller, I find that mongoose model User is available in req object.
From where it has got added in req object?
Refer the code below, I wants to understand var user = req.user;, How user is added in req object?
'use strict';
/**
* Module dependencies.
*/
var _ = require('lodash'),
errorHandler = require('../errors.server.controller.js'),
mongoose = require('mongoose'),
passport = require('passport'),
User = mongoose.model('User');
/**
* Update user details
*/
exports.update = function(req, res) {
// Init Variables
var user = req.user;
var message = null;
// For security measurement we remove the roles from the req.body object
delete req.body.roles;
if (user) {
// Merge existing user
user = _.extend(user, req.body);
user.updated = Date.now();
user.displayName = user.firstName + ' ' + user.lastName;
user.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
req.login(user, function(err) {
if (err) {
res.status(400).send(err);
} else {
res.json(user);
}
});
}
});
} else {
res.status(400).send({
message: 'User is not signed in'
});
}
};
/**
* Send User
*/
exports.me = function(req, res) {
res.json(req.user || null);
};
In meanjs app.param([name], callback) is used, whenever a route with some id like articeId in parameter is accessed, app.param([name], callback) middleware is triggered. In meanjs it sets req.article like this.
app.param('articleId', articles.articleByID);
and in articleByID
exports.articleByID = function(req, res, next, id) {
if (!mongoose.Types.ObjectId.isValid(id)) {
return res.status(400).send({
message: 'Article is invalid'
});
}
Article.findById(id).populate('user', 'displayName').exec(function(err, article) {
if (err) return next(err);
if (!article) {
return res.status(404).send({
message: errorHandler.getErrorMessage(err)
});
}
req.article = article;
next();
});
};
more on app.param see http://expressjs.com/api.html#app.param
Passport’s authentication middleware sets req.user upon successful login.
See http://passportjs.org/guide/authenticate/.

child_process.fork - process.send does not return message

I am running this script with node child_process.fork api.
That is my express application script, from where I start my application:
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, http = require('http')
, path = require('path');
var app = express();
//database connection
var connection = require('express-myconnection');
var mysql = require('mysql');
//all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
//development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.use(
connection(mysql,{
host: 'localhost',
user: 'root',
password : '',
port : 3306, //port mysql
database:'test-db'
},'pool')
);
//routes
//app.get('/', routes.index);
app.get('/', routes.list);
app.use(app.router);
//run script
var cp = require('child_process');
var child = cp.fork('dataGrabber/pusherMysql');
child.on('message', function(m) {
// Receive results from child process
console.log('received: ' + m);
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port') + ' http://localhost:' + app.get('port'));
});
That`s the part where I run my script:
//run script
var cp = require('child_process');
var child = cp.fork('dataGrabber/pusherAPI');
child.on('message', function(m) {
// Receive results from child process
console.log('received: ' + m);
});
As you can see I load my script and want to receive a message from the child.
That is my pusherAPI.js script:
var mysql = require('mysql');
var Pusher = require('pusher-client');
/**
* connect with mysql db
*/
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
database : 'test-db',
port : '3306',
password : ''
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
//connect with the server
var API_KEY = 'cb65d0a7a72cd94adf1f';
var pusher = new Pusher(API_KEY, {
encrypted: true
});
var channel = pusher.subscribe("ticker.160");
channel.bind("message", function(data) {
console.log(data);
this.data = data;
/**
* save data to db
*/
var trade = {
timestamp : data.trade.timestamp,
price : data.trade.topbuy.price,
};
var query = connection.query('INSERT INTO trades SET ?', trade, function(err, result) {
if (err) {
connection.rollback(function() {
throw err;
});
}
//push message back to the app.js
process.on('message', function(m) {
// Pass results back to parent process
m = "insert happened";
process.send(m);
});
connection.commit(function(err) {
if (err) {
connection.rollback(function() {
throw err;
});
}
});
});
console.log(query.sql);
});
I want to send a message back to my app.js, whenever an insertion happened to my sql db
My script starts and runs my queries. However, process.send(m); does not send anything back.
Any recommendations what I am doing wrong?
I appreciate your answer!
Update
When changing my pusherAPI.js to, I get nothing back in the console.
var channel = pusher.subscribe("ticker.160");
process.on('insert_message', function(m) {
channel.bind("message", function(data) {
console.log(data);
this.data = data;
/**
* save data to db
*/
var trade = {
timestamp : data.trade.timestamp,
price : data.trade.topbuy.price,
};
var query = connection.query('INSERT INTO trades SET ?', trade, function(err, result) {
if (err) {
connection.rollback(function() {
throw err;
});
}
//push message back to the app.js
// Pass results back to parent process
m = "insert happened";
process.send(m);
connection.commit(function(err) {
if (err) {
connection.rollback(function() {
throw err;
});
}
});
});
console.log(query.sql);
});
});
In my app.js I changed my code like that:
//run script
var cp = require('child_process');
var child = cp.fork('dataGrabber/pusherAPI');
child.on('insert_message', function(m) {
// Receive results from child process
console.log('received: ' + m);
});
Move your process.send(m); outside of the message event handler. Otherwise you're adding a new message event handler for every query and those event handlers only fire when the parent process sends it a message. Example:
var channel = pusher.subscribe("ticker.160");
channel.bind("message", function(data) {
this.data = data;
/**
* save data to db
*/
var trade = {
timestamp : data.trade.timestamp,
price : data.trade.topbuy.price,
};
var query = connection.query('INSERT INTO trades SET ?',
trade,
function(err, result) {
if (err) {
connection.rollback(function() {
throw err;
});
return;
}
//push message back to the app.js
m = "insert happened";
process.send(m);
connection.commit(function(err) {
if (err) {
connection.rollback(function() {
throw err;
});
}
});
});
});

req.session undefined only with AJAX

So, I've been struggling with these for a couple of hours now. The session won't get sent to server when I use AJAX to POST something to the server, but it works fine without AJAX, like clicking links, logout, etc and this is makes me pulling my hair in frustration. Anyway, these are my codes:
var express = require('express'), // express 4
mongoskin = require('mongoskin'),
Busboy = require('busboy'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
mailer = require('nodemailer'),
compress = require('compression'),
morgan = require('morgan'),
ect = require('ect'),
suspend = require('suspend'),
MongoStore = require('connect-mongo')(session);
app.use(compress());
app.engine('.ect', renderer.render);
app.set('env', 'development');
app.use(express.static(__dirname + '/public'));
app.use(cookieParser());
app.use('/admin', session({
secret : 'qlauwork secret yo',
name : 'qlauworks.sess',
proxy : true,
rolling : true,
cookie : {
maxAge : 1000 * 60 * 60 * 6
},
store : new MongoStore({
db : 'qlauworks',
auto_reconnect : true,
defaultExpirationTime : 1000 * 60 * 60 * 6
}),
unset : 'destroy'
}));
// ... etc etc
app.post('/admin/login', function (req, res) {
var msg = {};
var busboy = new Busboy({ headers : req.headers });
busboy.on('field', function (fieldName, val) {
msg[fieldName] = val;
});
busboy.on('finish', function () {
suspend.run(function * () {
msg.password = crypto.createHash('whirlpool').update(SALT).update(msg.password).digest('hex');
var user = yield db.users.findOne({ username : msg.username, password : msg.password }, suspend.resume());
if (!user) {
return res.json({ error : 'Wrong username or password' });
}
// create session token
var token = yield crypto.randomBytes(32, suspend.resume());
token = token.toString('hex');
yield db.users.update({ username : msg.username }, { $set : { token : token } }, { upsert : true }, suspend.resume());
req.session.token = token;
res.redirect('/admin/forms');
}, function (err) {
if (err) {
console.log('login: ', err);
res.send('Server error');
}
});
});
req.pipe(busboy);
});
// this is the logout and forms, works just fine
app.get('/admin/logout', auth, function (req, res) {
suspend.run(function * () {
var token = req.session.token;
yield db.users.update({ token : token }, { $unset : { token : true } }, suspend.resume());
delete req.session.token;
req.session.destroy(function (err) {
if (!err) {
res.clearCookie('qlauworks.sess', { path : '/' });
res.redirect('/admin');
}
});
}, function (err) {
if (err) {
console.log('logout: ', err);
res.json({ error : 'Server error' });
}
});
});
app.get('/admin/forms', auth, function (req, res) {
res.send(formPage);
});
// and this is the auth middleware, could logout and moving around the admin page
// but req.session always undefined if comes from an AJAX request
function auth (req, res, next) {
suspend.run(function * () {
console.log(req.session);
console.log('=====================================================')
if (!req.session.token) {
return res.json({ error : 'Invalid token' });
}
var user = yield db.users.findOne({ token : req.session.token }, suspend.resume());
if (!user.username) {
return res.json({ error : 'Invalid token' });
}
next();
}, function (err) {
if (err) {
console.log('auth: ', err);
res.json({ error : 'Server error' });
}
});
}
and this is the client side
$.post('/api/item/new', elem, function (rep) {
thisForm.find('input[type="submit"]').attr('disabled', false);
if (rep.error) {
$('#alert-multi').removeClass('success').addClass('alert').text(rep.error);
} else {
$('#alert-multi').removeClass('alert').addClass('success').text('Success');
$('input[type="reset"]').click();
for (var i = 0; i < len; i++) {
$('#preview-multi' + i).attr('src', '');
$('#multi' + i).attr('data-image-src', '');
}
}
});
So, how do I solve this?
It looks like you mounted the session middleware on /admin but you're trying to call /api/item/view.
That won't work as using express.use(path, middleware) will invoke middleware only for requests whose req.url contains path.
Either mount the session middleware on / (by not using path parameter - simple express.use(middleware) will do), or change your ajax url to start with /admin (probably not something you want to do).

Categories

Resources