req.session is undefind and keep resetting - javascript

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

Related

Passport authenticate doesn't works and redirects to the url specified

I have installed express-session before initializing passport yet the passport authenticate doesn't works and it simply redirects to the failureRedirect url without any errors or messages.
i have checked that passport initializing works perfectly just authentication is not working
my index.js file
const ejs = require("ejs");
const url = require("url");
const session = require("express-session");
const cookieParser = require('cookie-parser')
const flash = require('connect-flash');
const toastr = require('express-toastr');
const Profile = require('./models/Profile.js');
const passport = require("passport");
const { customAlphabet } = require('nanoid');
const express = require("express"),
path = require('path')
const app = express();
const port = 3000;
const { Notyf } = require('notyf')
const { connect } = require('mongoose');
const LocalStrategy = require('passport-local');
const MemoryStore = require("memorystore")(session);
const methodOverride = require('method-override')
connect(process.env.mongodb);
const initializePassport = require('./utils/passport-config.js')
initializePassport(
passport,
email => Profile.find({ email_id: email }),
id => Profile.find({ user_id: email })
)
var bodyParser = require('body-parser');
app.use(cookieParser());
app.use(
session({
store: new MemoryStore({ checkPeriod: 86400000 }),
secret: "##%#&^$^$%#$^$&%#$%##$%$^%&$%^#$%##$%#E%#%#$FEErfgr3g#%GT%536c53cc6%5%tv%4y4hrgrggrgrgf4n",
resave: false,
saveUninitialized: false,
}),
);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(toastr());
app.use('/assets', express.static(path.join(__dirname, 'assets')))
app.use('/scripts', express.static(path.join(__dirname, 'node_modules')))
app.set('views', './views');
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: true,
}),
);
const checkAuth = (req, res, next) => {
try {
if (req.isAuthenticated()) return next();
req.session.backURL = req.url;
res.redirect("/login");
} catch (e) {
console.log(e)
}
};
app.get('/', async function(req, res){
res.render('index.ejs', { url: req.url })
});
app.get('/login', async function(req, res){
if (req.session.backURL) {
req.session.backURL = req.session.backURL;
} else if (req.headers.referer) {
const parsed = url.parse(req.headers.referer);
if (parsed.hostname === app.locals.domain) {
req.session.backURL = parsed.path;
}
} else {
req.session.backURL = "/";
}
res.render('login.ejs', { url: req.url })
});
app.get('/signup', async function(req, res){
res.render('signup.ejs', { url: req.url })
});
app.get('/newshop', async function(req, res){
res.render('shopcreate.ejs', { url: req.url })
});
app.get('/profile', async function(req, res){
res.render('profile.ejs', { url: req.url })
});
app.get('/settings', async function(req, res){
res.render('settings.ejs', { url: req.url })
});
app.post('/login', passport.authenticate('local', {
failureRedirect: '/login',
}), async (
err,
req,
res,
next,
) => {
try {
await console.log(req)
if (req.session.backURL) {
const backURL = req.session.backURL;
req.session.backURL = null;
res.redirect(backURL);
} else {
res.redirect('/');
}
} catch(e) {
console.log(e)
}
})
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`));
my passport-config.js file -
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt')
function initialize(passport, getUserByEmail, getUserById) {
const authenticateUser = async (email, password, done) => {
console.log(email)
const user = getUserByEmail(email)
if (user == null) {
return done(null, false, { message: 'User not found' })
}
try {
if (await bcrypt.compare(password, user.password)) {
return done(null, user)
} else {
return done(null, false, { message: 'Password incorrect' })
}
} catch (e) {
return done(e)
}
}
passport.use(new LocalStrategy({ usernameField: 'email' }, authenticateUser))
passport.serializeUser((user, done) => done(null, user.id))
passport.deserializeUser((id, done) => {
return done(null, getUserById(id))
})
}
module.exports = initialize

Why are passportjs' req methods not working and flagged as 'not a function'?

the req.isAuthenticated an req.logout seems not to be working and flagged as 'not a function' in my project. here's the code for the project. my verify function seems not to be working as expected.
i've worked other video tutorials aside the paid tutorial i'm watching now on udemy, yet i get the same error on my end or my session's aren't stored.
const http = require("http");
const path = require("path");
const express = require("express");
const helmet = require("helmet");
const passport = require("passport");
const cookieSession = require("cookie-session");
const googleStrategy = require("passport-google-oauth20").Strategy;
require("dotenv").config();
const PORT = 8000;
const G_CONF = {
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "/auth/google/cb",
};
const CC_CONF = {
name: "session",
maxAge: 60 * 60 * 1000,
keys: [process.env.COOKIE_KEY_00, process.env.COOKIE_KEY_01],
secure: false,
httpOnly: true,
};
const app = express();
const server = http.createServer(app);
function verifyUser(req, res, next) {
const loggedIn = req.user;
console.log(loggedIn);
if (req.user === undefined) {
return res.status(401).json({ error: "you must log in" });
}
next();
}
passport.use(
new googleStrategy(G_CONF, (accessToken, refreshToken, profile, done) => {
done(null, profile);
})
);
// Serializes or push authenticated user to session.
passport.serializeUser((user, done) => {
done(null, user.id);
});
// Deserializes or pull authenticated user from subsequent session request.
passport.deserializeUser((id, done) => {
done(err, user);
});
app.use(helmet());
app.use(cookieSession(CC_CONF));
app.use(passport.initialize());
app.get("/", (req, res) => {
res.status(200).sendFile(path.join(__dirname, "public", "index.html"));
});
app.get(
"/auth/google",
passport.authenticate("google", { scope: ["profile"] })
);
app.get(
"/auth/google/cb",
passport.authenticate("google", {
failureRedirect: "/failed",
successRedirect: "/success",
session: true,
})
);
app.get("/secret", verifyUser, (req, res, next) => {
res.send("secret");
});
app.get("/failed", (req, res) => {
res.sendFile(path.join(__dirname, "public", "failed.html"));
});
app.get("/success", (req, res) => {
res.status(200).sendFile(path.join(__dirname, "public", "success.html"));
});
app.get("/auth/logout", (req, res) => {
req.logout();
res.redirect("/");
});
server.listen(PORT, (err) => {
if (err) {
console.error(err);
}
console.log("Auth Server running on port 8000");
});
i get 'undefined' when i log 'user'
my verify seems not to be working properly
passportjs req.method() isn't working.

passport.initialize() middleware not in use

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 ;)

req.user is undefined after passport.authenticate

I'm having issues getting access to req.user after I login. The passport authentication works and I initially get the req.user information to send to the client side after logging in but it becomes undefined immediately after.Here is a picture of the console showing this. How can I stop req.user form being undefined after logging in? It looks like it is in the session for a brief moment after the initial login. I've spent hours for fixes but nothing seems to work.
Below is how I handle the login.
router.post(
'/login',
function (req, res, next) {
next()
},
passport.authenticate('local', { failureFlash: true, failureRedirect: '/login' }),
async (req, res) => {
const fullUser = await User.findOne({ username: req.user.username })
console.log(req.user)
console.log(req.session)
res.send(fullUser);
}
)
Below is the server setup.
const express = require('express');
const mongoose = require('mongoose');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local');
const User = require('./models/user');
const usersRoutes = require('./routes/users-routes');
const chirpsRoutes = require('./routes/chirps-routes');
const singleRoutes = require('./routes/single-routes');
const HttpError = require('./models/http-error');
const MongoDBStore = require('connect-mongo')(session);
const cors = require('cors');
const app = express();
const connectUrl = 'mongodb info removed';
mongoose.connect(connectUrl, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
console.log("Database connected");
});
// const connectConfig = {
// useNewUrlParser: true,
// useCreateIndex: true,
// useUnifiedTopology: true,
// useFindAndModify: false
// }
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true })); //used to parse req.body
const secret = process.env.SECRET || 'thishouldbeabettersecret!';
const store = new MongoDBStore({
url: connectUrl,
secret,
touchAfter: 24 * 60 * 60
});
store.on("error", function (e) {
console.log("SESSION STORE ERROR", e)
})
const sessionConfig = {
name: 'session',
secret,
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
expires: Date.now() + 1000 * 60 * 60 * 24 * 7,
maxAge: 1000 * 60 * 60 * 24 * 7
}
}
app.use(session(sessionConfig))
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
//Add user to session
passport.serializeUser(User.serializeUser());
//Remove user from session
passport.deserializeUser(User.deserializeUser());
// middleware
app.use((req, res, next) => {
// res.locals.currentUser = req.user; //passport user
res.setHeader('Access-Control-Allow-Origin', '*'); //set header on resposne
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-Width, Content-Type, Accept, Authorization'); //incoming requests handle
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE');
console.log('******REQ.USER******' + " " + req.user)
console.log('******SESSION BELOW******')
console.log(req.session)
next();
})
app.use('/auth', usersRoutes)
app.use('/chirps', chirpsRoutes)
app.use('/:uid', singleRoutes)
app.use((req, res, next) => { //error handling for invalid routes
const error = new HttpError('Could not find this route.', 404);
return next(error);
})
app.use((error, req, res, next) => {
if (res.headerSent) {
return next(error);
}
res.status(error.code || 500);
res.send({ message: error.message || 'An unknown error occurred!' });
})
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Serving on port ${port}`)
})
Below is the User schema.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const passportLocalMongoose = require('passport-local-mongoose');
const UserSchema = new Schema({
email: {
type: String,
required: true,
unique: true
},
about: String
});
//add username & password to UserSchema
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model('User', UserSchema);
And lastly, below is my login post request that I handle with React.
function loginUser(username, password) {
try {
const data = {
username,
password
}
axios.post('http://localhost:5000/auth/login', data)
.then(response => {
console.log(response.data)
if (response.status === 200) {
auth.login(response.data._id,response.data.username)
history.push('/chirps');
}
})
} catch (error) {
console.log(error)
}
}

Passport + NodeJs + Express getting "req.user" undefined

I am facing a session problem, Getting req.user undefined after successful passport. authenticate method.
Basically after signUp or login, when I am redirecting, unable to find "user" in request variable.
I have used a hackathon starter which was using mongo, I tried to change things to use Postgres.
Edit -- After following suggestions on Comment
Now signup flow is working fine, but login flow having some problem. Something weird happening, when I am adding a lot of breaking points, It seems to do login intermittently. Update code with comment suggestions
app.js
const express = require('express');
const compression = require('compression');
const session = require('express-session');
const bodyParser = require('body-parser');
const logger = require('morgan');
const chalk = require('chalk');
const errorHandler = require('errorhandler');
const lusca = require('lusca');
const dotenv = require('dotenv');
const flash = require('express-flash');
const path = require('path');
const passport = require('passport');
const expressValidator = require('express-validator');
const expressStatusMonitor = require('express-status-monitor');
const sass = require('node-sass-middleware');
const multer = require('multer');
dotenv.load({ path: '.env.example' });
const SequelizeStore = require('connect-session-sequelize')(session.Store);
const models = require('./models');
const upload = multer({ dest: path.join(__dirname, 'uploads') });
/**
* Load environment variables from .env file, where API keys and passwords are configured.
*/
/**
* Controllers (route handlers).
*/
const homeController = require('./controllers/home');
const userController = require('./controllers/user');
const contactController = require('./controllers/contact');
const dashController = require('./controllers/dash');
const currencyController = require('./controllers/currency');
const accountController = require('./controllers/account');
const testController = require('./controllers/test');
const txController = require('./controllers/transaction');
/**
* API keys and Passport configuration.
*/
const passportConfig = require('./config/passport');
/**
* Create Express server.
*/
const app = express();
/**
* Express configuration.
*/
app.set('host', '127.0.0.1');
app.set('port', 8080);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(expressStatusMonitor());
app.use(compression());
app.use(sass({
src: path.join(__dirname, 'public'),
dest: path.join(__dirname, 'public')
}));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(session({
resave: true,
saveUninitialized: true,
secret: process.env.SESSION_SECRET,
cookie: { maxAge: 1209600000 }, // two weeks in milliseconds
store: new SequelizeStore({
db: models.sequelize
})
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use((req, res, next) => {
// if (req.path === '/api/upload') {
// next();
// } else {
// lusca.csrf()(req, res, next);
// }
next();
});
app.use(lusca.xframe('SAMEORIGIN'));
app.use(lusca.xssProtection(true));
app.disable('x-powered-by');
app.use((req, res, next) => {
res.locals.user = req.user;
next();
});
app.use((req, res, next) => {
// After successful login, redirect back to the intended page
if (!req.user
&& req.path !== '/login'
&& req.path !== '/signup'
&& !req.path.match(/^\/auth/)
&& !req.path.match(/\./)) {
req.session.returnTo = req.originalUrl;
} else if (req.user
&& (req.path === '/account' || req.path.match(/^\/api/))) {
req.session.returnTo = req.originalUrl;
}
next();
});
app.use('/', express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 }));
app.use('/js/lib', express.static(path.join(__dirname, 'node_modules/chart.js/dist'), { maxAge: 31557600000 }));
app.use('/js/lib', express.static(path.join(__dirname, 'node_modules/popper.js/dist/umd'), { maxAge: 31557600000 }));
app.use('/js/lib', express.static(path.join(__dirname, 'node_modules/bootstrap/dist/js'), { maxAge: 31557600000 }));
app.use('/js/lib', express.static(path.join(__dirname, 'node_modules/jquery/dist'), { maxAge: 31557600000 }));
app.use('/webfonts', express.static(path.join(__dirname, 'node_modules/#fortawesome/fontawesome-free/webfonts'), { maxAge: 31557600000 }));
/**
* Primary app routes.
*/
app.get('/', homeController.index);
app.get('/login', userController.getLogin);
app.post('/login', userController.postLogin);
app.get('/logout', userController.logout);
app.get('/forgot', userController.getForgot);
app.post('/forgot', userController.postForgot);
app.get('/reset/:token', userController.getReset);
app.post('/reset/:token', userController.postReset);
app.get('/signup', userController.getSignup);
app.post('/signup', userController.postSignup);
// app.get('/account', passportConfig.isAuthenticated, userController.getAccount);
// app.post('/account/profile', passportConfig.isAuthenticated, userController.postUpdateProfile);
app.post('/account/password', passportConfig.isAuthenticated, userController.postUpdatePassword);
// app.post('/account/delete', passportConfig.isAuthenticated, userController.postDeleteAccount);
// app.get('/account/unlink/:provider', passportConfig.isAuthenticated, userController.getOauthUnlink);
app.get('/dashboard', passportConfig.isAuthenticated, dashController.index);
app.get('/test', passportConfig.isAuthenticated, testController.test);
// app.get('/contact', contactController.contact);
// app.post('/addContact', contactController.addContact);
// app.post('/editContact', contactController.editContact);
// app.get('/listContacts', contactController.listContacts);
// app.get('/listCurrency', currencyController.listCurrency);
// app.post('/addAccount', accountController.addAccount);
// app.post('/editAccount', accountController.editAccount);
// app.get('/listAccounts', accountController.listAccounts);
// app.get('/getTransactions', txController.getTransactions);
/**
* Error Handler.
*/
if (process.env.NODE_ENV === 'development') {
// only use in development
app.use(errorHandler());
} else {
app.use((err, req, res, next) => {
console.error(err);
res.status(500).send('Server Error');
});
}
/**
* Start Express server.
*/
models.sequelize.sync({}).then(() => {
app.listen(app.get('port'), () => {
console.log('%s App is running at http://localhost:%d in %s mode', chalk.green('✓'), app.get('port'), app.get('env'));
console.log('Press CTRL-C to stop\n');
});
});
module.exports = app;
user.js
const { promisify } = require('util');
const crypto = require('crypto');
const nodemailer = require('nodemailer');
const passport = require('passport');
const models = require('../models');
const { User } = models;
const randomBytesAsync = promisify(crypto.randomBytes);
/**
* GET /login
* Login page.
*/
exports.getLogin = (req, res) => {
if (req.user) {
return res.redirect('/');
}
res.render('account/login', {
title: 'Login'
});
};
/**
* POST /login
* Sign in using email and password.
*/
exports.postLogin = (req, res, next) => {
req.assert('email', 'Email is not valid').isEmail();
req.assert('password', 'Password cannot be blank').notEmpty();
req.sanitize('email').normalizeEmail({ gmail_remove_dots: false });
const errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/login');
}
passport.authenticate('local', (err, user, info) => {
if (err) { return next(err); }
if (!user) {
req.flash('errors', info);
return res.redirect('/login');
}
req.logIn(user, (err) => {
if (err) { return next(err); }
res.locals.user = user; //Updated code after comment suggestions
req.flash('success', { msg: 'Success! You are logged in.' });
res.redirect('/dashboard');
});
})(req, res, next);
};
/**
* GET /logout
* Log out.
*/
exports.logout = (req, res) => {
req.logout();
req.session.destroy((err) => {
if (err) console.log('Error : Failed to destroy the session during logout.', err);
req.user = null;
res.redirect('/');
});
};
/**
* GET /signup
* Signup page.
*/
exports.getSignup = (req, res) => {
if (req.user) {
return res.redirect('/');
}
res.render('account/signup', {
title: 'Create Account'
});
};
/**
* POST /signup
* Create a new local account.
*/
exports.postSignup = (req, res, next) => {
req.assert('email', 'Email is not valid').isEmail();
req.assert('password', 'Password must be at least 4 characters long').len(4);
req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password);
req.sanitize('email').normalizeEmail({ gmail_remove_dots: false });
const errors = req.validationErrors();
if (errors) {
req.flash('errors', errors);
return res.redirect('/signup');
}
User.findAll({ limit: 1, where: { email: req.body.email }, plain: true })
.then((existingUser) => {
if (existingUser) {
req.flash('errors', { msg: 'Account with that email address already exists.' });
return res.redirect('/signup');
}
User.create({
email: req.body.email,
password: req.body.password
}).then((user) => {
req.logIn(user, (err) => {
if (err) { return next(err); }
res.locals.user = user; //updated code after comment suggestions
return res.redirect('/');
});
}).catch(error => next(error));
});
};
passport.js
const passport = require('passport');
const request = require('request');
const { Strategy: LocalStrategy } = require('passport-local');
const _ = require('lodash');
const models = require('../models');
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
models.User.findAll({ where: { id }, limit: 1, plain: true })
.then(user => done(null, user))
.catch(err => done(err));
});
/**
* Sign in using Email and Password.
*/
passport.use(new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
models.User.findAll({ where: { email }, limit: 1, plain: true }).then((user) => {
if (!user) {
return done(null, false, { msg: `Email ${email} not found.` });
}
user.comparePassword(password, (err, isMatch) => {
if (err) { return done(err); }
if (isMatch) {
return done(null, user);
}
return done(null, false, { msg: 'Invalid email or password.' });
});
}).catch(error => done(error));
}));
/**
* OAuth Strategy Overview
*
* - User is already logged in.
* - Check if there is an existing account with a provider id.
* - If there is, return an error message. (Account merging not supported)
* - Else link new OAuth account with currently logged-in user.
* - User is not logged in.
* - Check if it's a returning user.
* - If returning user, sign in and we are done.
* - Else check if there is an existing account with user's email.
* - If there is, return an error message.
* - Else create a new account.
*/
/**
* Login Required middleware.
*/
exports.isAuthenticated = (req, res, next) => {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/login');
};
/**
* Authorization Required middleware.
*/
exports.isAuthorized = (req, res, next) => {
const provider = req.path.split('/').slice(-1)[0];
const token = req.user.tokens.find(token => token.kind === provider);
if (token) {
next();
} else {
res.redirect(`/auth/${provider}`);
}
};
In your app.js, you need to call const passportConfig = require('./config/passport'); after you initialize passport, like so:
app.use(passport.initialize());
app.use(passport.session());
// place it here
const passportConfig = require('./config/passport')(passport);
Further, you need to adjust your password config file (./config/passport), so that on module loading it can get the passport instance that you instantiated in app.js, and subsequently uses it instead of loading a new passport instance via require('passport') - this in my opinion messes things up; didn't test it though. :)
Can you share the user object sample which refer to this code in your passport.js LocalStrategy
user.comparePassword(password, (err, isMatch) => {....});
looks like user.id is not available in serializeuser below which may be the cause it cant set user.id in the session and cant deserialize User further not setting the user object in req
passport.serializeUser((user, done) => {
done(null, user.id);
});

Categories