NodeJs Session, Work in Postman but not in browser - node.js

I have some problems with the express session where I cannot retrieve my session variable that I had stored previously. Below are parts of my codes that I had written.
server.js
let express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
config = require('./config/database'),
expressSession = require('express-session'),
uid = require('uid-safe'),
db;
let app = express();
//Import Routes
let auth = require('./routes/auth'),
chimerListing = require('./routes/chimer-listing'),
brandListing = require('./routes/brand-listing');
//Specifies the port number
let port = process.env.PORT || 3000;
// let port = 3000;
// Express session
app.use(expressSession({
secret: "asdasd",
resave: true,
saveUninitialized: false,
cookie: {
maxAge: 36000000,
secure: false
}
}));
//CORS Middleware
app.use(cors());
//Set Static Folder
var distDir = __dirname + "/dist/";
app.use(express.static(distDir));
//Body Parser Middleware
app.use(bodyParser.json());
//MongoDB
let MongoClient = require('mongodb').MongoClient;
MongoClient.connect(config.database, (err, database) => {
if (err) return console.log(err)
db = database;
//Start the server only the connection to database is successful
app.listen(port, () => {
console.log('Server started on port' + port);
});
});
//Make db accessbile to routers;
app.use(function(req, res, next) {
req.db = db;
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.set('Access-Control-Allow-Headers', 'Content-Type');
next();
});
//Routes
app.use('/login', auth);
app.use('/user-listing', userListing);
app.use('/brand-listing', brandListing);
//Index Route
app.get('/', (req, res) => {
res.send('Invalid Endpoint');
});
genuuid = function() {
return uid.sync(18);
};
auth.js
let express = require('express'),
router = express.Router(),
db;
//Login Router for chimer
router.post('/chimer', (req, res, next) => {
db = req.db;
// let client = req.client;
db.collection('chimeUser').find({
Username: req.body.username,
Password: req.body.password
}).toArray().then(function(docs) {
//If there is such user
if (docs.length >= 1) {
req.session.chimerId = docs[0]._id;
console.log(req.session);
req.session.save(function(err) {
// session saved
if (err)
console.log(err)
res.json({
success: true,
chimerId: docs[0]._id
//objects: docs
});
})
} else {
res.json({
success: false,
//objects: docs
})
}
});
});
//Login Router brand
router.post('/brand', (req, res, next) => {
db = req.db;
db.collection('brand').find({
Username: req.body.username,
Password: req.body.password
}).toArray().then(function(docs) {
req.session.brand = docs;
console.log(req.session.brand);
//If there is such user
if (docs.length >= 1) {
res.json({
success: true,
//objects: docs
})
} else {
res.json({
success: false,
//objects: docs
})
}
//db.close()
});
});
});
module.exports = router;
user-listing.js
let express = require('express'),
moment = require('moment'),
router = express.Router(),
// ObjectID = require('mongodb').ObjectID,
db, client;
// let applyListing = require('../models/chimer-listing');
//Retrieve All Listing
router.get('/getAllListing', (req, res, next) => {
db = req.db;
console.log(req.session)
db.collection('listing').find().toArray().then(function(listing) {
//If there is any listing
if (listing.length >= 1) {
res.json({
success: true,
results: listing
})
} else {
res.json({
success: false,
})
}
//db.close()
});
});
module.exports = router;
So in my server.js, I have three routes file which is auth, user-listing, and brand-listing.
Firstly, a user will need to login with the web application which is developed in angular2 and this will trigger the auth route. It will then check for the credentials whether does it exist in the database if it exists I will then assign an ID to req.session.chimerId so that in other routes I will be able to use this chimerId.
Next, after the user has logged in, they will then retrieve an item listing. The problem arises where I can't seem to retrieve the req.session.chimerId that I had previously saved. It will be undefined
NOTE: I tried this using Postman and the browser. In the Postman it works, I am able to retrieve back the req.session.chimerId whereas when I use the angular2 application to hit the endpoints req.session.chimerId is always null

Related

Logout not working - nodejs express-session

I can't get the logout function to work correctly and remove the session from the mongodb.
I'm able to store the session. logout was initially req.session.destroy(); but that kept returning an error. (destroy undefined)
I'm pretty new to nodejs/javascript, I'm trying to learn my apologies in advance for any ignorance!
Any help would be appreciated!!
app.js
const express = require('express'), url = require('url');
const path = require('path');
const dotenv = require('dotenv');
const connectToDatabase = require('./src/db/mongoose');
const helmet = require('helmet');
const router = require('./src/routes/routes');
const openApiDocumentation = require('./src/swagger/openApiDocumentation');
const swaggerUi = require('swagger-ui-express');
const cors = require('cors');
const bodyParser = require("body-parser");
var app = express();
const session = require('express-session');
const MongoStore = require('connect-mongo');
const port = process.env.PORT || 3000;
dotenv.config();
connectToDatabase(); //This removed to simplify the connection
app.use(express.json());
app.use(express.static('src/css'));
app.use(express.static('src/js'));
app.use(express.static('scripts'));
app.use(express.static('controllers'));
app.use(express.static(__dirname + '/views'));
app.use(express.static("views"));
app.use('/', express.static(path.join(__dirname, 'views'),{extensions:['html']}));
app.use('/api', swaggerUi.serve, swaggerUi.setup(openApiDocumentation));
app.use(function(req, res, next){
res.locals.user = req.user;
next();
});
app.use("/v1/login", session({
name: 'auth',
secret: 'mykey',
httpOnly: true,
secure: true,
maxAge: 1000 * 60 * 60 * 7,
resave: false,
saveUninitialized: true,
store: MongoStore.create({
mongoUrl: '<redacted>'
})
}));
app.get('/name', (req, res) => {
let name;
if (!req.session) {
return res.status(404).send();
}
name = req.session.user.name;
return res.status(200).send({name});
})
app.use(function (req, res, next) {
res.locals.session = req.session;
next();
});
router.get("/vl/login", function(req, res) {
if (
typeof reqsession.user != "object" || (
typeof req.session.user.name == "undefined" &&
typeof req.session.user.password == "undefined")
) {
res.render("pages/index");
}
res.redirect("Login");
});
app.use(function(req, res, next) {
console.log('%s %s', req.method, req.url);
next();
});
app.engine('.html', require('ejs').__express);
app.set('view engine', 'ejs');
// index page
app.get('/', function(req, res) {
res.render('pages/index');
});
// about page
app.get('/about', function(req, res) {
res.render('pages/about');
});
app.use(function(req, res, next){
res.locals.user = req.user;
next();
});
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(helmet());
app.use('/v1', router);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.listen(port, () => console.log(`Server is running on Port: ${port}`));
userController.js
login: async (req, res) => {
const { userName, password } = req.body
const user = await userModel.findOne({ userName }).lean()
if (!user) {
return res.json({ status: 'error', error: 'Invalid username/password' })
}
if (await bcrypt.compare(password, user.password)) {
// the username, password combination is successful
const token = jwt.sign(
{
id: userModel._id,
userName: userModel.userName
},
JWT_SECRET
)
const { name } = req.body;
req.session.user = {
name,
isLoggedIn: true
}
try {
await req.session.save();
} catch (err) {
console.error('Error saving to session storage: ', err);
return next(new Error('Error creating user'));
}
return res.json({ status: 'ok', data: token })
}
res.json({ status: 'error', error: 'Invalid username/password' })
},
logout: async (req, res, next) => {
try {
await await req.session == null;
} catch (err) {
console.error('Error logging out:', err);
return next(new Error('Error logging out'));
}
return res.json({ status: 'ok'})
},
routes.js
const express = require('express');
const router = express.Router();
const newUser = require('../controllers/userController');
const company = require('../controllers/companyController');
const upload = require('../controllers/upload');
const auth = require('../middleware/auth');
/* GET response for '/'/*
router.get('/', (req, res) => {
res.redirect('/');
}) */
//generate token
router.get('/token', newUser.generateToken);
//login
router.post('/login', newUser.login);
//logout
router.post('/logout', newUser.logout);
//create service user
router.post('/addServiceUser', newUser.addServiceUser);
//Add user
router.post('/users', newUser.addUser);
//remove user
router.delete('/users/:id',auth, newUser.removeUser);
//Get All users
router.get('/users',auth, newUser.getAllUsers);
//Get User
router.get('/user/:id',auth, newUser.getUser);
//Get first name
router.get('/users/:id/firstName',auth, newUser.getUserFirstName);
//Set first name
router.put('/users/:id/firstName',auth, newUser.setUserFirstName);
//Get last name
router.get('/users/:id/lastName',auth, newUser.getUserLastName);
//Set last name
router.put('/users/:id/lastName',auth, newUser.setUserLastName);
//Get user email
router.get('/users/:id/email',auth, newUser.getUserEmail);
//set user email
router.put('/users/:id/email',auth, newUser.setUserEmail);
//Get user phone
router.get('/users/:id/phone',auth, newUser.getUserPhone);
//set user phone
router.put('/users/:id/phone',auth, newUser.setUserPhone);
//get user age
router.get('/users/:id/age',auth, newUser.getUserAge);
//set user age
router.put('/users/:id/age',auth, newUser.setUserAge);
//set user status
router.put('/users/:id/status',auth, newUser.setUserStatus);
//get user status
router.get('/users/:id/status',auth, newUser.getUserStatus);
//set user level
router.put('/users/:id/level',auth, newUser.setUserLevel);
//get user level
router.get('/users/:id/level',auth, newUser.getUserLevel);
//get user gender
router.get('/users/:id/gender',auth, newUser.getUserGender);
//set user gender
router.put('/users/:id/gender',auth, newUser.setUserGender);
//set user address
router.put('/users/:id/address',auth, newUser.setUserAddress);
//get user address
router.get('/users/:id/address',auth, newUser.getUserAddress);
//get active users
router.get('/users/status/active',auth, newUser.getActiveUsers);
//get inactive users
router.get('/users/status/inactive',auth, newUser.getInActiveUsers);
//get non admin users
router.get('/users/level/intern',auth, newUser.getInternUsers);
//get mentor users
router.get('/users/level/mentor',auth, newUser.getMentorUsers);
//Get Avatar
router.get('/users/:id/avatar',auth, newUser.getUserAvatar);
//Set Avatar
router.put('/users/:id/avatar',auth, upload.single('avatar'), newUser.setUserAvatar);
//Delete Avatar
router.delete('/users/:id/avatar',auth, newUser.removeUserAvatar);
//Add Companies
router.post('/companies/:id/team', auth, company.setUserTeamName);
module.exports= router;
It looks like in your logout function, the way your attempting to "logout" the user is setting req.session to null.
As you've figured out this doesn't act how you've expected. The correct way to logout a user would be calling req.session.destroy() usually accompanied by a redirect back to the login page:
return res.redirect("/login");
This will completely remove or, destroy the session and log the user out.

I keep getting "Login sessions require session support" when I try to use tokens

So I am following a tutorial on how to use JSON tokens and I am getting an error, it was working fine using sessions but I can't figure out why I am having trouble, it is the exact code
this is my authenticate.js file:
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const User = require("./models/user");
const JwtStrategy = require("passport-jwt").Strategy;
const ExtractJwt = require("passport-jwt").ExtractJwt;
const jwt = require("jsonwebtoken"); // used to create, sign, and verify tokens
const config = require("./config.js");
exports.local = passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
exports.getToken = function (user) {
return jwt.sign(user, config.secretKey, { expiresIn: 3600 });
}; // config.secretKey is a string of random numbers
const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = config.secretKey;
exports.jwtPassport = passport.use(
new JwtStrategy(opts, (jwt_payload, done) => {
console.log("JWT payload:", jwt_payload);
User.findOne({ _id: jwt_payload._id }, (err, user) => {
if (err) {
return done(err, false);
} else if (user) {
return done(null, user);
} else {
return done(null, false);
}
});
})
);
exports.verifyUser = passport.authenticate("jwt", { session: false });
This is my app.js file (the main file):
const createError = require("http-errors");
const express = require("express");
const path = require("path");
const logger = require("morgan");
const config = require("./config");
const indexRouter = require("./routes/index");
const usersRouter = require("./routes/users");
const mongoose = require("mongoose");
const passport = require("passport");
const url = config.mongoUrl;
const connect = mongoose.connect(url, {
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true,
});
connect.then(
() => console.log("Connected correctly to server"),
(err) => console.log(err)
);
const app = express();
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// app.use(cookieParser("12345-67890-09876-54321"));
app.use(passport.initialize());
app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use(express.static(path.join(__dirname, "public")));
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
// render the error page
res.status(err.status || 500);
res.render("error");
});
module.exports = app;
this is the routes/users.js file (I believe the problem is here because I can sign-up (create new users) but I can't login with the same users)
const express = require("express");
const User = require("../models/user");
const passport = require("passport");
const authenticate = require("../authenticate");
const router = express.Router();
/* GET users listing. */
router.get(
"/",
function (req, res, next) {
res.send('send users')
}
);
router.post("/signup", (req, res) => {
User.register(
new User({ username: req.body.username }),
req.body.password,
(err, user) => {
if (err) {
res.statusCode = 500;
res.setHeader("Content-Type", "application/json");
res.json({ err: err });
} else {
if (req.body.firstname) {
user.firstname = req.body.firstname;
}
if (req.body.lastname) {
user.lastname = req.body.lastname;
}
user.save((err) => {
if (err) {
res.statusCode = 500;
res.setHeader("Content-Type", "application/json");
res.json({ err: err });
return;
}
passport.authenticate("local")(req, res, () => {
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.json({
success: true,
status: "Registration Successful!",
});
});
});
}
}
);
});
// I tried to add a console.log inside of the .post() route but it never reach it
router.post(
"/login",
passport.authenticate("local"),
(req, res) => {
const token = authenticate.getToken({ _id: req.user._id });
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.json({
success: true,
token: token,
status: "You are successfully logged in!",
});
}
);
router.get("/logout", (req, res, next) => {
if (req.session) {
req.session.destroy();
res.clearCookie("session-id");
res.redirect("/");
} else {
const err = new Error("You are not logged in!");
err.status = 401;
return next(err);
}
});
module.exports = router;
Basically, every time that i go to localhost:3000/users/login and send a POST request with the username and password, it tells me that I need to use express-session but I am trying to use tokens instead of session
The problem is caused when passport.authenticate('local') is called in routes/users.js file. It is a middleware that automatically calls req.login function in case correct username and password is provided.
The req.login() in turn, implements sessions in order to serialise the user in the session.
You can solve the issue by adding another parameter to passport.authenticate() as passport.authenticate('local', {session: false}. This ensures sessions are not implemented in the 'local' strategy and subsequently login can be performed.
Thanks, it helped me. You have to remove app.use(passort.session) from app.js and do
router.post('/login', passport.authenticate('local', { session: false }), (req, res) => {
var token = authenticate.getToken({ _id: req.user._id });
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({ success: true, token: token, status: 'You are successfully logged in!' });
});

Unauthorized when logged in?

I am logging in successfully, however, I am getting unauthorized when I'm trying to access my authenticated-only route. I don't understand what I am doing wrong here, it successfully logs me in and returns the user, where am I wrong?
Here's my code:
This here is basically the server configuration for the backend.
server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors')
const passport = require('passport')
// passport
const cookieParser = require('cookie-parser')
const session = require('cookie-session')
const { COOKIE_NAME } = require('./client/src/common/config')
const app = express();
// Bodyparser Middleware
app.use(bodyParser.json());
// DB Config
const db = require ('./config/keys').mongoURI;
// Connect to MongoDB
mongoose
.connect(db, {useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false})
.then(() => console.log('Mongo DB Connected...'))
.catch(err => console.log(err));
// CORS
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
const secret = process.env.APP_SECRET
const env = process.env.NODE_ENV || 'development'
const isLocal = env === 'development'
/* Session Setup */
app.use(cookieParser()) // read cookies (needed for auth)
if (!isLocal) {
app.set('trust proxy', 1)
}
app.use(
session({
httpOnly: false,
name: COOKIE_NAME,
keys: [secret],
secure: !isLocal,
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
})
)
/* Session management with Passport */
require('./passport')(passport)
app.use(passport.initialize())
app.use(passport.session())
// Register Schema
require('./models/User')
// Insert some default users
// require('./config/_insertDefaultUsers')
const patients = require('./routes/api/patients');
const auth = require('./routes/api/auth');
const drugs = require('./routes/api/drugs');
const trainees = require('./routes/api/trainees')
// Use Routes
app.use('/api/patients', patients);
app.use('/api/drugs', drugs);
app.use('/api/trainees', trainees)
app.use('/api/auth', auth);
app.use(cors())
// Connect to deployment port or localhost
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
access.js this is a basic middleware to check for authentication, so I can add it in my routes
const ROLES = require('.././client/src/common/roles')
/** Access middleware to ensure user is allowed to access certain routes */
const AccessMiddleware = {
hasAccess: (req, res, next) => {
if (!req.isAuthenticated()) {
req.session.redirectTo = req.originalUrl
return res.status(401).json({ success: false, error: 'unauthorized' })
}
next()
},
hasAdminAccess: (req, res, next) => {
if (!req.isAuthenticated() || req.user.role !== ROLES.ADMIN) {
req.session.redirectTo = req.originalUrl
return res.status(401).json({ success: false, error: 'unauthorized' })
}
next()
},
}
module.exports = AccessMiddleware
auth.js route and this is basically the authentication API which allows me to login and so on
const express = require('express');
const router = express.Router();
const passport = require('passport')
const AccessMiddleware = require('../../config/access')
const errorResponse = (res, error) => {
res.status(400).json({ success: false, error })
}
router.get('/test', (req, res) => {
res.json({ success: true, message: 'Test API route working fine!' })
})
router.get('/authenticated-only', AccessMiddleware.hasAccess, (req, res) => {
res.json({ success: true, message: 'You have auth access!' })
})
router.get('/admin-only', AccessMiddleware.hasAdminAccess, (req, res) => {
res.json({ success: true, message: 'You have admin access!' })
})
router.post('/login', (req, res, next) => {
const { email, password } = req.body
if (!email || !password) {
return errorResponse(res, 'Invalid credentials')
}
// Authenticate the user using the credentials provided
passport.authenticate('local', { session: true }, function (err, user) {
if (err) {
return errorResponse(res, 'Invalid credentials')
}
// When using passport with callback, we have to manually call req.login to set the Cookie
req.login(user, async () => {
res.json({ success: true, user })
})
})(req, res, next)
})
module.exports = router
exports.errorResponse = errorResponse
For anyone looking for a solution:
const secret = "secrethere"
app.use(cookieParser("secrethere"))
The issue seems to have been that I was not using the same secret within the server file.

How to pass data into ejs without res.render?

I want to send a variable value after succesful register but i have to do that without using res.render because i have some of flash messages if i want to show all of them i have to use res.redirect otherwise it does not work for example : who will try to register the flash message show "you cant use a password less than 6 character". How can i passs variable value to my ejs page for hide or display some of nav bar links according to after login or register or logout
// Here is my app.js file
// Config folder
require('dotenv').config();
const port = process.env.port;
const dbUrl = process.env.dbUrl;
// İmport required npms
const express = require("express");
const mongoose = require("mongoose");
const session = require("express-session");
const connectMongo = require('connect-mongo');
const flash = require("connect-flash");
const passport = require("passport");
const app = express();
// Passport Config
require("./config/passport")(passport);
// Db Connection And Permissions
mongoose.connect(dbUrl, {
useNewUrlParser: process.env.useNewUrlParser,
useUnifiedTopology: process.env.useUnifiedTopology,
useCreateIndex: process.env.useCreateIndex
});
// Express-Session Settings , Permanenet Session
const mongoStore = connectMongo(session);
app.set('trustproxy', true)
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true,
store: new mongoStore({ mongooseConnection: mongoose.connection }),
cookie: {
maxAge: 86400000
}
}));
// Passport Middleware
app.use(passport.initialize());
app.use(passport.session());
// The Navbar Display Links According To Log in
app.use((req, res, next) => {
const userId = req.session;
if (userId) {
res.locals = {
displayLink: true
}
} else {
res.locals = {
displayLink: false
}
}
next();
});
// Set ejs settings, middleware, static folders
app.use(express.static("public"));
app.set("view engine", "ejs");
// Connect flash
app.use(flash());
// Global variables
app.use((req, res, next) => {
res.locals.success_msg = req.flash("success_msg");
res.locals.error_msg = req.flash("error_msg");
res.locals.error = req.flash("error");
next();
});
// Import Pages
const index = require("./routes");
const user = require("./routes/user");
// Routes
app.use("/", index);
app.use("/user", user);
app.listen(port, (err) => { if (err) throw err; console.log("No problem"); });
// Here is my user.js file
const express = require("express");
const router = express.Router();
const User = require("../models/User");
const bcrypt = require("bcrypt")
const bodyParser = require('body-parser');
const passsport = require("passport");
router.use(bodyParser.urlencoded({ extended: false }));
router.use(bodyParser.json());
// Users Routing Operations
// Get Requests
// Login Page
router.get("/login", (req, res) => {
res.render("pages/login");
});
// Register Page
router.get("/register", (req, res) => {
res.render("pages/register");
});
// Post Requests
// After Finishing Register
router.post("/register", async (req, res) => {
const { name, email, password, rptPassword } = req.body;
let errors = [];
// Check required fields
if (!name || !email || !password || !rptPassword) {
errors.push({ msg: "Lütfen bütün alanları doldurunuz" });
}
// Check passwords match
if (password !== rptPassword) {
errors.push({ msg: "Şifreler eşleşmiyor" });
}
// Check password length
if (password.length < 6) {
errors.push({ msg: "Şifreniz en az 6 karakterden oluşmalı" });
}
if (errors.length > 0) {
res.render("pages/register", {
errors,
name,
email,
password,
rptPassword
});
} else {
User.findOne({ email: req.body.email }).then(async (user) => {
if (!user) { // If user doesnt exist before
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password, salt);
req.body.password = hashedPassword;
User.create(req.body, () => { });
req.flash("success_msg", "Kayıt Tamamlandı");
res.redirect("/user/register");
} else { // If user already exist
errors.push({ msg: "Bu Email adresi kullanımda" })
res.render("pages/register", {
errors,
name,
email,
password,
rptPassword
});
res.redirect("/user/register");
}
});
}
});
// Login handle
router.post("/login", (req, res, next) => {
passsport.authenticate("local", {
successRedirect: "/",
failureRedirect: "/user/login",
failureFlash: true
})(req, res, next);
});
// After Loging Out
router.get("/logout", (req, res) => {
req.logout();
req.flash("success_msg", "Çıkış Yaptınız");
res.redirect("/user/login");
});
module.exports = router;
I think one of the solutions for that is to use multiple query strings
and then you can handle the errors in the app.get functions like so
router.post("/register", async (req, res) => {
const { name, email, password, rptPassword } = req.body;
// Check required fields
if (!name || !email || !password || !rptPassword) {
res.redirect('/register?error=error-1')
}
then in the handle it like so
// Register Page
router.get("/register", (req, res) => {
if (req.query.error === 'error-1' )
res.render("pages/register" ,{
msg: "Lütfen bütün alanları doldurunuz"
});
});
and so you can handle all errors by giving them unique code

"TypeError: Cannot read property 'email' of undefined" in nodejs authentication system

I'm trying to run an authentication module using express-session and passport.
server.js
var express = require("express");
var session = require('express-session');
var connection = require('./config');
var bodyParser = require('body-parser');
var passport = require('passport');
const redis = require('redis');
const redisStore = require('connect-redis')(session);
const client = redis.createClient();
var app = express();
var router = express.Router();
var authController=require('./controllers/auth-controller');
var regController=require('./controllers/reg-controller');
app.use(session({secret: 'secret', store: new redisStore({ host: 'localhost', port: 8000, client: client,ttl : 260}), saveUninitialized: true, resave: true}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
router.get('/',(req,res) => {
let sess = req.session;
if(sess.email){
return res.redirect('/admin');
}
res.sendFile( __dirname + '/' + 'index.html' );
})
router.post('/login',(req,res) => {
sess = req.session;
sess.email = req.body.email;
res.end('done');
});
router.get('/admin',(req,res) => {
sess = req.session;
if(sess.email) {
res.write(`<h1>Hello ${sess.email} </h1><br>`);
res.end('<a href='+'/logout'+'>Logout</a>');
}
else {
res.write('<h1>Please login first.</h1>');
res.end('<a href='+'/'+'>Login</a>');
}
});
router.get('/logout',(req,res) => {
req.session.destroy((err) => {
if(err) {
return console.log(err);
}
res.redirect('/');
});
});
app.use('/', router);
app.post('/api/register',regController.register);
app.post('/api/authenticate',authController.authenticate);
console.log(authController);
app.post('/controllers/register-controller', regController.register);
app.post('/controllers/authenticate-controller', authController.authenticate);
app.listen(8000);
config.js
var mysql = require('mysql');
const localAuth = require('./controllers/timeoutcontroller');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password',
database : 'dbname'
});
connection.connect(function(err){
if(!err) {
console.log("Database is connected");
} else {
console.log("Error while connecting with database");
}
});
function ensureAuthenticated(req, res, next) {
if (!(req.headers && req.headers.authorization)) {
return res.status(400).json({
status: 'Please log in'
});
}
// decode the token
var header = req.headers.authorization.split(' ');
var token = header[1];
localAuth.decodeToken(token, (err, payload) => {
if (err) {
return res.status(401).json({
status: 'Token has expired'
});
} else {
return knex('users').where({id: parseInt(payload.sub)}).first()
.then((user) => {
next();
})
.catch((err) => {
res.status(500).json({
status: 'error'
});
});
}
});
}
module.exports = connection;
Here I am able to connect to the mysql database and the connection is set but I'm getting the error
TypeError: Cannot read property 'email' of undefined
If someone could explain why this happens, it'd be great.
Thanks.
This means that your variable sess is undefined. Your req.session variable does not have any value inside it. You need to check why is that happening.
Try this:
let sess = req.session;
sess.user = req.user;
req.mysess=sess.user //pass like this
router.get('/', function(req, res, next) {
let sess = req.mysess;
console.log(sess);
});

Resources