I am currently trying to test an application with Mocha and Chai but I am having difficulties in connecting one of the modules to the test.
Here is my test case:
"use strict";
var chai = require('chai');
var expect = require("chai").expect;
var helloWorld = require("../routes");
var mongoose = require("mongoose");
var app = require("../app");
var application = require("../routes");
describe('helloWorld', function () {
it('Mongo Module extended', function () {
expect(helloWorld()).equal('Mongo Module Extended');
});
});
describe('application', function application(app){
it('connects properly', function(done) {
expect(application(app))
.request('http://localhost:80')
.get('/')
.end(function(err, res) {
expect(res).to.have.status(200);
done(); // <= Call done to signal callback end
});
});
});
and here is the file I am currently trying to test:
var passport = require('passport');
var Account = require('./models/account');
var path = require('path');
var mongojs = require('mongojs');
var dbx = mongojs('test', ['logs']);
var fs = require('fs');
var dbc = mongojs('test', ['accounts']);
function helloWorld() {
return 'Mongo Module Extended';
}
module.exports = helloWorld;
function application(app) {
app.get('/',
function(req, res){
res.sendFile('login.html', {root: __dirname});
});
app.get('/login',
function(req, res){
res.sendFile(path.join(__dirname + '/login.html'));
});
app.get('/index', isLoggedIn,
function(req, res){
req.flash('info', 'Flash is back!')
res.sendFile(path.join(__dirname + '/views/index.html'));
});
app.get('/', isLoggedIn,
function(req, res){
res.sendFile(path.join(__dirname + '/login.html'));
});
app.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.json({success:false, message: "Wrong Username or Password"}); //sends json message to the Front end jQuery function
}
req.logIn(user, function(err) {
if (err) {
return next(err);
}
res.json({success:true, redirectTo: '/index', message: "You are logged-in."}); //sends json message to the Front end jQuery function
/* Add username and time of login to the collection in MongoDB */
dbc.accounts.findOne(function(err, info){
var users = info.username; //Gets the logging username from the collection
var date = new Date().toLocaleDateString(); // generates a new date.
console.log(date);
console.log(date +" "+ "date");
var stamp = {name: users, time:date}; // object to hold both variables.
//toLocaleDateString('en-GB')
dbx.logs.insert(stamp, function(err, result){ //query to insert one inside the "logs" collection.
if(err) { throw err; }else{console.log("added" + JSON.stringify(stamp));}
});
});
/* END of Collection Logging Method */
});
})(req, res, next);
});
app.get('/logout',
function(req, res){
req.logout();
res.redirect('/login');
});
function isLoggedIn(req, res, next) {
//console.log('here is Authenticated', req.isAuthenticated()) //prints out 'here is Authenticated' if the Passport login is successful
if (req.isAuthenticated()){
console.log('here is Authenticated');
return next();
}else{
console.log("you cannot access the routes without being logged in!");
}
}
module.exports = application;
I keep receiving this error:
TypeError: expect(...).request is not a function
which I guess is referencing the first get request I am trying to make in my application file:
app.get('/',
function(req, res){
res.sendFile('login.html', {root: __dirname});
});
At this point I am not really sure how to fix this. I know that my error is in the way that I am trying to test the get request but I cannot seem to bypass it.
How can I correct my code so I can reference the methodsGET and POST methods from module.exports = application; correctly?
Chai on its own doesn't support testing of http routes, you need chai-http to do just that.
You could see the link for more: https://scotch.io/tutorials/test-a-node-restful-api-with-mocha-and-chai
Related
I have a Express server resolving GET /companies/:id/populate/. Now, I would like to setup GET /companies/populate/ (without the :id). However, I can't make this route to work. If I try, for example, GET /companies/all/populate/, it works, so it seems the pattern for an Express route is path/:key/path/:key.
Is this true? Thanks!
Edit: Adding code.
server.js
'use strict';
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
var mongoUri = 'mongodb://localhost:27017';
mongoose.connect(mongoUri);
var db = mongoose.connection;
db.on('error', function() {
throw new Error('Unable to connect to database at' + mongoUri);
});
// runs Express
var app = express();
// uses Cors
app.use(cors());
// uses bodyParser
app.use(bodyParser.json());
// requires Mongo models
require('./models');
// includes routes.js, passing the object 'app'
require('./routes')(app);
// listens for connections on port 3000
app.listen(3000, function() {
console.log("Express started on Port 3000");
});
routes.js
module.exports = function(app) {
// thumbs up if everything is working
app.get('/', function(req, res, next) {
res.send('👍');
console.log('Server Running');
res.end();
});
// companies
var companies = require('./controllers/companies');
app.get('/companies', companies.findAll);
app.get('/companies/:id', companies.findById);
app.get('/companies/:id/populate', companies.populate);
app.get('/companies/populate', companies.populateAll);
app.post('/companies', companies.add);
app.patch('/companies/:id', companies.patch);
app.delete('/companies/:id', companies.delete);
};
/controllers/companies.js
var mongoose = require('mongoose');
Company = mongoose.model('Company');
// GET /companies
// status: works, needs error handling
exports.findAll = function(req, res) {
Company.find({}, function(err, results) {
return res.send(results);
});
};
// GET /companies/:id
// status: works, needs to check error handling
exports.findById = function(req, res) {
var id = req.params.id;
Company.findById(id, function(err, results) {
if (results) res.send(results);
else res.send(204);
});
};
// POST /companies
// status: works, needs error handling
exports.add = function(req, res) {
Company.create(req.body, function(err, results) {
if (err) {
return console.log(err)
} else {
console.log('company created');
}
return res.send(results);
});
};
// PATCH /companies/:id
// status: works, needs error handling
exports.patch = function(req, res) {
var id = req.params.id;
var data = req.body;
Company.update( { '_id' : id }, data, function(err, numAffected) {
if (err) return console.log(err);
return res.send(200);
});
};
// DELETE /companies/:id
// status: works, needs error handling, make sure that we are sending a 204 error on delete
exports.delete = function(req, res) {
var id = req.params.id;
Company.remove({ '_id': id }, function(results) {
console.log('deleted ' + id); // tester
return res.send(results);
});
};
// GET /companies/:id/populate
exports.populate = function(req, res) {
var id = req.params.id;
Company
.findOne({ _id: id })
.populate('contacts country')
.exec(function (err, results) {
if (err) return handleError(err);
else res.send(results);
});
};
// GET /companies/populate
exports.populateAll = function(req, res) {
Company
.find({})
.populate('contacts country')
.exec(function (err, results) {
if (err) return handleError(err);
else res.send(results);
});
};
I am very new to node js. I have made an application, where when admin logs in, it is showing 'Cannot POST /userslist', but once I refresh the page, it is fetching the userslist, following is the routing code for admin-
admin.js-
module.exports = function(app)
{
app.get('/adminedit', function (req, res) {
res.render('adminedit', { });
});
app.get('/userslist', function (req, res) {
res.render('userslist', { });
});
}
i think the best way to achieve your goal (using express) is:
create a single service (called for example listUsers) in this way:
var express = require('express');
var router = express.Router();
router.post('/', function(req, res, next) {
User.find(function (err, users) {
if(err) return res.json({success: false, message: err});
res.json({success: true, userlist: users});
)};
});
module.exports = router;
then you can use this service in app.js in this way:
var userListService = require('./routes/listUsers');
app.use('/listUsers', userListService);
at this point if you try to call in POST /listUsers, everything should work fine.
I'm a newbie in node.js and I'm trying to redirect all the routes after localhost:4000/ if it is not logged in. And it gives me error with "Too many redirects"...
my code that using app.get in app.js
app.get('*', loggedInCheck);
and below code is loggedInCheck function that I've written,
function loggedInCheck(req, res, next) {
if (req.isAuthenticated()){
res.redirect('/status');
}else{
console.log("Please Log in to access to this webpage");
res.redirect('/login');
}
}
However, it keeps giving me an error as "Too many redirects" and doesn't go through login page because it is not authenticated yet.
What is my problem here? and how can I fix this....?
Can anybody help me out here??
Just in case, I'll put my whole code from app.js
app.js
var io = require('socket.io');
var express = require('express');
var app = express();
var redis = require('redis');
var sys = require('util');
var fs = require('fs');
//Added for connecting login session
var http = require('http');
var server = http.createServer(app);
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var session = require('express-session');
var flash = require('connect-flash');
var async = require('async');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
//Connecting Database (MongoDB)
mongoose.connect("my private mongoDB address");
var db = mongoose.connection;
db.once("open",function () {
console.log("DB connected!");
});
db.on("error",function (err) {
console.log("DB ERROR :", err);
});
//Setting bcrypt for password.
var bcrypt = require("bcrypt-nodejs");
//Setting userSchema for MongoDB.
var userSchema = mongoose.Schema({
email: {type:String, required:true, unique:true},
password: {type:String, required:true},
createdAt: {type:Date, default:Date.now}
});
userSchema.pre("save", function (next){
var user = this;
if(!user.isModified("password")){
return next();
} else {
user.password = bcrypt.hashSync(user.password);
return next();
}
});
//setting bcrypt for password.
userSchema.methods.authenticate = function (password) {
var user = this;
return bcrypt.compareSync(password,user.password);
};
//Setting User as userSchema.
var User = mongoose.model('user',userSchema);
io = io.listen(server);
//Setting middleware for login format.
app.set("view engine", 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(methodOverride("_method"));
app.use(flash());
app.use(session({secret:'MySecret', resave: true, saveUninitialized: true}));
app.use(passport.initialize());
app.use(passport.session());
//Initializing passport.
passport.serializeUser(function(user, done) {
//console.log('serializeUser()', user);
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
//console.log('deserializeUser()', user);
User.findById(id, function(err, user) {
done(err, user);
});
});
var global_username = ''; //Global variable for username to put in the address
//Initializing passport-local strategy.
var LocalStrategy = require('passport-local').Strategy;
passport.use('local-login',
new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(req, email, password, done) {
User.findOne({ 'email' : email }, function(err, user) {
if (err) return done(err);
if (!user){
req.flash("email", req.body.email);
return done(null, false, req.flash('loginError', 'No user found.'));
}
if (!user.authenticate(password)){
req.flash("email", req.body.email);
return done(null, false, req.flash('loginError', 'Password does not Match.'));
}
var email_address = req.body.email;
var username = email_address.substring(0, email_address.lastIndexOf("#"));
global_username = username;
return done(null, user);
});
}
)
);
//Check whether it is logged in or not.
//If it is not logged in(Session is out), it goes to login page
//If it is logged in(Session is still on), it goes directly to status.html
app.get('*', loggedInCheck);
app.get('/login', function (req,res) {
res.render('login/login',{email:req.flash("email")[0], loginError:req.flash('loginError')});
});
//Accessing to MongoDB to check to login or not
app.post('/login',
function (req,res,next){
next();
}, passport.authenticate('local-login', {
successRedirect : '/status',
failureRedirect : '/login',
failureFlash : true
})
);
//Logging out
app.get('/logout', function(req, res) {
req.logout();
console.log("Logging out the account!");
res.redirect('/login');
});
//Creating new account
app.get('/users/new', function(req,res){
res.render('users/new', {
formData: req.flash('formData')[0],
emailError: req.flash('emailError')[0],
passwordError: req.flash('passwordError')[0]
}
);
});
//If creating an account is successed, then goes back to login page.
app.post('/users', checkUserRegValidation, function(req,res,next){
User.create(req.body.user, function (err,user) {
if(err) return res.json({success:false, message:err});
res.redirect('/login');
});
});
//Calling status.html
app.get('/status', isLoggedIn, function(req, res){
res.redirect('/status.html?channel=' + global_username);
});
//Calling Topology_view html
app.get('/topology', isLoggedIn, function(req, res){
console.log("Accessing to topology_view");
res.redirect('topology.html?channel=' + global_username);
});
//functions
//Check whether session is still on or not.
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()){
console.log("Authenticated");
return next();
}else{
console.log("Unauthorized Attempt");
res.redirect('/login');
}
}
//Initial checking whether session is on or not.
function loggedInCheck(req, res, next) {
if (req.isAuthenticated()){
res.redirect('/status');
}else{
console.log("Please Log in to access to this webpage");
res.redirect('/login');
}
}
//Checking whether email is already in the database or not in sign up.
//If email is already in the database, it gives error message.
function checkUserRegValidation(req, res, next) {
var isValid = true;
async.waterfall(
[function(callback) {
User.findOne({email: req.body.user.email, _id: {$ne: mongoose.Types.ObjectId(req.params.id)}},
function(err,user){
if(user){
isValid = false;
req.flash("emailError","- This email is already resistered.");
}
callback(null, isValid);
}
);
}], function(err, isValid) {
if(err) return res.json({success:"false", message:err});
if(isValid){
return next();
} else {
req.flash("formData",req.body.user);
res.redirect("back");
}
}
);
}
//handler function is for topology.html.
function handler(req,res){
fs.readFile(__dirname + '/public/topology.html', function(err,data){
if(err){
res.writeHead(500);
return res.end('Error loading topology.html');
}
res.writeHead(200);
console.log("Listening on port 3000");
res.end(data);
});
fs.readFile(__dirname + '/public/style.css', function(err,data){
if(err){
res.writeHead(500);
return res.end('Error loading topology.html');
}
res.writeHead(200);
console.log("Listening on port 3000");
res.end(data);
});
}
io.sockets.addListener('connection', function(socket){
console.log("connceted : " + socket.id);
var subscriber = redis.createClient(6379, 'localhost');
subscriber.psubscribe("*");
subscriber.on("pmessage", function(pattern, channel, message) {
//console.log(message);
socket.emit(channel, message);
});
socket.on('disconnect', function () {
console.log("disconnceted : " + socket.id);
subscriber.quit();
});
socket.on('close', function() {
console.log("close");
subscriber.quit();
});
});
server.listen(4000);
Your issue is in your loggedInCheck function. No matter what route you are on, you are checking if the user is authenticated otherwise redirect to login. So, even if your trying to get to the login page, it's gonna try and redirect again, and again forever.
app.get('*', loggedInCheck);
Isn't a good way todo it. You should have some sort of function that makes sure your not trying to go to a zone that is okay for non-users. Maybe something like this:
app.get('*', function(req, res, next){
if(req.url != '/login'){
loggedInCheck(req, res, next);
}else{
next();
}
});
I have a middleware setup in node to perform a task and call next upon success or failure. The task is called after an initial promise block runs. It is called in the .then function:
var Q = require('q');
var dataPromise = getCustomerId();
dataPromise
.then(function(data) {
getGUID(req, res, next);
}, function(error) {
console.log('Failure...', error);
});
};
The server hangs though because the (req,res,next) parameters are all undefined when in the context of the .then function.
Here is getCustomerId function:
var getCustomerId = function() {
var getCustomerIdOptions = {
options...
};
var deferred = Q.defer();
request(getCustomerIdOptions, function(err,resp,body){
if(err){
deferred.reject(err);
console.log(err);
return;
}else{
deferred.resolve(body);
}
});
return deferred.promise;
};
What would be the correct way to pass these parameters to the function called in the .then block?
EDIT:
The (req,res,next) parameters are from the outer function and are accessible when getGUID(req,res,next) is called outside of the .then() block.
var assureGUID = function(req, res, next) {
if(app.locals.guid){
next();
return;
}
var dataPromise = getCustomerId();
dataPromise
.then(function(data) {
getGUID(req, res, next)
}, function(error) {
console.log('Failure...', error);
}).;
};
Not sure what you are trying to do exactly, but you can call your promise function inside a express common middleware function like the next sample.
var express = require('express');
var $q = require('q');
var request = require('request');
var app = express();
// Middleware 1
app.use( function(req, res, next) {
console.log('i\'m the first middleware');
getCustomerId().then( function(body) {
console.log('response body', body);
return next();
},
function(err) {
console.log('Error on middlware 1: ', err);
});
});
// Middleware 2
app.use( function(req, res, next) {
console.log('i\'m the second middleware');
return next();
});
app.get('/', function(req, res) {
res.send('hi world');
});
app.listen(3000);
// Your custom function definition
function getCustomerId() {
var deferred = $q.defer();
request('http://someurltogetjsondata/user/id', function(err, resp, body) {
if(err) return deferred.reject(err);
deferred.resolve(body);
});
return deferred.promise;
}
I hope this helps a little, good luck.
I am trying to write a code for user login authentication in express using express-session
This is my accounts.js api
.use(bodyParser.urlencoded())
.use(bodyParser.json())
.use(session({ secret: 'hcdjnxcds6cebs73ebd7e3bdb7db73e' }))
.get('/login', function (req, res) {
res.sendfile('public/login.html');
})
.post('/login', function (req, res) {
var user = {
username : req.body.username,
password : hash(req.body.password)
};
var collection = db.get('users');
collection.findOne (user, function (err, data) {
if (data) {
req.session.userId = data._id;
res.redirect('/');
} else {
res.redirect('/login');
}
});
})
.get('/logout', function (req, res) {
req.session.userId = null;
res.redirect('/');
})
.use(function (req, res, next) {
if (req.session.userId) {
var collection = db.get('users');
collection.findOne({ _id : new ObjectId(req.session.userId)}, function (err, data) {
req.user = data;
});
}
next();
});
module.exports = router;
And this is my server.js code
var express = require('express'),
api = require('./api'),
users = require('./accounts'),
app = express();
app
.use(express.static('./public'))
.use('/api', api)
.use(users)
.get('*', function (req, res) {
if (!req.user) {
res.redirect('/login');
} else {
res.sendfile(__dirname + '/public/main.html');
}
})
.listen(3000);
My problem is, in server.js, req.user is getting null value that's why i am not able to login. But in account.js req.user getting user data which is not reflecting in server.js.
Again, if in accounts.js, I am placing next() inside the if (req.session.userId) statement, I am able to get user data in server.js but it creating problem in logout.
Please help me out in this.
Your accounts.js is executing next() before your collection query returns, so it makes sense that your req.user is undefined in your middleware later on. To fix it, try this:
.use(function (req, res, next) {
if (req.session.userId) {
var collection = db.get('users');
collection.findOne({ _id : new ObjectId(req.session.userId)}, function (err, data) {
req.user = data;
next();
});
} else {
next();
}
});
As a side note, you're very much reinventing the wheel here by implementing user login yourself. I would reccommend taking take a look at passportjs for doing user login like this.