I wanted to separate each group of routes in a file. I need to use isAuthenticated in most routes to restrict access. When I put all routes in the same file it works.
When I use module.exports = isAuthenticated in auth.js and in order.js I use var auth = require('auth.js'); I will get a error of 'isAuthenticated is not defined' when I go to http://localhost:3000/order the routes defined in auth.js just works as expected.
I'm using Express.js middleware 'Passport local strategy' (followed tutorial from tutsplus and downloaded github repository from here).
My project structure:
bin/www
models/auth/init.js
models/auth/user.js
models/auth/signup.js
models/auth/login.js
models/order.js
views/error.pug
views/index.pug
views/home.pug
views/layout.pug
views/order.pug
views/register.pug
routes/order.js
routes/auth.js
public/stylesheets/style.css
app.js
db.js
./routes/auth.js:
var express = require('express');
var router = express.Router();
var isAuthenticated = function (req, res, next) {
// if user is authenticated in the session, call the next() to call the next request handler
// Passport adds this method to request object. A middleware is allowed to add properties to
// request and response objects
if (req.isAuthenticated())
return next();
// if the user is not authenticated then redirect him to the login page
res.redirect('/');
}
module.exports = isAuthenticated;
module.exports = function(passport){
/* GET login page. */
router.get('/', function(req, res) {
// Display the Login page with any flash message, if any
res.render('index', { message: req.flash('message') });
});
/* Handle Login POST */
router.post('/login', passport.authenticate('login', {
successRedirect: '/home',
failureRedirect: '/',
failureFlash : true
}));
/* GET Registration Page */
router.get('/signup', function(req, res){
res.render('register',{message: req.flash('message')});
});
/* Handle Registration POST */
router.post('/signup', passport.authenticate('signup', {
successRedirect: '/home',
failureRedirect: '/signup',
failureFlash : true
}));
/* GET Home Page */
router.get('/home', isAuthenticated, function(req, res){
res.render('home', { user: req.user });
});
/* Handle Logout */
router.get('/signout', function(req, res) {
req.logout();
res.redirect('/');
});
return router;
}
./routes/order.js:
var express = require('express');
var router = express.Router();
var order = require('../models/order');
var auth = require('./auth.js');
module.exports = function(passport){
router.get('/order', isAuthenticated, function(req, res){
res.render('order');
});
router.post('/order', isAuthenticated, function(req, res)
{
var testorder = new order({
orderid: '52363',
productname: 'it works',
quantity: 1337
});
testorder.save(function (err) {
if (err) {console.log(err.stack);}
console.log('saving done...');
});
res.render('order', { product: req.body.productname });
});
};
./app.js
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var pug = require('pug');
var dbConfig = require('./db');
var mongoose = require('mongoose');
// Connect to DB
mongoose.connect(dbConfig.url);
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
// TODO - Why Do we need this key ?
app.use(expressSession({secret: 'mySecretKey'}));
app.use(passport.initialize());
app.use(passport.session());
// Using the flash middleware provided by connect-flash to store messages in session
// and displaying in templates
var flash = require('connect-flash');
app.use(flash());
// Initialize Passport
var initPassport = require('./models/auth/init.js');
initPassport(passport);
var auth = require('./routes/auth')(passport);
var order = require('./routes/order');
app.use('/', auth);
app.use('/order', order);
/// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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
});
});
}
module.exports = app;
Try auth.isAuntheticated(),
It should work that way.
Related
The issue here is when i log in with correct details, the session should be created and cookie should be generated at client side which is happening when i use postman but not in case of web browsers.
I am using the following:
passport for authenticating login details from mongoDB using mongoose
express-session for creating session when a user logs in.
cors at the backend (react is running at port 3000 and node is running at port 4000)
Here is my app.js (backend):
var createError = require('http-errors');
var cookieParser = require('cookie-parser')
var path = require('path');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var serverRouter = require("./routes/server");
var DbRouter = require("./routes/DbRequest");
var ProductRouter = require("./routes/ProductRouter");
var CategoryRouter = require("./routes/CategoryRouter");
const session = require("express-session");
const passport = require("./passport");
var cors = require("cors");
var express = require('express');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
// USING SESSION AND PASSPORT
app.use(session({
secret: 'adsdsacoasdqwdn',
resave: false,
saveUninitialized: false,
cookie: { secure: false }
}))
app.use(passport.initialize());
app.use(passport.session());
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use("/api/admin",serverRouter);
app.use("/api/user",DbRouter);
app.use("/api/product",ProductRouter);
app.use("/api/category",CategoryRouter);
app.use(express.json({ extended:false}));
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Methods','GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
})
// 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;
Here is my file where i am making the routes and creating sessions :
var express = require("express");
var router = express.Router();
var connectDB = require("./connect");
const passport = require("../passport");
connectDB();
router.post("/adminlogin", (req,res,next) => {
passport.authenticate("local-adminSignin",function(err,user,info){
if(err){
return res.status(500).send(err)
}
req.login(user,function(error){
if(error){
return res.status(500).json(err)
}
return res.json(user);
})
})(req,res,next);
})
router.get("/currentAdmin", (req,res,next) => {
res.json(req.user)
})
module.exports = router;
Here , when i make a get request to "/currentAdmin" after i logged in as admin, i should be getting the user object as a response which contains all details of the admin from mongoDB.
POSTMAN LOGIN (i cant post images because this is a new account, i've linked gyazo below) :
https://gyazo.com/5569415297fbe7c7178a93634d1506e6
AFTER LOGIN, MAKING REQUEST TO "/currentAdmin"
https://gyazo.com/cd2ec99e1ee8f959d0c3874b43b76454
But, when i make same request from react, it gives me empty object as a response. One thing i noticed here is cookies are generated in postman and i get response but no cookies are there in the browser after admin login.
MY PASSPORT INDEX.JS FILE
const passport = require("passport");
const User = require("../routes/AdminSchema")
passport.serializeUser(function(user, done) {
console.log('i am serializing the user');
done(null, user.username);
});
passport.deserializeUser(function(username, done) {
console.log('i am de-serializing the user');
User.findOne({username}).lean().exec((err,user) => {
done(err, user);
});
});
//import strategy
const AdminLoginStrategy = require("./AdminLoginStrategy");
passport.use('local-adminSignin',AdminLoginStrategy);
module.exports = passport;
MY LOGIN STRATEGY FILE:
const Strategy = require("passport-local").Strategy;
const User = require("../routes/AdminSchema")
const bcrypt = require("bcryptjs")
const LoginStrategy = new Strategy({passReqToCallback:true},function(req,username,password,done){
User.findOne({username}).lean().exec((err,user) => {
if(err){
return done("db error idk bro",null)
}
if(!user){
return done("user not found!",null)
}
const isPasswordValid = bcrypt.compareSync(password, user.password);
if(!isPasswordValid){
return done("username or password not valid!",null)
}
return done(null,user)
})
})
module.exports = LoginStrategy
PS: If i send text response or other json from "/currentAdmin", I am getting it in react but i am not getting the res.user object which i think is because of cookies not being generated in the browser.
How can i solve this issue? Thanks!
Am a newbie to Node.js, Am getting only a loading page in node.js post request when running the passport authentication. Can anyone help me
my Router.js
var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/user-model');
var Local = require('../config/passport-local');
/* GET home page. */
router.get('/', function(req, res, next){
res.render('index',{ title : 'Login'});
});
router.post('/login', (req, res, next) => {
passport.authenticate('local',(req, res,next) => {
console.log('ok');
});
}, (req, res, next) => {
});
module.exports = router;
passport-local.js
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user-model')
passport.use(new LocalStrategy(
function(username, password, next) {
console.log('auth');
User.findOne({username: username}, function(err, user) {
console.log('passport');
if(err) { return next(err);}
if(!user) {
return next(null, false, {message : 'invalid username'});
}
if(!user.validPassword(password)) {
return next(null, false, {message: 'invalid password'})
}
return next(null, user);
});
}
));
App.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var commonKeys = require('./config/keys');
var app = express();
//connect mongoDb
mongoose.connect(commonKeys.mongoDB.connect + '/' + commonKeys.mongoDB.database, { useNewUrlParser: true });
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use('/', indexRouter);
app.use('/users', usersRouter);
// 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;
I am trying to learn passport authentication in nodejs. it is much appriciated if anyone can explain the error in this code and why its not working.
You need to update your code accordingly:
router.post('/login',
passport.authenticate('local'),
function(req, res) {
// If this function gets called, authentication was successful.
// `req.user` contains the authenticated user.
res.send('Done');
});
Here's more documentation.
I've spent more time than I'd like to admit scouring countless posts online that have the same problem as me, to no avail. The majority of solutions seemed to be things like not including
passReqToCallback: true in my LocalStrategy.
passport.serializeUser() and passport.deserializeUser() in my init file.
app.use(passport.initialize()) and app.use(passport.session()) in app.js.
Requiring and using app.use(cookieParser()) in app.js.
Passing cookie parser my secret key.
Adding proxy and cookie attributes to my expressSession variable in app.js.
Invoking req.login inside passport.authenticate within my page route.
And several other little tweaks I can't remember...
My login.js is as follows;
var LocalStrategy = require('passport-local').Strategy;
var User = require('../../models/user');
var bCrypt = require('bcrypt-nodejs');
module.exports = function(passport) {
passport.use('login', new LocalStrategy({passReqToCallback: true},
function(req, username, password, done) {
//Queries MongoDB For User
User.findOne({'username': username}, function(err, user) {
//In The Event Of An Error, Throw It
if (err) {
return done(err);
}
//Username Does Not Exist, Log Error, Callback, Flash Error Message
if (!user){
console.log('User: '+ username + ", does not exist.");
return done(null, false, req.flash('message', 'User Not found.'));
}
//User Exists, But Password Is Incorrect
if (!isValidPassword(user, password)){
console.log('Invalid Password');
return done(null, false, req.flash('message', 'Invalid Password')); // redirect back to login page
}
//If No Previous Error Conditions Are Met - Username/Password Are Correct
console.log("Validated User: " + username + ".");
//req.user = user;
return done(null, user);
}); //End of User.findOne()
}) //End of new LocalStrategy
); //End of passport.use()
/*
var isValidPassword = function(user, password){
return bCrypt.compareSync(password, user.password);
}
*/
//Passwords are not currently hashed in my DB, so ignore bcrypt for now.
var isValidPassword = function(user, password) {
return user.password == password;
}
}
My passport-init.js file
var login = require('./login');
var User = require('../../models/user');
module.exports = function(passport){
//Serialise User
passport.serializeUser(function(user, done) {
console.log("Serializing User: " + user.username + "\n" + user + ".");
done(null, user._id);
});
//De-Serialise User
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
console.log("Deserializing User: " + user.username + "\n" + user);
done(err, user);
});
});
//Setting up Passport Strategy for Login
login(passport);
}
My index.js file contains the POST Login route
/* POST Login Page*/
router.post('/login', passport.authenticate('login', {
successRedirect: '/dashboard',
failureRedirect: '/login',
failureFlash: true
}));
And dashboard.js contains all the routing for /dashboard/other-pages.
These ones are protected by the isAuthenticated function.
var express = require('express');
var router = express.Router();
var database = require('../public/javascripts/db-connect.js');
var isAuthenticated = function(req, res, next) {
console.log("User: " + req.user);
console.log("Authenticated?: " + req.isAuthenticated());
if (req.isAuthenticated()) {
return next();
} else {
res.redirect('/unauthorised');
}
}
module.exports = function(passport) {
//Routes /dashboard --> dashboard.pug
router.get('/', isAuthenticated, function(req, res, next) {
database.getData("busdata", function(err, data) {
if (err) {
console.error(err);
} else {
res.render('dashboard', {title: 'Dashboard', busdata: data});
}
});
});
//Routes /dashboard/journeys --> journeys.pug
router.get('/journeys', isAuthenticated, function(req, res, next) {
database.getData("journeydata", function(err, data) {
if (err) {
console.error(err);
} else {
res.render('journeys', {title: 'Journey Graphs', journeydata: data});
}
});
});
return router;
}
So when I run the app;
I check localhost:3000/dashboard and localhost:3000/dashboard/journeys. They correctly re-direct me to /unauthorised.
Navigate to /login.
Enter a correct username and password, the console then spits out:
Validated User: TomPlum. Meaning passport.use() reached return done(null, user)
Serialising User: TomPlum + the objects properties
POST /login 302 time ms
User: undefined from isAuthenticated
isAuthenticated? false
GET /dashboard 302 time ms
Deserialising User: TomPlum + the objects properties
I'm then redirected to /unauthorised as isAuthenticated() evaluates to false.
Why is req.user undefined? Should I be using a LocalStrategy if my MongoDB is not-local? (Amazon Atlas Server). Other forum posts have suggested it could be a cookie issue but I've included the relevant cookie-parser includes in my app.js file.
app.js is here in-case it's an order issue.
//Require Variables
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');
//Mongo DB Connection Settings
var dbConfig = require('./db'); //db.js contains DB URL
var mongoose = require('mongoose');
mongoose.connect(dbConfig.url); //dbConfig.url refers to the export in db.js
//Page Routing
//var index = require('./routes');
var users = require('./routes/users');
var dashboard = require('./routes/dashboard')(passport);
var app = express();
app.d3 = require('d3');
// 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/images', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser('urban_sensing'));
app.use(express.static(path.join(__dirname, 'public')));
//app.use('/', index);
app.use('/dashboard', dashboard);
app.use('/users', users);
//Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
app.enable('trust-proxy');
app.use(expressSession({
secret: 'urban_sensing',
resave: true,
saveUninitialized: true,
proxy: true,
cookie: {
secure: true,
maxAge: 3600000
}
}));
app.use(passport.initialize());
app.use(passport.session());
//Flash Messaging For Passport
var flash = require('connect-flash');
app.use(flash());
//Initialize Passport
var initPassport = require('./public/javascripts/passport-init');
initPassport(passport);
var index = require('./routes/index')(passport);
app.use('/', index);
//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;
Some of the app.use(expressSession({..})); properties may currently be unnecessary as they've been added in an attempt to fix the issue.
Any help would be appreciated.
After too much time on this, turns out it was simply the order of app.js.
By moving
var dashboard = require('./routes/dashboard')(passport);
app.use('/dashboard', dashboard);
below all the passport configuration. It now works correctly. It seems that something wasn't initialised correctly during the routing of /dashboard when it was before the passport code.
Updated app.js
//Require Variables
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');
//Mongo DB Connection Settings
var dbConfig = require('./db'); //db.js contains DB URL
var mongoose = require('mongoose');
mongoose.connect(dbConfig.url); //dbConfig.url refers to the export in db.js
//Page Routing
//var index = require('./routes');
var users = require('./routes/users');
var app = express();
app.d3 = require('d3');
// 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/images', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser('urban_sensing'));
app.use(express.static(path.join(__dirname, 'public')));
//app.use('/', index);
app.use('/users', users);
//Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
app.use(expressSession({
secret: 'urban_sensing',
resave: false,
saveUninitialized: true,
cookie: {
maxAge: 3600000 //1 Hour
}
}));
app.use(passport.initialize());
app.use(passport.session());
//Flash Messaging For Passport
var flash = require('connect-flash');
app.use(flash());
//Initialize Passport
var initPassport = require('./public/javascripts/passport-init');
initPassport(passport);
var dashboard = require('./routes/dashboard')(passport);
app.use('/dashboard', dashboard);
var index = require('./routes/index')(passport);
app.use('/', index);
//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;
I'm trying to get Toastr library to work in my ExpressJS app! I scaffolded the app with the yeoman 'standard' Express Generator...
I've required the lib express-toastr and did the following:
in app.js:
const cookieParser = require('cookie-parser');
const session = require('express-session');
const flash = require('connect-flash');
const toastr = require('express-toastr');
app.use(cookieParser());
app.use(session( {secret: 'xxx', saveUninitialized: true, resave: true} ));
app.use(flash());
app.use(toastr());
in index.js
const express = require('express');
const router = express.Router();
const httpntlm = require('httpntlm');
router.post('/', function (req, res, next) {
// parse inputs
let user = req.body.user || "";
let password = req.body.password || "";
// save in session
req.session.user = {user: user, password: password};
// appropriate response to login attempt
if (!req.session.user) {
res.status(401).send();
}
else {
req.toastr.success('Successfully logged in.', "You're in!");
res.render('groups', {
req: req
});
}
});
module.exports = router;
In index.jade
#{req.toastr.render()}
I'm loading these files in my <head> section:
link(rel='stylesheet', href='//cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.2/css/toastr.min.css')
script(src='/components/jquery/dist/jquery.min.js')
script(src='//cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.2/js/toastr.min.js')
Nothing is showing. What am I missing???
-- UPDATE! --
Here is my complete app.js file. I now try to use express-flash and making a dedicated route for showing a flash message. Still not working. Please help!
'use strict';
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const expressSanitizer = require('express-sanitizer');
const login = require('./routes/login');
const apply = require('./routes/apply');
const admin = require('./routes/admin');
var session = require('express-session');
var flash = require('express-flash');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// 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());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
cookie: { maxAge: 60000 },
store: new session.MemoryStore,
saveUninitialized: true,
resave: 'true',
secret: 'secret'
}));
app.use(flash());
// Route that creates a flash message using the express-flash module
app.all('/express-flash', function( req, res ) {
req.flash('success', 'This is a flash message using the express-flash module.');
res.redirect(301, '/');
});
// sanitize inputs
app.use(expressSanitizer());
app.use('/', apply);
app.use('/apply', apply);
app.use('/login', login);
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 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: {}
});
});
module.exports = app;
Try using this middleware in your app.js, I found this here
app.use(function (req, res, next)
{
res.locals.toasts = req.toastr.render()
next()
});
and then access locals in your view as follows:
#{toasts}
This worked for me.
So I am not familiar with your syntax in your index.jade file(!=). What does it do? If you change that line in your index to #{req.toastr.render()} it should work.
I've created a simple project, with 3 pages: Home, Contact and About.
Everything was working, then I wanted to add users registration with mongo.
So I followed this tutorial
But, when I add somes new routes, I can't acces any more pages.
This was my index.js when I can acces my 3 pages
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
/* GET contact page. */
router.get('/contact', function(req, res) {
res.render('contact');
});
/* POST contact page (submit). */
router.post('/contact', function(req, res) {
res.render('contact', { name: req.param('name') });
});
/* GET home page. */
router.get('/home', function(req, res) {
res.render('home');
});
/* POST home page (submit). */
router.post('/home', function(req, res) {
res.render('home', { comm: req.param('comm') });
});
/* GET about page. */
router.get('/about', function(req, res) {
res.render('about');
});
module.exports = router;
all simple and working.
and now, it's like that :
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
/* GET contact page. */
router.get('/contact', function(req, res) {
res.render('contact');
});
/* POST contact page (submit). */
router.post('/contact', function(req, res) {
res.render('contact', { name: req.param('name') });
});
/* GET home page. */
router.get('/home', function(req, res) {
res.render('home');
});
/* POST home page (submit). */
router.post('/home', function(req, res) {
res.render('home', { comm: req.param('comm') });
});
/* GET about page. */
router.get('/about', function(req, res) {
res.render('about');
});
module.exports = router;
module.exports = function(passport){
// /* GET login page. */
// router.get('/', function(req, res) {
// // Display the Login page with any flash message, if any
// res.render('index', { message: req.flash('message') });
// });
/* Handle Login POST */
router.post('/login', passport.authenticate('login', {
successRedirect: '/home',
failureRedirect: '/',
failureFlash : true
}));
/* GET Registration Page */
router.get('/signup', function(req, res){
res.render('register',{message: req.flash('message')});
});
/* Handle Registration POST */
router.post('/signup', passport.authenticate('signup', {
successRedirect: '/home',
failureRedirect: '/signup',
failureFlash : true
}));
return router;
}
and now, no routes are showed.
Any ideas ?
thanks !
EDIT : app.js
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var swig = require('swig');
var dbConfig = require('./db.js');
var mongoose = require('mongoose');
mongoose.connect(dbConfig.url);
var routes = require('./routes/index');
var app = express();
// Configuring Passport
var passport = require('passport');
var expressSession = require('express-session');
app.use(expressSession({secret: 'mySecretKey'}));
app.use(passport.initialize());
app.use(passport.session());
// view engine setup
app.engine('html', swig.renderFile);
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));
// view cache
app.set('view cache', false);
swig.setDefaults({ cache: false });
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
/// catch 404 and forwarding 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: {}
});
});
module.exports = app;
Your module expects a passport object
module.exports = function(passport){
but you're not calling it with a passport object in app.js
var routes = require('./routes/index');
also, you'll need to defined passport before calling the routes module. So in the end you'll need to modify your app.js to look something like this:
var passport = require('passport');
var expressSession = require('express-session');
app.use(expressSession({secret: 'mySecretKey'}));
app.use(passport.initialize());
app.use(passport.session());
...
var routes = require('./routes/index')(passport);
...
app.use('/', routes);