authenticate.getToken is not a function on node.js v12.18.2 - node.js

I am receiving an authenticate.getToken is not a function error.
var express = require('express');
const bodyParser = require('body-parser');
var User = require('../models/user');
const passport = require('passport');
var authenticate = require('../authenticate');
var router = express.Router();
router.use(bodyParser.json());
/* GET users listing. */
router.get('/', function (req, res, next) {
res.send('respond with a resource');
});
router.post('/signup', (req, res, next) => {
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 {
passport.authenticate('local')(req, res, () => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({ success: true, status: 'Registration Successful!' });
});
}
}
);
});
router.post('/login', passport.authenticate('local'), (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!' });
});
router.get('/logout', (req, res) => {
if (req.session) { req.session.destroy();
res.clearCookie('session-id');
res.redirect('/');
} else {
var err = new Error('you are not logged in');
err.status = 403;
next(err);
}
});
module.exports = router;

The error simply means that authenticate.getToken is not a function. have you exported correctly in your authenticate.js file? It may be worth posting your authenticate.js file to your OP.
It should look something like this for it to work:
authenticate.js
module.exports = {
getToken: function() {
// code here
}
}

Related

Sending passport-local and express middleware to express router

I have a simple app.js file with passport authentication, I have a app.get on my app.js that looks something like this
app.get('/test', isAuthenticated, (req, res) => {
res.json(req.user)
})
When I open this page ('/test'), I get the following data
{
"email": "jhondoe#example.com",
"id": "f8dbee1ba8e95ace16656a008c548b91",
"expiry": "06/10/2022"
}
Now, I'm trying to do the same thing, but in my express router ('/s/main'), this is how I've imported my router
const settings = require('./routes/settings')
app.use("/s", settings)
Now I want to be able to access my 'req.user' and the isAuthenticated middleware that I declared in app.js
function isAuthenticated(req, res, done) {
if (req.user) {
return done();
}
return res.send('You need to be authenticated to view this page.');
}
this is my settings.js file from the routes folder
const express = require('express')
const router = new express.Router();
router.get('/main', (req, res) => {
res.send(req.user)
})
module.exports = router;
Conclusion
I want to do the same thing as the '/test' app.js in my '/s/main' in express router
Thanks for reading
app.js
const express = require('express');
const app = express();
const session = require('express-session');
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy;
const fs = require('fs');
const settings = require('./routes/settings')
app.use("/s", settings) //
app.use(express.urlencoded({ extended: false }))
app.use(session({ secret: 'pswd', resave: false, saveUninitialized: false }))
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(
function(email, password, done) {
console.log(email, password)
let user = findByEmail(email) // converts email address to user ID
let uid = user.id;
console.log(user, uid)
// compare(id) basically gets the password from the database
if (user.code != 200) {
return done(null, false, { message: 'Email not registered.' });
}
if (compare(uid) == password) {
return done(null, user); // login success
} else {
return done(null, false, { message: 'Incorrect password.' });
}
}
))
passport.serializeUser((user, done) => {
if (user) {
return done(null, user.id);
}
return done(null, false);
});
passport.deserializeUser((id, done) => {
let user = findById(id)
if (user.id == null) {
return done(null, false)
}
return done(null, user)
});
function isAuthenticated(req, res, done) {
if (req.user) {
return done();
}
return res.send('You need to be authenticated to view this page.');
}
app.get('/test', isAuthenticated, (req, res) => {
res.json(req.user)
})
app.get('/login', (req, res) => {
res.send('Login Page')
})
app.post('/login', passport.authenticate('local'), function (req, res) {
console.log('Valid login')
res.json(req.user)
})
app.post('/logout', (req, res) => {
req.logout();
res.send('Logged out')
})
app.get('/', (req, res) => {
res.send('Hello World!');
})
function findByEmail(email) {
let users = JSON.parse(fs.readFileSync('users.json', 'utf8'));
let index = users.findIndex(user => user.email == email);
if (index != -1) {
users[index].code = 200;
return users[index]
} else {
return { code: 404, email: null, id: null, expiry: null }
}
}
function findById(id) {
let users = JSON.parse(fs.readFileSync('users.json', 'utf8'));
let index = users.findIndex(user => user.id == id);
if (index != -1) {
return users[index]
} else {
return { email: null, id: null, expiry: null }
}
}
function compare(id) {
// basisically comparing the user ID's password and the entered password
if (id == 'f8dbee1ba8e95ace16656a008c548b91') {
return 'pswd_admin'
}
}
app.listen(3000, () => {
console.log('Server is up on port 3000');
});
module.exports = { isAuthenticated }
settings.js
const express = require('express')
const router = new express.Router();
router.get('/main', (req, res) => {
res.json(req.user)
})
module.exports = router;```

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!' });
});

Middleware not working for 2nd model i.e doctor but it works fine for admin.Here I am creating a two user model one is admin and one is doctor

I am trying to build a two user login system one is admin and 2nd one is doctor. Here i am creating a middleware which is working fine for first one i.e admin but in case of doctor it is redirecting me again and again to the login page though my password and user name is correct.
please some one let me know how to create middleware for two model auth
'use strict';
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
passport = require("passport"),
LocalStrategy = require("passport-local"),
mongoose = require('mongoose');
var Admin = require("./models/admin");
var Doctor = require("./models/doctor");
var http = require('http');
var port = process.env.PORT || 1337;
//Set up default mongoose connection
var mongoDB = 'mongodb://localhost:27017/seeddb';
mongoose.connect(mongoDB, { useNewUrlParser: true });
app.use(bodyParser.urlencoded({ extended: true }));
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public", { redirect: false }));
//PASSPORT CONFIGURTION
app.use(require("express-session")({
secret: "Rockey is the best",`enter code here`
resave: false,
saveUninitialized: false,
}));
app.enable('trust proxy');
app.use(passport.initialize());
app.use(passport.session());
app.use(require('flash')());
//=========================================================
//Admin Authentication
passport.use('adminLocal', new LocalStrategy(Admin.authenticate()));
passport.serializeUser(Admin.serializeUser());
passport.deserializeUser(Admin.deserializeUser());
//Doctor Authentication
passport.use('doctorLocal', new LocalStrategy(Doctor.authenticate()));
passport.serializeUser(Doctor.serializeUser());
passport.deserializeUser(Doctor.deserializeUser());
//=========================================================
app.use(function (req, res, next) { // to pass currentUser to each routes
res.locals.currentUser = req.user;
next();
});
//========================================================
//Landing route
//========================================================
app.get('/', function (req, res) {
res.render("clinic/landing");
});
//=========================================================
//Admin routes
//=========================================================
app.get('/admin-login', function (req, res) {
res.render("admin/login");
});
//Sign Up
app.post('/admin-signup', function (req, res) {
var newAdmin = new Admin({ username: req.body.username });
Admin.register(newAdmin, req.body.password, function (err, admin) {
if (err) {
console.log(err);
return res.redirect("/admin-login");
}
passport.authenticate("adminLocal")(req, res, function () { //local can be twitter fb for authentication
console.log("Successfully signup Login to continue");
res.redirect("/admin-login");
});
});
});
//Admin sign in
// process the login form
app.post('/admin-login', function (req, res, next) {
passport.authenticate('adminLocal', { failureFlash: true }, function (err, admin, info) {
if (err) { return next(err); }
if (!admin) { return res.redirect('/admin-login'); }
req.logIn(admin, function (err) {
if (err) { return next(err); }
return res.redirect('/admin/' + admin._id);
});
})(req, res, next);
});
//Admin home
app.get('/admin/:id', isLoggedIn, function (req, res) {
Admin.findById(req.params.id, function (err, admin) {
if (err) {
console.log(err);
} else {
Doctor.find({}).exec(function (err, doctors) {
if (err) throw err;
res.render("admin/adminhome", {"doctors" : doctors, admin: admin });
});
}
});
});
//===============================================
//Doctor routes
//===============================================
//Doctor login
app.get('/doctor-login', function (req, res) {
Admin.findById(req.params.id, function (err, admin) {
if (err) {
console.log(err);
} else {
res.render("doctors/login");
}
});
});
app.post('/doctor-signup', function (req, res) {
var newDoctor = new Doctor({
username: req.body.username,
fname: req.body.fname,
lname: req.body.lname,
email: req.body.email,
exp: req.body.exp,
dept: req.body.dept,
address: req.body.address,
hospInfo: req.body.hospInfo,
desc: req.body.description,
});
Doctor.register(newDoctor, req.body.password, function (err, doctor) {
if (err) {
console.log(err);
return res.redirect("back");
}
passport.authenticate("doctorLocal")(req, res, function (){ //local can be twitter fb for authentication
console.log("Doctor signup successfully Done");
res.redirect("/doctor-login");
});
});
});
//Doctor sign in
// process the login form
app.post('/doctor-login', function (req, res, next) {
passport.authenticate('doctorLocal', { failureFlash: true }, function (err, doctor, info) {
if (err) { return next(err); }
if (!doctor) { console.log("No doc found"); return res.redirect('/doctor-login'); }
req.logIn(doctor, function (err) {
if (err) { return next(err); }
return res.redirect('/doctor/' + doctor._id);
});
})(req, res, next);
});
//doctor home
app.get('/doctor/:id', isLoggedIn, function (req, res) {
Doctor.findById(req.params.id, function (err, doctor) {
if (err) {
console.log(err);
} else {
res.render("doctors/doctorhome", { doctor: doctor });
}
});
});
// //middleware to check whether it is logged in or not
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect("back");
}

Authentication failure when using express-session

I wrote some code for login authentication using express. I used express-session. Code sample is
// Authentication and Authorization Middleware
var auth = function(req, res, next) {
if (req.session && req.session.admin) {
return next();
} else {
console.log("failed");
return res.sendStatus(401);
}
}
// Login endpoint
router.post('/login', function (req, res) {
var collection = db.get("login");
collection.find({}, function(err, details) {
if (!req.body.username || !req.body.password) {
res.send('login failed');
} else if(req.body.username === details[0].name && req.body.password === details[0].password ) {
req.session.admin = true;
var data = {
"status": "success",
"message": "login success!"
}
res.send(data);
} else {
var data = {
"status": "failure",
"message": "login failed"
}
res.send(data);
}
});
});
// Logout endpoint
router.get('/logout', auth, function (req, res) {
req.session.destroy();
res.send("logout success!");
});
//Getting Details endpoint
router.get("/data", auth, function(req, res) {
var collection = db.get('details');
collection.find({}, function(err, details){
if (err) throw err;
res.json(details);
});
});
After successful login req.session.admin is set to true. But, at Authentication middleware (auth), it is sending 401 status. Please help me solve this problem.
code:
//app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var getDetails = require('./routes/getDetails');
var app = express();
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
// view engine setup
// 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(express.cookieParser());
app.use(express.static(path.join(__dirname, 'routes')));
app.use(express.session({
secret: '2C44-4D44-WppQ38S',
resave: true,
saveUninitialized: true
}));
app.use('/getDetails',getDetails);
// 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(3001);
module.exports = app;
//getDetails.js
var express = require('express');
var router = express.Router();
var monk = require('monk');
var db = monk('localhost:27017/saidb');
// Login endpoint
router.post('/login', function (req, res) {
var collection = db.get("login");
//var data;
collection.find({}, function(err, details) {
//res.json(details);
if (!req.body.username || !req.body.password) {
res.send('login failed');
} else if(req.body.username === details[0].name && req.body.password === details[0].password ) {
req.session.admin = true;
var data = {
"status": "success",
"message": "login success!"
}
res.send(data);
} else {
var data = {
"status": "failure",
"message": "login failed"
}
res.send(data);
}
});
});
var auth = function(req, res, next) {
if (req.session && req.session.admin) {
console.log("success");
return next();
} else {
console.log("failed");
return res.sendStatus(401);
}
}
// Logout endpoint
router.get('/logout', auth, function (req, res) {
req.session.destroy();
res.send("logout success!");
});
//Getting Details endpoint
router.get("/data", auth, function(req, res) {
var collection = db.get('details');
collection.find({}, function(err, details){
if (err) throw err;
res.json(details);
});
});
//Get details by ID endpoint
router.get("/data:id", auth, function(req, res) {
var collection = db.get('details');
collection.find({id: parseInt(req.params.id)}, function(err, details){
if (err) throw err;
res.json(details);
});
});
//Adding Details endpoint
router.post("/data", auth, function(req, res) {
var collection = db.get("details");
collection.count({id : parseInt(req.body.id)},function(err,count){
if(!err){
if(count>0){
//send the response that its duplicate.
//console.log(errorororrrroror);
res.send("r");
}
}
});
console.log("request", req.body);
collection.insert({ id: parseInt(req.body.id),
website: req.body.website,
subtitle: req.body.subtitle,
url: req.body.url },
function(err, details) {
if(err) throw err;
res.json(details);
})
});
//Editing Details endpoint
router.put("/data", auth, function(req,res){
var collection = db.get("details");
collection.update({id: parseInt(req.body.id)},
{id: parseInt(req.body.id), website: req.body.website, subtitle: req.body.subtitle, url: req.body.url},
function(err, details){
if(err) throw err;
res.json(details);
})
});
//Deleting details endpoint
router.delete("/data", auth, function(req,res){
var collection = db.get("details");
collection.remove({id: parseInt(req.body.id)}, function(err, details){
if(err) throw err;
res.json(details);
})
});
module.exports = router;
Use these lines in your server file at top after express object like this
var app = express();
app.use(express.cookieParser());
app.use(express.session({secret: "sdsddsd23232323" }));

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