Exposing user object inside the req object - node.js

I am trying to get user object inside the req, so I can have it on all my routes. This is my setup:
app.js:
// Use the passport middleware
app.use(passport.initialize());
// load passport strategies
const localSignupStrategy = require('./server/passport/local-signup');
const localLoginStrategy = require('./server/passport/local-login');
passport.use('local-signup', localSignupStrategy);
passport.use('local-login', localLoginStrategy);
// View engine setup
app.set('views', path.join(__dirname, '/server/views'));
app.set('view engine', 'pug');
// Serve static assets normally
app.use(express.static(path.join(__dirname, '/dist')));
// Define routes
app.use('/auth', auth); //Auth controller
app.use('/api', api);
Route for Auth controller:
const express = require('express');
const router = express.Router();
const authController = require('../main/controllers/authController');
// POST /auth/signup
router.post('/signup', authController.postSignup);
// POST /auth/login
router.post('/login', authController.postLogin);
module.exports = router;
authController.postLogin
exports.postLogin = function(req, res, next) {
const validationResult = validateLoginForm(req.body);
if (!validationResult.success) {
return res.status(400).json({
success: false,
message: validationResult.message,
errors: validationResult.errors
});
}
return passport.authenticate('local-login', (err, token, userData) => {
if (err) {
if (err.name === 'IncorrectCredentialsError') {
return res.status(400).json({
success: false,
message: err.message
});
}
return res.status(400).json({
success: false,
message: 'Could not process the form.'
});
}
return res.json({
success: true,
message: 'Login success.',
token,
user: userData
});
})(req, res, next);
};
This is my normal controller route:
// GET /api/cms
router.get('/cms/', authCheck(), getCmsDataController.getCmsData);
module.exports = router;
authcheck.js
module.exports = function(roles) {
// Return middleware
return (req, res, next) => {
if (!req.headers.authorization) {
return res.status(401).end();
}
// Get the last part from a authorization header string like "bearer token-value"
const token = req.headers.authorization.split(' ')[1];
// Decode the token using a secret key-phrase
return jwt.verify(token, config.jwtSecret, (err, decoded) => {
// 401 not unauthorized
if (err) return res.status(401).end();
const userId = decoded.sub;
// Check if user exists
return User.findById(userId, (err2, user) => {
if (err2 || !user) return res.status(401).end();
req.currentLoggedUser = user;
console.log(user.role);
if (roles) {
if (roles.indexOf(user.role) > -1) return next();
else return res.status(401).end();
}
return next();
});
});
};
};
And the controller itself:
// GET /api/cms-data/
exports.getCmsData = function(req, res, next) {
return res.json({
message: 'Lets see does this thing work or not!!!'
});
};
Issue is when I reach the getCmsData controller, I would like to have a user object inside the req object. My user has some properties like role and gender, which I need access to. I have one hacky solution, but I think there is a way to do that.

Could you create a middleware function for this purpose:
function getRequestUser(req) {
// In reality you'd load from data store based on request.
return {id: 1, name: "Jim Smith"};
}
function addUserMiddleWare(req, res, next) {
req.user = getRequestUser(req);
next();
}
// Then add it to your route.
// GET /api/cms
router.get('/cms/', authCheck(), addUserMiddleWare, getCmsDataController.getCmsData);
module.exports = router;
// Or, apply to all paths on router
router.use(addUserMiddleWare);

Related

I keep getting "Login sessions require session support" when I try to use tokens

So I am following a tutorial on how to use JSON tokens and I am getting an error, it was working fine using sessions but I can't figure out why I am having trouble, it is the exact code
this is my authenticate.js file:
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const User = require("./models/user");
const JwtStrategy = require("passport-jwt").Strategy;
const ExtractJwt = require("passport-jwt").ExtractJwt;
const jwt = require("jsonwebtoken"); // used to create, sign, and verify tokens
const config = require("./config.js");
exports.local = passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
exports.getToken = function (user) {
return jwt.sign(user, config.secretKey, { expiresIn: 3600 });
}; // config.secretKey is a string of random numbers
const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = config.secretKey;
exports.jwtPassport = passport.use(
new JwtStrategy(opts, (jwt_payload, done) => {
console.log("JWT payload:", jwt_payload);
User.findOne({ _id: jwt_payload._id }, (err, user) => {
if (err) {
return done(err, false);
} else if (user) {
return done(null, user);
} else {
return done(null, false);
}
});
})
);
exports.verifyUser = passport.authenticate("jwt", { session: false });
This is my app.js file (the main file):
const createError = require("http-errors");
const express = require("express");
const path = require("path");
const logger = require("morgan");
const config = require("./config");
const indexRouter = require("./routes/index");
const usersRouter = require("./routes/users");
const mongoose = require("mongoose");
const passport = require("passport");
const url = config.mongoUrl;
const connect = mongoose.connect(url, {
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true,
});
connect.then(
() => console.log("Connected correctly to server"),
(err) => console.log(err)
);
const app = express();
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// app.use(cookieParser("12345-67890-09876-54321"));
app.use(passport.initialize());
app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use(express.static(path.join(__dirname, "public")));
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// 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;
this is the routes/users.js file (I believe the problem is here because I can sign-up (create new users) but I can't login with the same users)
const express = require("express");
const User = require("../models/user");
const passport = require("passport");
const authenticate = require("../authenticate");
const router = express.Router();
/* GET users listing. */
router.get(
"/",
function (req, res, next) {
res.send('send users')
}
);
router.post("/signup", (req, res) => {
User.register(
new User({ username: req.body.username }),
req.body.password,
(err, user) => {
if (err) {
res.statusCode = 500;
res.setHeader("Content-Type", "application/json");
res.json({ err: err });
} else {
if (req.body.firstname) {
user.firstname = req.body.firstname;
}
if (req.body.lastname) {
user.lastname = req.body.lastname;
}
user.save((err) => {
if (err) {
res.statusCode = 500;
res.setHeader("Content-Type", "application/json");
res.json({ err: err });
return;
}
passport.authenticate("local")(req, res, () => {
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.json({
success: true,
status: "Registration Successful!",
});
});
});
}
}
);
});
// I tried to add a console.log inside of the .post() route but it never reach it
router.post(
"/login",
passport.authenticate("local"),
(req, res) => {
const token = authenticate.getToken({ _id: req.user._id });
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.json({
success: true,
token: token,
status: "You are successfully logged in!",
});
}
);
router.get("/logout", (req, res, next) => {
if (req.session) {
req.session.destroy();
res.clearCookie("session-id");
res.redirect("/");
} else {
const err = new Error("You are not logged in!");
err.status = 401;
return next(err);
}
});
module.exports = router;
Basically, every time that i go to localhost:3000/users/login and send a POST request with the username and password, it tells me that I need to use express-session but I am trying to use tokens instead of session
The problem is caused when passport.authenticate('local') is called in routes/users.js file. It is a middleware that automatically calls req.login function in case correct username and password is provided.
The req.login() in turn, implements sessions in order to serialise the user in the session.
You can solve the issue by adding another parameter to passport.authenticate() as passport.authenticate('local', {session: false}. This ensures sessions are not implemented in the 'local' strategy and subsequently login can be performed.
Thanks, it helped me. You have to remove app.use(passort.session) from app.js and do
router.post('/login', passport.authenticate('local', { session: false }), (req, res) => {
var token = authenticate.getToken({ _id: req.user._id });
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({ success: true, token: token, status: 'You are successfully logged in!' });
});

Cannot destructure property '_id' of 'req.user' as it is undefined

Doesn't work the request (below) as needed, drops out into an error:
app.get('/protected', auth.isAuthenticated(User), function(req, res) {
res.send('Hoooora! Authentificated!');
});
The isAuthenticated function is called from the auth.js file:
auth.js:
const SECRET = 'secret-message';
const jwt = require('jsonwebtoken');
const { expressjwt: expressJwt } = require('express-jwt');
const compose = require('composable-middleware');
function sign(user) {
return jwt.sign({
_id: user._id,
}, SECRET, {
expiresIn: 60 * 60
});
}
function sendUnauthorized(req, res) {
console.log(req.headers.authorization);
console.log(req.user);
res.status(401).json ({ message: 'Unathorized' });
};
const validateJwt = expressJwt({
secret: SECRET,
algorithms: ['HS256'],
fail: sendUnauthorized,
getToken(req){
if(req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
return req.headers.authorization.split(' ')[1];
} else if (req.query && req.query.access_token) {
return req.query.access_token;
}
return null;
}
});
function isAuthenticated(User) {
console.log('isAuthenticated is called');
return compose()
.use(validateJwt)
.use((req, res, next) => {
// Attach user to request
const { _id } = req.user;
console.log(_id + req.user);
User.findById(_id, function(err, user) {
if (err) return next(err);
if (!user) return sendUnauthorized(req, res);
req.user = user;
console.log('Successfuly verified user by token: ');
next();
});
});
};
module.exports = {
sign,
sendUnauthorized,
isAuthenticated,
};
I get an error when the isAuthenticated function runs. And I don't figure out how to fix it:
"error":{"message":"Cannot destructure property '_id' of 'req.user' as it is undefined."
There is a suspicion that the body-parser or express is not working. Although I did yarn add body-parser and yarn add express. In the index.js file code I also added the following:
const express = require('express');
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

Why am I getting a 401 Unauthorized Error when hitting my protected endpoint at /api/protected?

I am using JWT to generate a token for access control. I can hit /api/auth/login and get back the token, however, when attempting to hit /api/protected with a GET request, I get 401 Unauthorized.
I've looked through SO and haven't found anything specific although it seems like a routine issue, maybe. I have tried moving the route around in the server.js file to see if that is the issue . I have removed the preceeding slash from the route (from /api/protected to api/protected) and using the latter I get back a bunch of html due to, I think, the app.use(express.static....
I am using Postman to test it but i'm not sure what I'm missing here. I have also made sure to set the authorization to Bearer Token in Postman.
'use strict';
const { Strategy: LocalStrategy } = require('passport-local');
// Assigns the Strategy export to the name JwtStrategy using object destructuring
const { Strategy: JwtStrategy, ExtractJwt } = require('passport-jwt');
const { User } = require('../users/models');
const { JWT_SECRET } = require('../config');
const localStrategy = new LocalStrategy((username, password, callback) => {
let user;
User.findOne({ username })
.then(_user => {
user = _user;
if (!user) {
// Return a rejected promise so we break out of the chain of .thens.
// Any errors like this will be handled in the catch block.
return Promise.reject({
reason: 'LoginError',
message: 'Incorrect username or password'
});
}
return user.validatePassword(password);
})
.then(isValid => {
if (!isValid) {
return Promise.reject({
reason: 'LoginError',
message: 'Incorrect username or password'
});
}
return callback(null, user);
})
.catch(err => {
if (err.reason === 'LoginError') {
return callback(null, false, err);
}
return callback(err, false);
});
});
const jwtStrategy = new JwtStrategy(
{
secretOrKey: JWT_SECRET,
// Look for the JWT as a Bearer auth header
jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('Bearer'),
// Only allow HS256 tokens - the same as the ones we issue
algorithms: ['HS256']
},
(payload, done) => {
done(null, payload.user);
}
);
module.exports = { localStrategy, jwtStrategy };
'use strict';
//How does order of code affect how it works?
// YES
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const morgan = require('morgan');
const passport = require('passport');
const path = require('path');
const { router: usersRouter } = require('./users');
const { router: authRouter, localStrategy, jwtStrategy } = require('./auth');
mongoose.Promise = global.Promise;
// Is this needed if dotenv is in this file also?
const { PORT, DATABASE_URL } = require('./config');
const app = express();
// Logging
app.use(morgan("common"));
// const logRequest = (req, res, next) => {
// const now = new Date();
// console.log(
// `local log - ${now.toLocaleDateString()} ${now.toLocaleTimeString()} ${req.method} ${req.url}`
// );
// next();
// }
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type,Authorization');
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE');
if (req.method === 'OPTIONS') {
return res.send(204);
}
next();
});
passport.use(localStrategy);
passport.use(jwtStrategy);
//app.use(logRequest);
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use('/api/users/', usersRouter);
app.use('/api/auth/', authRouter);
app.use("/api/items", require('./routes/api/items'));
// protected route that needs a valid JWT for access
const jwtAuth = passport.authenticate("jwt", { session: false });
// route to handle static content ie.e *.jpg
app.use(express.static(path.join(__dirname, "client", "build")));
app.get('/api/protected', jwtAuth, (req, res) => {
return res.json({
data: 'Hello World'
});
});
// have react client handle all additional routes
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "client", "build", "index.html"));
});
let server;
function runServer(DATABASE_URL, port = PORT) {
return new Promise((resolve, reject) => {
// How is DATABASE_URL used? What is the value? Is it referencing
// DATABASE_URL?
mongoose.connect(DATABASE_URL, { useNewUrlParser: true, useFindAndModify: false }, (err) => {
console.log("Success");
if (err) {
return reject(err);
}
server = app.listen(port, () => {
console.log(`Your app is listening on port ${PORT}`);
resolve();
})
.on('error', (err) => {
mongoose.disconnect();
reject(err);
});
});
});
}
function closeServer() {
return mongoose.disconnect()
.then(() => new Promise((resolve, reject) => {
console.log("Closing server");
server.close((err) => {
if (err) {
return reject(err);
}
resolve();
});
}));
}
if (require.main === module) {
runServer(DATABASE_URL)
.catch(err => console.error(err));
}
module.exports = { app, runServer, closeServer };
enter code hereI am expecting to get back a string that says "Hello World" just to make sure i'm hitting the endpoint correctly. Instead I get the 401 error, GET /api/protected HTTP/1.1" 401enter code here

Nodejs middleware always executed

I am learning NodeJS, and I am having trouble understanding why my middleware is always executed.
From my understanding, the middleware as I wrote it should be executed for all the routes declared after the middleware itself.
My index.js is something like this:
const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
const bodyParser = require('body-parser'); // Parse incoming request bodies in a middleware before your handlers, available under the req.body property.
const configdb = require('./config/db_develop');
const path = require('path');
const authentication = require('./routes/authentication')(router); // Import Authentication Routes
const noNeedForAuth = require('./routes/noNeedForAuth')(router);
const app = express();
const port = 30000;
mongoose.Promise = global.Promise;
mongoose.connect(configdb.uri, (err) => {
if (err) {
console.log('Could not connect to database ' + err);
} else {
console.log('Connected to the database ' + configdb.db);
}
});
app.use(bodyParser.urlencoded({
extended: false
})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(express.static(__dirname + '/frontend/buildpath'));
app.use('/noNeedForAuth', noNeedForAuth);
app.use('/users', authentication);
app.get('*', (req, res) => {
res.send(path.join(__dirname + '/client/dist'));
});
app.listen(port, () => {
console.log('Listening on port ' + port + '!');
});
The authentication.js is:
const User = require('../models/user'); // Import User Model Schema
const config = require('../config/db_develop.js'); // Import database configuration
const jwt = require('jsonwebtoken'); // Compact, URL-safe means of representing claims to be transferred between two parties.
module.exports = (router) => {
router.post('/register', (req, res) => {
//Register
});
router.post('/login', (req, res) => {
//Login
});
// MIDDLEWARE
router.use((req, res, next) => {
const token = req.headers['authorization']; // Create token found in headers
// Check if token was found in headers
if (!token) {
res.status(403);
res.json({
success: false,
message: 'No token provided'
}); // Return error
} else {
// Verify the token is valid
jwt.verify(token, config.secret, (err, decoded) => {
// Check if error is expired or invalid
if (err) {
res.json({
success: false,
message: 'Token invalid: ' + err
}); // Return error for token validation
} else {
req.decoded = decoded; // Create global variable to use in any request beyond
next(); // Exit middleware
}
});
}
});
/* ===============================================================
Route to get user's profile data
=============================================================== */
router.get('/profile', (req, res) => {
//Profile, protected route
});
return router; // Return router object to main index.js
}
And my noNeedForAuth.js is
module.exports = (router) => {
/* ===============================================================
Route to get all sections' names
=============================================================== */
router.get('/something', (req, res) => {
// Do something
res.json({
message: 'foobar'
});
});
return router; // Return router object to main index.js
}
From my understanding, a query to /noNeedForAuth/something should be executed without passing from the middleware, so without the need for Authentication. But this is not happening, the middleware is executed first, always.
What am I missing?
Thanks
You are applying your middleware without any mount path to your router. It will execute for any route.
Try something like:
// MIDDLEWARE
router.use('/protected', (req, res, next) => {
const token = req.headers['authorization']; // Create token found in headers
// Check if token was found in headers
if (!token) {
res.status(403);
res.json({
success: false,
message: 'No token provided'
}); // Return error
} else {
// Verify the token is valid
jwt.verify(token, config.secret, (err, decoded) => {
// Check if error is expired or invalid
if (err) {
res.json({
success: false,
message: 'Token invalid: ' + err
}); // Return error for token validation
} else {
req.decoded = decoded; // Create global variable to use in any request beyond
next(); // Exit middleware
}
});
}
});
All your routes, where the user have to be authenticated, are behind /protected.

Passport.js remember me functionality

https://github.com/jaredhanson/passport-remember-me
passport.use(new RememberMeStrategy(
function(token, done) {
Token.consume(token, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
return done(null, user);
});
},
function(user, done) {
var token = utils.generateToken(64);
Token.save(token, { userId: user.id }, function(err) {
if (err) { return done(err); }
return done(null, token);
});
}
));
post
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }),
function(req, res, next) {
// issue a remember me cookie if the option was checked
if (!req.body.remember_me) { return next(); }
var token = utils.generateToken(64);
Token.save(token, { userId: req.user.id }, function(err) {
if (err) { return done(err); }
res.cookie('remember_me', token, { path: '/', httpOnly: true, maxAge: 604800000 }); // 7 days
return next();
});
},
function(req, res) {
res.redirect('/');
});
I'm trying to implement remember me feature (above) into my existing application but I couldn't make it. When I add RememberMeStrategy into my login.js, it throws
ReferenceError: RememberMeStrategy is not defined
error. What's missing here?
index.js
var rendering = require('../util/rendering');
var express = require('express');
var router = express.Router();
exports.home = function(req, res) {
res.render('index/index');
};
exports.userHome = function(req, res) {
res.render('index/user-home');
};
login.js
var crypto = require('crypto'),
passport = require('passport'),
passportRememberMe = require('passport-remember-me'),
passportLocal = require('passport-local'),
data = require('../models/auth')();
exports.registerPage = function (req, res) {
res.render('login/register', {username: req.flash('username')});
};
exports.registerPost = function (req, res) {
var vpw = req.body.vpw;
var pwu = req.body.pw;
var un = req.body.un;
req.flash('username', un);
if (vpw !== pwu) {
req.flash('error', 'Your passwords did not match.');
res.redirect('/register');
return;
}
req.checkBody('un', 'Please enter a valid email.').notEmpty().isEmail();
var errors = req.validationErrors();
if (errors) {
var msg = errors[0].msg;
req.flash('error', msg);
res.redirect('/register');
return;
}
var new_salt = Math.round((new Date().valueOf() * Math.random())) + '';
var pw = crypto.createHmac('sha1', new_salt).update(pwu).digest('hex');
var created = new Date().toISOString().slice(0, 19).replace('T', ' ');
new data.ApiUser({email: un, password: pw, salt: new_salt, created: created}).save().then(function (model) {
passport.authenticate('local')(req, res, function () {
res.redirect('/home');
})
}, function (err) {
req.flash('error', 'Unable to create account.');
res.redirect('/register');
});
};
exports.loginPage = function (req, res) {
res.render('login/index', {username: req.flash('username')});
};
exports.checkLogin = function (req, res, next) {
passport.authenticate('local', function (err, user, info) {
if (err || !user) {
req.flash('username', req.body.un);
req.flash('error', info.message);
return res.redirect('/login');
}
req.logIn(user, function (err) {
if (err) {
req.flash('error', info.message);
return res.redirect('/login');
}
req.flash('success', 'Welcome!');
return res.redirect('/home');
});
})(req, res, next);
};
exports.logout = function (req, res) {
req.logout();
req.flash('info', 'You are now logged out.');
res.redirect('/login');
};
routes.js
var rendering = require('./util/rendering'),
indexController = require('./controllers/index'),
loginController = require('./controllers/login');
module.exports = function (app, passport) {
// Home
app.get('/', indexController.home);
app.get('/home', ensureAuthenticated, indexController.userHome);
// Auth
app.get('/register', loginController.registerPage);
app.post('/register', loginController.registerPost);
app.get('/login', loginController.loginPage);
app.post('/login', loginController.checkLogin);
app.get('/logout', loginController.logout);
// 'rendering' can be used to format api calls (if you have an api)
// into either html or json depending on the 'Accept' request header
app.get('/apitest', function(req, res) {
rendering.render(req, res, {
'data': {
'test': {
'testsub': {
'str': 'testsub hello world'
},
'testsub2': 42
},
'test2': 'hello world'
}
});
})
// Auth Middleware
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
res.redirect('/login');
}
}
server.js
var dbConfig;
try {
// Look for dev conf for local development
dbConfig = require('./config/db.dev.conf.js');
} catch(e) {
try {
// production conf?
dbConfig = require('./config/db.conf.js');
} catch(e) {
console.log('Startup failed. No db config file found.');
return false;
}
}
var knex = require('knex')({
client: 'mysql',
connection: dbConfig
}),
express = require('express'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
cookieSession = require('cookie-session'),
serveStatic = require('serve-static'),
expressValidator = require('express-validator'),
flash = require('connect-flash'),
swig = require('swig'),
passport = require('passport'),
passportRememberMe = require('passport-remember-me'),
passportLocal = require('passport-local'),
crypto = require('crypto'),
Bookshelf = require('bookshelf'),
messages = require('./util/messages');
var app = express();
Bookshelf.mysqlAuth = Bookshelf(knex);
app.use(cookieParser('halsisiHHh445JjO0'));
app.use(cookieSession({
keys: ['key1', 'key2']
}));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(expressValidator());
app.use(passport.initialize());
app.use(passport.session());
app.use(passport.authenticate('remember-me'));
app.use(flash());
app.use(serveStatic('./public'));
//app.use(express.favicon(__dirname + '/public/images/shortcut-icon.png'));
app.use(messages());
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
require('./util/auth')(passport);
require('./routes')(app, passport);
app.listen(process.env.PORT || 3000);
console.log('Listening on port 3000');
That error is simply saying that you haven't defined the RememberMeStrategy function before calling it (you're using new but in Javascript that's just calling a function with a special variable called this). You need to require the module first, in this case:
var RememberMeStrategy = require('passport-remember-me').Strategy;
Just require it in the variable RememberMeStrategy
var RememberMeStrategy= require('passport-remember-me').Strategy;

Resources