I am using node, express, mongoose and passport for my project and I implemented a simple Log In functionality to my code as seen below in app.js and it works perfectly. I then tried to split my code because I want to use MVC and this time when I run my application and try to log in I get the passport.initialize() middleware not in use Error. I have tried everything that other users in other posts have suggested but to no avail. Any suggestions?
app.js - old one which works
const express = require('express');
const morgan = require('morgan');
const mongoose = require('mongoose');
const Donation = require('./models/Donation');
const User = require('./models/User');
const donationRoutes = require('./routes/donationRoutes');
const registerRoutes = require('./routes/registerRoutes');
// express app
const app = express();
// connect to mongodb & listen for requests
const dbURI = "mongodb+srv://test:test#test.8npff.mongodb.net/test?retryWrites=true&w=majority";
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(result => app.listen(3000))
.catch(err => console.log(err));
// register view engine
app.set('view engine', 'ejs');
// middleware & static files
app.use(express.static('public'));
app.use(express.urlencoded({ extended: true }));
app.use(morgan('dev'));
app.use((req, res, next) => {
res.locals.path = req.path;
next();
});
// express setup for login
const bodyParser = require('body-parser');
const expressSession = require('express-session')({
secret: 'secret',
resave: false,
saveUninitialized: false
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressSession);
// passport setup for auth login
const passport = require('passport');
app.use(passport.initialize());
app.use(passport.session());
// passport local authentification
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
/* LOGIN ROUTES */
const connectEnsureLogin = require('connect-ensure-login');
app.post('/login', (req, res, next) => {
passport.authenticate('local',
(err, user, info) => {
if (err) {
return next(err);
}
if (!user) {
return res.redirect('/login?info=' + info);
}
req.logIn(user, function(err) {
if (err) {
return next(err);
}
return res.redirect('/');
});
})(req, res, next);
});
app.get('/login',
(req, res) => res.render('login', {title: 'login'})
);
app.get('/donations',
connectEnsureLogin.ensureLoggedIn(),
(req, res) => {
Donation.find().sort({ createdAt: -1 })
.then(result => {
res.render('donations/index', { donations: result, title: 'All Donations' });
})
.catch(err => {
console.log(err);
});
}
);
app.get('/user',
connectEnsureLogin.ensureLoggedIn(),
(req, res) => res.send({user: req.user})
);
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
//Register Routes
app.use('/', registerRoutes);
// *** routes ***
app.get('/', (req, res) => {
res.redirect('/donations');
});
//donation routes
app.use('/donations', donationRoutes);
// 404 page
app.use((req, res) => {
res.status(404).render('404', { title: '404' });
});
app.js - new one
const express = require('express');
const morgan = require('morgan');
const mongoose = require('mongoose');
const donationRoutes = require('./routes/donationRoutes');
const registerRoutes = require('./routes/registerRoutes');
const loginRoutes = require('./routes/loginRoutes');
// express app
const app = express();
// connect to mongodb & listen for requests
const dbURI = "mongodb+srv://test:test#test.8npff.mongodb.net/test?retryWrites=true&w=majority";
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(result => app.listen(3000))
.catch(err => console.log(err));
// register view engine
app.set('view engine', 'ejs');
// middleware & static files
app.use(express.static('public'));
app.use(express.urlencoded({ extended: true }));
app.use(morgan('dev'));
app.use((req, res, next) => {
res.locals.path = req.path;
next();
});
//Register Routes
app.use('/', registerRoutes);
//Login Routes
app.use('/', loginRoutes);
// *** routes ***
app.get('/', (req, res) => {
res.redirect('/donations');
});
//donation routes
app.use('/donations', donationRoutes);
// 404 page
app.use((req, res) => {
res.status(404).render('404', { title: '404' });
});
loginController.js
const connectEnsureLogin = require('connect-ensure-login');
const Donation = require('../models/Donation');
const express = require('express');
const User = require('../models/User');
// express app
const app = express();
// express setup for login
const bodyParser = require('body-parser');
const expressSession = require('express-session')({
secret: 'secret',
resave: false,
saveUninitialized: false
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressSession);
// passport setup for auth login
const passport = require('passport');
app.use(passport.initialize());
app.use(passport.session());
// passport local authentification
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
const login_post = (req, res, next) => {
passport.authenticate('local',
(err, user, info) => {
if (err) {
return next(err);
}
if (!user) {
return res.redirect('/login?info=' + info);
}
req.logIn(user, function(err) {
if (err) {
return next(err);
}
return res.redirect('/');
});
})(req, res, next);
}
const login_get = (req, res) => {
res.render('login', {title: 'login'});
}
const index_get = (req, res) => {
connectEnsureLogin.ensureLoggedIn();
Donation.find().sort({ createdAt: -1 })
.then(result => {
res.render('donations/index', { donations: result, title: 'All Donations' });
})
.catch(err => {
console.log(err);
});
}
const user_get = (req, res) => {
connectEnsureLogin.ensureLoggedIn();
res.send({user: req.user});
}
const logout_get = (req, res) => {
req.logout();
res.redirect('/')
}
module.exports = {
login_post,
login_get,
index_get,
user_get,
logout_get
}
loginRoutes.js
const express = require('express');
const loginController = require('../controllers/loginController');
const router = express.Router();
router.post('/login', loginController.login_post);
router.get('/login', loginController.login_get);
router.get('/donations', loginController.index_get);
router.get('/user', loginController.user_get);
router.get('/logout', loginController.logout_get);
module.exports = router;
And here is the error log:
Error: passport.initialize() middleware not in use
at IncomingMessage.req.login.req.logIn (C:\Users\123\Documents\Datenbanken_Projekt\transparent_blood\node_modules\passport\lib\http\request.js:46:34)
at C:\Users\123\Documents\Datenbanken_Projekt\transparent_blood\controllers\loginController.js:43:9
at Strategy.strategy.success (C:\Users\123\Documents\Datenbanken_Projekt\transparent_blood\node_modules\passport\lib\middleware\authenticate.js:219:18)
at verified (C:\Users\123\Documents\Datenbanken_Projekt\transparent_blood\node_modules\passport-local\lib\strategy.js:83:10)
at C:\Users\123\Documents\Datenbanken_Projekt\transparent_blood\node_modules\passport-local-mongoose\index.js:205:41
There are two problems here:
You create new app more than once. First in app.js, then in loginController.js. You should use just one instance of app, otherwise it's like a second server and your middleware won't work properly.
In your example, you never initialize passport (using passport.initialize()). In the first sample (that is working), there are many lines of passport initialization, including strategies and stuff - everything after // passport setup for auth login. Then they're gone. You need to bring them back ;)
Related
I'm building a server with Node and Express, using handlebars as views. My controller contains the system logic functions, which receive the request and response objects as parameters and my Route, only makes the connection between the route and the controller. But I am not able to see the error to generate this error in the title.
My controller.js:
const router = express.Router();
exports.home = (req, res) => {
res.render('home', { entries: entries });
};
exports.Form = (req, res) =>{
res.render('form')
};
exports.FormFetch = (req, res) =>{
res.render('form-fetch')
};
My app.js:
const express = require('express');
const handlebars = require('express-handlebars');
const app = express();
app.engine('.hbs', handlebars.engine({
defaultLayout: 'main',
extname: '.hbs',
}));
app.set('view engine', '.hbs')
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
var userRoute = require('./routes')
app.get('/', userRoute)
app.use('/new-entry', userRoute)
app.use('/new-entry-fetch', userRoute)
app.listen(3000, () =>{
console.log('Ok')
});
My routes.js:
const express = require('express');
const controller = require('./controllers/controllers');
const app = express();
const entries = [];
app.get('/', (req, res) => {
res.render(controller.home, { entries: entries });
});
app.get('/new-entry', (req, res) => {
res.render(controller.Form);
});
app.get('/new-entry-fetch', (req, res) => {
res.render(controller.FormFetch);
});
app.post('/new-entry', (req, res) => {
entries.push({
title: req.body.title,
content: req.body.body,
published: new Date()
});
res.redirect(303, '/');
});
module.exports = app
i was trying to track if the user is logged in or not and if not and try to make a new post he will redirected to login page then i store the url he was trying to go to (the new post url) so when he log in he will be redirected there, i used express session to store that and have passport local to do the auth thing anyway the (new post) url is in the session but when i log in (doing post request) it just got deleted altho i tried other post requests to see if that the prob but it only reset on this post
the middleware to check and store the url in the session
module.exports.isLoggedIn = (req, res, next) => {
if (!req.isAuthenticated()) {
req.session.returnTo = req.originalUrl
console.log(req.session.returnTo)
req.flash('error', 'You must be signed in first!');
return res.redirect('/login');
}
next();
}
module.exports.isNotLoggedIn = (req, res, next) => {
if (req.isAuthenticated()) {
return res.redirect('/campgrounds')
}
next();
}
the login routes
const express = require('express');
const router = express.Router();
const passport = require('passport');
const catchAsync = require('../utils/catchAsync');
const User = require('../models/user');
const { isNotLoggedIn } = require('../middleware')
router.get('/register', isNotLoggedIn, (req, res) => {
res.render('users/register');
});
router.post('/register', isNotLoggedIn, catchAsync(async (req, res, next) => {
try {
const { email, username, password } = req.body;
const user = new User({ email, username });
const registeredUser = await User.register(user, password);
req.login(registeredUser, err => {
if (err) return next(err);
req.flash('success', 'Welcome to Yelp Camp!');
res.redirect('/campgrounds');
})
} catch (e) {
req.flash('error', e.message);
res.redirect('register');
}
}));
router.get('/login', isNotLoggedIn, (req, res) => {
console.log(req.session)
res.render('users/login');
})
router.post('/login', isNotLoggedIn, passport.authenticate('local', { failureFlash: true, failureRedirect: '/login' }), (req, res) => {
req.flash('success', 'welcome back!');
const returnTo = req.session.returnTo || '/campgrounds';
console.log('this thsisdifsdk')
console.log(req.session) //todo this req.session is getting reset for some reason and i cannot return to what page i was goin for
res.redirect(returnTo);
})
router.get('/logout', (req, res) => {
req.logout((err) => {
if (err) { return next(err); }
req.flash('success', "Goodbye!");
res.redirect('/campgrounds');
});
})
module.exports = router;
the app.js
const express = require('express')
const path = require('path')
const mongoose = require('mongoose')
const ejsMate = require('ejs-mate');
const session = require('express-session')
const flash = require('connect-flash')
const ExpressError = require('./utils/ExpressError')
const methodOverride = require('method-override')
const passport = require('passport');
const LocalStrategy = require('passport-local')
const User = require('./models/user')
const userRoutes = require('./routes/user')
const campgroundRoutes = require('./routes/campgrounds')
const reviewRoutes = require('./routes/reviews');
mongoose.connect('mongodb://localhost:27017/yelp-camp');
const db = mongoose.connection //?shortcut
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('Database Connected');
})
const app = express();
app.engine('ejs', ejsMate)
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))
app.use(express.urlencoded({ extended: true }));
app.use(methodOverride('_method'));
app.use(express.static(path.join(__dirname, 'public')))
const sessionConfig = {
secret: 'meowmeowthecatsounduwu',
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true,
expires: Date.now() + 1000 * 60 * 60 * 24 * 7,
maxAge: 1000 * 60 * 60 * 24 * 7
}
}
app.use(session(sessionConfig))
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use((req, res, next) => {
console.log(req.session)
res.locals.currentUser = req.user;
res.locals.success = req.flash('success');
res.locals.error = req.flash('error');
next();
})
app.use('/', userRoutes);
app.listen(3000, () => {
console.log('Serving on port 3000')
})
things i tried
remove the cookie, add for cookie secure: true, change secure: false, change the secret, make resave true and false, make saveUninitialized true and false, change the session name, nothing worked, i suspect that the passport is the problem but idk how to solve it
passport.authenticate('local', {failureFlash:true, failureRedirect:'/login', keepSessionInfo:true})
router.post('/#',
passport.authenticate('local', {
failureFlash: true,
failureRedirect: '/login',
keepSessionInfo: true
})
);
I am using passport, node and express in my project. I keep getting this error when i try to register: Bad Request
I am not sure what the problem is. If I delete the authentication, it works perfectly but when I add it, it gives me the same error so I think there's a problem that I can't find. Thank you. I really appreciate it!!!
const express = require('express');
const bodyParser =require("body-parser");
const passport=require("passport");
const mongoose= require("mongoose");
const passportLocalMongoose = require('passport-local-mongoose');
const session = require("session");
const expressSession =require("express-session");
const app = express();
const LocalStrategy = require('passport-local').Strategy
const Schema= mongoose.Schema;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.set('view engine', 'ejs');
mongoose.connect('mongodb://localhost:27017/userDB2', {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex:true});
const userSchema= new mongoose.Schema({
email:String,
password:String
})
userSchema.plugin(passportLocalMongoose)
const User= mongoose.model("User",userSchema);
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser())
app.get('/', (req, res) => {
res.render('index');
});
app.get('/login', (req, res) => {
res.render('login');
});
app.get("/register",(req,res)=>
{
res.render("register");
})
app.get('/message', (req, res) => {
if(req.isAuthenticated())
{
res.redirect("/message")
}
else
{
res.redirect("/register")
}
});
app.post("/register",(req,res)=>
{
const email= req.body.email;
const password= req.body.password;
User.register({username:email}, password, function(err, user) {
if (err) {
console.log("err")
res.redirect("/register")
}
else
{
passport.authenticate("local")(req,res, function()
{
res.redirect("/message")
})
}
})
})
app.listen('4000', (req, res) => {
console.log('working and refreshin...')
});
I think you are messing this important lines for passport to work
sessions
app.use(session({secret: 'secret'}))
app.use(passport.initialize());
app.use(passport.session());
I'm trying Nextjs for the first time and I added express to use mongodb. I got so far as getting login in with my google credentials but I'm struggling getting the session info to my user's profile page.
Server.js:
const express = require('express');
const next = require('next');
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
const passport = require("passport");
const LocalStrategy = require("passport-local");
const exsession = require("express-session");
const User = require('../models/User');
const port = process.env.PORT || 8080;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const middleware = require("../middleware/middleware")
const uri = "XXXX"
app.prepare()
.then(() => {
const server = express();
const showRoutes = require('./routes/index');
const authRouter = require('./routes/auth');
mongoose.connect(uri)
.then(function () {
console.log('Connected to MONGOD !!');
}).catch(function (err) {
console.log('Failed to establish connection with MONGOD !!');
console.log(err.message);
});
server.use(express.static(__dirname + "/public"));
server.use(bodyParser.urlencoded({extended: true}));
server.use(bodyParser.json());
/////////////////////////////////////
//passport configuration
/////////////////////////////////////
server.use(exsession({
secret: "projectx",
resave: false,
saveUninitialized: false,
}));
server.use(passport.initialize());
server.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
server.use(function(req, res, next){
res.locals.currentUser = req.user;
next();
})
server.use('/api', showRoutes);
server.use('/auth', authRouter);
server.get('/login', (req, res) => {
return app.render(req, res, '/login', req.query )
})
server.get('/profile', middleware.isLoggedIn, (req, res, next) => {
console.log(req.query)
return app.render(req, res, '/profile', { user: req.user } )
})
server.get('/post/:id', (req, res) => {
return app.render(req, res, '/post', { id: req.params.id })
})
server.get("*", (req, res) => {
return handle(req,res);
})
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`)
})
})
.catch(ex => {
console.log(ex.stack);
process.exit(1);
})
Profile.js:
import React, { Component } from 'react'
export default class extends Component {
static getInitialProps ({ user: { user } }) {
console.log(user)
return { user: user }
}
render () {
return <div>
<h1>Welcome{this.props.user}</h1>
</div>
}
}
I'm trying to display my current user's name in my profile page however i get undefined in my console.
my studies/add wont render. I get "CastError: Cast to ObjectId failed for value "add" at path "_id" " error. I just dont get it, nothing seems to work the way I would expect. Im quite new to express. I tried all kind of different things but it just wont render /studies/add
my studies route `
const express = require('express')
const router = express.Router()
const Studies = require('../models/studies')
router.get('/', (req, res) => {
Studies.find({}, (err, studies) => {
studies.sort(function (a, b) {
return new Date(b.endDate) - new Date(a.endDate)
})
if (err) {
console.log(err)
} else {
res.render('studies', {
studies
})
}
})
})
router.get('/:id', function (req, res) {
Studies.findById(req.params.id, function (err, studies) {
if (err) {
console.log(err)
} else {
res.render('course', {
studies
})
}
})
})
router.get('/add', function (err, req, res) {
if (err) {
console.log(err)
}
res.render('addstudy')
})
module.exports = router
`
my app.js file
const express = require('express')
const bodyParser = require('body-parser')
const path = require('path')
const config = require('./config/database')
const mongoose = require('mongoose')
const Studies = require('./models/studies')
const session = require('express-session')
const passport = require('passport')
// const flash = require('connect-flash')
const app = express()
mongoose.connect(config.database)
let db = mongoose.connection
// Check connection
db.once('open', function () {
console.log('Connected to MongoDB')
})
// Check for DB errors
db.on('error', function (err) {
console.log(err)
})
const logger = function (req, res, next) {
console.log('loogging..')
next()
}
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
// Body Parser Middleware
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(logger)
// Passport Config
require('./config/passport')(passport)
// Passport Middleware
app.use(passport.initialize())
app.use(passport.session())
// Express Session Middleware
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true
}))
// Express Messages Middleware
/* app.use(require('connect-flash')())
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res)
next()
}) */
app.use(express.static('public'))
app.get('*', function (req, res, next) {
res.locals.user = req.user || null
next()
})
app.get('/', (req, res) => {
Studies.find({}, (err, studies) => {
console.log(studies)
if (err) {
console.log(err)
} else {
res.render('index', {
name: studies[0].name,
description: studies[0].description
})
}
})
})
let studies = require('./routes/studies')
let work = require('./routes/work')
let about = require('./routes/about')
let users = require('./routes/users')
app.use('/studies', studies)
app.use('/work', work)
app.use('/about', about)
app.use('/users', users)
app.listen(3002, () => {
console.log('started on 3002')
})