Nextjs + Express + Passport; Req.user is undefined - javascript

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.

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

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

Request body undefined in controller Express

I have a problem with my controller when I'm writing console.log(req); I have all the content of the request body but when I write console.log(req.body); is undefined. I'm trying to write my Portfolio with Next.js React and Express.
This is my server index.js:
const express = require('express');
const next = require('next');
const routes = require('../routes');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
// SERVICE
const authService = require('./services/auth');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = routes.getRequestHandler(app);
const config = require('./config');
const portfolioRoutes = require('./routes/portfolio');
const secretData = [
{ id: '1',
title: 'Secret Data',
description: 'plans for build something !'
},
{
id: '2',
title: 'Secret Data2',
description: 'plans for build something2 !'
}
]
//MONGODB
mongoose.connect(config.DB_URI, {useNewUrlParser: true, useUnifiedTopology: true})
.then(() => {
console.log("Db connected");
}).catch(err => console.log(err));
app.prepare()
.then(() => {
const server = express();
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: false }));
var jsonParser = bodyParser.json()
server.use('/api/v1/portfolio', portfolioRoutes);
server.get('/api/v1/secret', authService.checkJWT, (req,res) => {
return res.json(secretData);
})
server.get('/api/v1/ownersite', authService.checkJWT, authService.checkRole('siteOwner'),
(req,res) => {
return res.json(secretData);
})
server.get('*', jsonParser,(req,res) => {
return handle(req,res);
})
server.use(function (err, req, res, next){
if (err.name === 'UnauthorizedError') {
res.status(401).send({title: `Invalid token...`});
}
});
server.use(handle).listen(3000, (err) => {
if(err) throw err
console.log('> Ready on http://localhost:3000');
})
}).catch((ex) => {
console.error(ex.stack)
process.exit(1);
})
This is my routes :
const express = require('express');
const router = express.Router();
const portfolioCtrl = require('../controllers/portfolio');
const authService = require('../services/auth');
router.route('').get(authService.checkJWT, authService.checkRole('siteOwner'),
portfolioCtrl.getPortfolio);
router.route('').post(authService.checkJWT, authService.checkRole('siteOwner'),
portfolioCtrl.savePortfolio);
router.route('/:id').patch(authService.checkJWT, authService.checkRole('siteOwner'),
portfolioCtrl.updatePortfolio);
router.route('/:id').delete(authService.checkJWT, authService.checkRole('siteOwner'),
portfolioCtrl.deletePortfolio);
module.exports = router;
This is my Controller:
savePortfolio: (res, req) => {
console.log(req);
const portfolioData = req.body;
const portfolio = new Portfolio(portfolioData);
portfolio.save((err, createdPortfolio) => {
if(err) {
return res.status(422).send(err);
}
return res.json(createdPortfolio);
})
},
Express route's callback function takes the parameters in the following order:
(req, res, next) =>{...}
req, the request object.
res, the response object.
next, indicating the next middleware function (Optional)
savePortfolio: (res, req) => {...} has the order wrong. That is why req.body would be undefined.
Correction: savePortfolio: (req, res) => {...}

Cannot POST to CosmosDB using Angular

I am trying to post to my cosmosDB using Angular. I can GET just fine, but POST returns with a 404 error in Postman. I am new to routes and APIs so I am a little lost on what is causing the issue.
Here is my index.js
const bodyParser = require('body-parser');
const path = require('path');
const routes = require('./routes');
const root = './';
const port = process.env.PORT || '3000';
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(root, 'dist/checkin')));
app.use('/api', routes);
app.get('*', (req, res) => {
res.sendFile('dist/checkin/index.html', {root});
});
app.listen(port, () => console.log(`API running on localhost:${port}`));
My routes.js
const contactService = require('./contact.service');
const router = express.Router();
router.get('/contacts', (req, res) => {
contactService.getContacts(req, res);
});
router.post('/contact/', (req, res) => {
contactService.postContact(req, res);
});
module.exports=router;
My contact.service.js which contains all of my operations (Just GET and POST right now)
const ReadPreference = require('mongodb').ReadPreference;
require('./mongo').connect();
function getContacts(req, res) {
const docquery = Contact.find({}).read(ReadPreference.NEAREST);
docquery
.exec()
.then(contacts => {
res.status(200).json(contacts);
})
.catch(error => {
res.status(500).send(error);
return;
});
}
function postContact(req, res) {
const originalContact = { uid: req.body.uid, name: req.body.name, description: req.body.description };
const contact = new Contact(originalContact);
contact.save(error => {
if (checkServerError(res, error)) return;
res.status(201).json(contact);
console.log('Contact created successfully!');
});
}
function checkServerError(res, error) {
if (error) {
res.status(500).send(error);
return error;
}
}
module.exports = {
getContacts,
postContact
};
Input is obtained through an HTML forum which is picked up and sent through
return this.http.post<Contact>(`${api}/contact/`, contact);
}

My route wont render

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

Categories