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());
Related
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 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 ;)
This is my first day in express. I was trying to create a simple route but my save function doesn't seem to work. I tried looking at similar questions posted on stackoverflow but couldn't make it. Any help will be appreciated.
const express = require("express");
const router = express.Router();
const Post = require("../models/Post");
//ROUTES
router.post('/', (req, res) => {
const post = new Post({
title: req.body.title,
description: req.body.description
})
post.save()
.then(data => {
res.json(data);
})
.catch(err => {
res.json(err);
});
});
module.exports = router;
And here is my model.
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
}
});
module.exports = mongoose.model('Posts',PostSchema);
app.js code
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
require("dotenv/config");
//IMPORT ROUTES
const postsRoute = require("./routes/posts");
//MIDDLEWARE - Function that always execute when routes are being hit.
app.use(bodyParser.json())
app.use('/posts', postsRoute)
//app.use('/users', usersRoute)
//ROUTES
app.get('/', (req, res) => {
res.send("We are on home");
});
//CONNECT TO DB
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true },
() => {
console.log("DB Connected!!")
})
//How do we start listening to the server
app.listen(3000);
My postman query -
Postman Response -
Please let me know if you need any more information.
your app.js should be :
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
require("dotenv/config");
//MIDDLEWARE - Function that always execute when routes are being hit.
app.use(bodyParser.json())
mongoose.connect(process.env.DB_CONNECTION, { useNewUrlParser: true }, function(err) {
if (err) {
console.error('System could not connect to mongo server')
console.log(err)
process.exit()
} else {
console.log('System connected to mongo server')
}
});
//ROUTES
app.get('/', (req, res) => {
res.send("We are on home");
});
//IMPORT ROUTES
const postsRoute = require("./routes/posts");
app.use('/posts', postsRoute)
app.listen(3000);
also add console log in router to check req.body :
router.post('/', (req, res) => {
console.log('req.body===',req.body);
...
});
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')
})
So recently I came across a problem, which is happening when i try to authenticate using google oauth2 from mobile, but when i try to authenticate via computer, it works fine. I am using it with passportjs in node/express project.
project link: https://rhubarb-tart-18821.herokuapp.com/
You guys can see code here:
https://ide.c9.io/saijax/www
just whole authentication is so big that i can not put everything here...
EDIT:
here are some main files
passport.js
const GoogleStrategy = require("passport-google-oauth2")
.Strategy;
const mongoose = require("mongoose");
const keys = require("./keys");
module.exports = (passport) => {
passport.use(
new GoogleStrategy({
clientID: keys.googleClientID,
clientSecret: keys.googleClientSecret,
callbackURL: "/auth/google/callback",
proxy: true
}, (accessToken, refreshToken, profile, done) => {
const image = profile.photos[0].value.substring(0, profile.photos[0].value.indexOf("?"));
const newUser = {
googleID: profile.id,
email: profile.emails[0].value,
firstName: profile.name.givenName,
lastName: profile.name.familyName,
image: image
}
// CHECK FOR USER
User.findOne({
googleID: profile.id
}).then(user => {
if(user){
done(null, user);
} else {
// CREATE USER
new User(newUser)
.save()
.then(user => done(null,user));
}
})
})
);
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id)
.then(user => done(null, user));
});
}
auth.js
const express = require("express");
const passport = require("passport");
const router = express.Router();
router.get("/google", passport.authenticate("google", {
scope: [
"profile",
"email"
]
}));
router.get("/google/callback", passport.authenticate("google", {
failureRedirect: "/"
}), (req, res) => {
req.flash("success_msg", "Successfully Logged In");
res.redirect("/dashboard");
});
router.get("/verify", (req, res) => {
if(req.user){
console.log(req.user);
} else {
console.log("Not auth");
}
});
router.get('/logout', (req, res) => {
req.logout();
req.flash("success_msg", "Successfully Logged Out");
res.redirect('/');
});
module.exports = router;
app.js
// SETUP
const express = require("express");
const mongoose = require("mongoose");
const passport = require("passport");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const exphbs = require("express-handlebars");
const bodyParser = require("body-parser");
const methodOverride = require("method-override");
const flash = require("connect-flash");
// LOAD GOOGLE AND MONGO KEYS
const keys = require("./config/keys");
// LOAD MODELS
require("./models/story");
require("./models/user");
// PASSPORT CONFIG
require("./config/passport")(passport);
// LOAD ROUTES
const auth = require("./routes/auth");
const index = require("./routes/index");
const stories = require("./routes/stories");
// HANLEBARS HELPERS
const {
truncate,
stripTags,
formatDate,
select,
editIcon
} = require("./helpers/hbs");
// MONGOOSE CONNECT
mongoose.connect(keys.mongoURI)
.then(() => {
console.log("MongoDB Connected...");
}).catch(err => console.log(err));
// USE APP
const app = express();
// CSS CONFIG
app.use(express.static(__dirname + "/public"));
// VIEW ENGINE
app.engine("handlebars", exphbs({
helpers: {
truncate: truncate,
stripTags: stripTags,
formatDate: formatDate,
select: select,
editIcon: editIcon
},
defaultLayout: "main"
}));
app.set("view engine", "handlebars");
// BODY PARSER
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// METHOD OVERRIDE
app.use(methodOverride("_method"));
// FLASH
app.use(flash());
// COOKIE PARSER
app.use(cookieParser());
// SESSION MIDDLEWARE
app.use(session({
secret: "KAPPA",
resave: false,
saveUninitialized: false
}));
// PASSPORT MIDDLEWARE
app.use(passport.initialize());
app.use(passport.session());
// SET GLOBAL VARS
app.use((req, res, next) => {
res.locals.user = req.user || null;
res.locals.success_msg = req.flash("success_msg");
res.locals.error_msg = req.flash("error_msg");
next();
});
// ROUTES
app.use("/", index);
app.use("/auth", auth);
app.use("/stories", stories);
UPDATE: well, i dont know if it was silly mistake or not, but it seems like mobile can not read
callbackURL: "/auth/google/callback"
instead i changed following line with
callbackURL: keys.callback + "/auth/google/callback"
where keys.callback is url for my app(from c9/heroku) ... now it works perfectly!