*Please don't ignore the question looking at its length. It might seem long because I've attached the code. The actual problem statement is really small.
I've tried integrating Passport, Koa & MongoDB from the last two days. I've been failing and am unable to get any references regarding the problem I've been facing. My primary concern is to just get the login module working.
My problem is that the function to handle post request for login in my index routes, associated with koa-passport is being called and ctx.body is also being sent as a response but successRedirect and failureRedirect aren't working. Down below are the files that I'm using.
In the auth.js, I have console logged user inside the new LocalStrategy, right after var user = line. Nothing is logged to the console.
auth.js
const passport = require('koa-passport')
const LocalStretegy = require('passport-local').Strategy
const mongoose = require('mongoose')
const User = mongoose.model('User', mongoose.Schema({}, { strict: false }))
function *getUser(name) {
let user = yield User.find({username: name})
return user
}
passport.serializeUser( (user, done) => {
done(null, user.id)
})
passport.deserializeUser( async (id, done) => {
done(null, user)
})
passport.use(new LocalStretegy( (username, password, done) => {
co(function*() {
try {
var user = yield getUser(username)
if (user.username === username && user.password === password) {
return user
} else {
return null
}
} catch(e) {
return null
}
}).then((user) => {
done(null, user)
})
}))
module.exports = passport
/routes/index.js
const router = require('koa-router')()
const sendfile = require('koa-sendfile')
const passport = require('koa-passport')
const mongoose = require('mongoose')
const Counter = mongoose.model('Counter', mongoose.Schema({}, { strict: false }))
router.post('/custom', (ctx, next) => {
return passport.authenticate('local', function(user, info, status) {
if (user === false) {
ctx.status = 401
ctx.body = { success: false }
ctx.body = { success: true }
} else {
return ctx.login(user)
}
})(ctx, next)
})
router.post('/login', (ctx) => {
passport.authenticate('local', {
successRedirect: '/dash-board',
failureRedirect: '/login'
})
ctx.body={status: 'okay'}
})
router.get('/logout', (ctx) => {
ctx.logout()
ctx.redirect('/')
})
module.exports = router
app.js
const Koa = require('koa')
const router = require('koa-router')()
const app = new Koa()
app.proxy = true
//Routes
const users = require('./routes/users')
const index = require('./routes/index')
//Error handler
const onerror = require('koa-onerror')
onerror(app)
//MongoDB connection
const mongoose = require('mongoose')
mongoose.Promise = global.Promise
try{
mongoose.connect('mongodb://<user>:<pass>#<something>.mlab.com:<number>/<someDB>?poolSize=10&retries=5')
} catch(err) {
console.log(err)
}
// Sessions
const convert = require('koa-convert')
const session = require('koa-generic-session')
const MongoStore = require('koa-generic-session-mongo')
app.keys = ['key1']
app.use(convert(session({
store: new MongoStore()
})))
//body parser
const bodyparser = require('koa-bodyparser')
app.use(bodyparser({
enableTypes:['json', 'form', 'text']
}))
//passport
require('./auth')
const passport = require('koa-passport')
app.use(passport.initialize())
app.use(passport.session())
app.use(index.routes(), index.allowedMethods(), users.prefix('/index'))
app.use((ctx, next) => {
if(ctx.isAuthenticated()) {
return next()
} else {
ctx.redirect('/')
}
})
app.use((ctx, next) => {
return next().catch(function (err) {
ctx.status = err.status || 500;
if (err.expose) {
ctx.body = err.message;
}
})
})
module.exports = app
I am unable to deduce anything from here on. I've searched extensively and changed the code to work until here.
Maybe it has something to do with this code in which user does not seem to be declared.
passport.deserializeUser( async (id, done) => {
done(null, user)
})
Related
I know that there are some questions like this already, but i already tried every single response and nothing works, i don't know what the heck to add to app.js to make it work and store the sessions.
Here is my app.js:
const express = require("express");
const cors = require("cors");
const usersRouter = require("./routes/users");
const passport = require("passport");
const cookieParser = require("cookie-parser");
const session = require("express-session");
require("dotenv").config();
const app = express();
const connectDB = require("./db/connect");
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser(process.env.SESSION_SECRET));
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
cookie: { secure: false },
})
);
app.use(passport.initialize());
app.use(passport.session());
app.use(cors());
app.use("/api/v1/users", usersRouter);
const PORT = process.env.PORT || 5000;
const start = async () => {
try {
await connectDB(process.env.MONGO_URI);
app.listen(PORT, console.log(`Server is listening on port: ${PORT}....`));
} catch (error) {
console.log(error);
}
};
const notFound = require("./middleware/notFound");
app.use(notFound);
start();
My passport-config looks like this:
const localStrategy = require("passport-local").Strategy;
const bcrypt = require("bcryptjs");
const User = require("../models/user");
const initialize = (passport) => {
const authenticateUser = async (email, password, done) => {
let user = await User.findOne({ email: email });
User.findOne({ email: email });
if (!user) {
return done(null, false, {
message: "That email is not registered",
});
}
try {
if (await bcrypt.compare(password, user.password)) {
return done(null, user, { message: "User logged in" });
} else {
return done(null, false, { message: "Password incorrect" });
}
} catch (e) {
return done(e);
}
};
passport.use(new localStrategy({ usernameField: "email" }, authenticateUser));
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (user, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});
};
module.exports = initialize;
And my users router looks like this:
const express = require("express");
const router = express.Router();
const passport = require("passport");
const initializePassport = require("../config/passport-config");
initializePassport(passport);
const { postRegister } = require("../controllers/register");
router.route("/register").post(postRegister);
router.post("/login", function (req, res, next) {
passport.authenticate("local", function (err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).json({ message: info.message });
}
console.log(req.session.passport);
res.status(200).json(user);
})(req, res, next);
});
module.exports = router;
I'm making a middleware to authorize or to not authorize the call to another endpoint based on if it is authenticated or if it isn't.
Here is how that middleware looks:
const checkAuthenticated = (req, res, next) => {
const isAuthenticated = req.isAuthenticated();
console.log(req.session.passport);
if (isAuthenticated) {
next();
}
next();
};
module.exports = checkAuthenticated;
const checkNotAuthenticated = (req, res, next) => {
const isAuthenticated = req.isAuthenticated();
if (!isAuthenticated) {
res
.status(401)
.json({ msg: "Not allowed to this path without credentials" });
}
};
module.exports = checkNotAuthenticated;
req.session.passport is undefined, isAuthenticated() is always false, i don't know what to add.
Your bug in the deserializer function:
It will work by changing your deserializer callback argument from user to id as shown below.
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
That was a very obvious bug to me, to be sure you are not missing any other thing, check the lengthy answer I gave to this on another thread a few minutes ago here: https://github.com/jaredhanson/passport/issues/914#issuecomment-1241921637
Good luck.
I'm struggling with understanding how authentication with Passport works. I'm using Express.js as my routing management package and I have 3 usable routes and one router :
routes
├── auth.endpoints.js
├── concept.endpoints.js
├── routes.js
└── user.endpoints.js
routes.js is my API gateway, handling traffic to the different routes and it looks like this :
const { isConnected } = require("../middleware/is.connected"); //middleware that checks whether req.user exists or not
module.exports = function (app, passport) {
const userRouter = require("./user.endpoints");
const authRouter = require("./auth.endpoints")(passport);
const conceptRouter = require("./concept.endpoints");
const logger = require("../log/winston.logger");
const logLevels = require("../log/log.levels.json").levels;
app.use(function (req, res, next) {
logger(req.method + " " + req.url, logLevels.http);
next();
});
app.use("/auth", authRouter);
app.use(isConnected);
app.use("/api/user", userRouter);
app.use("/api/concept", conceptRouter);
};
The issue is in the auth route, more precisely, the signup endpoint :
// #ts-nocheck
const express = require("express");
const router = express.Router();
const { isConnected } = require("../middleware/is.connected");
const ErrorMiddleware = require("../middleware/error.middleware");
const { isAValidInstance } = require("../utils/schema.validator");
const userSchema = require("../database/schemas/user.schema.json");
const User = require("../database/models/user.model");
const logger = require("../log/winston.logger");
const SHA256 = require("js-sha256");
const logLevels = require("../log/log.levels.json").levels;
const ResponseError = require("../responses/response.error");
const ResponseSuccess = require("../responses/response.success");
module.exports = function (passport) {
router.get(
"/logout",
isConnected,
ErrorMiddleware(function (req, res, next) {
req.logout();
res.clearCookie("connect.sid", {
path: "/",
});
// eslint-disable-next-line node/handle-callback-err
req.session.destroy(function (err) {
ResponseSuccess.success(res);
});
})
);
router.post(
"/login",
passport.authenticate("local", {
successRedirect: "/auth/me",
failureRedirect: "/login",
})
);
router.get(
"/me",
isConnected,
ErrorMiddleware((req, res, next) => {
ResponseSuccess.success(res, req.user);
})
);
router.post(
"/signup",
ErrorMiddleware(async (req, res, next) => {
if (req.user !== undefined) {
res.redirect("/me");
return;
}
const user = req.body;
if (!isAValidInstance(user, userSchema)) {
logger("POST /auth/signup", logLevels.warn, "Invalid body");
ResponseError.badRequest(res);
return;
}
user.password = SHA256(user.password);
const createdUser = await User.createUser(user);
if (createdUser !== null) {
ResponseSuccess.success(res, createdUser);
} else {
ResponseError.unauthorized(res);
}
})
);
return router;
};
The problem is that after I sign up, I still have to manually login (at least via the backend and Postman) in order to be considered authenticated.
Is there something wrong with the way I'm doing things?
FYI, this is my current passport configuration :
// #ts-nocheck
const passport = require("passport");
const User = require("../database/models/user.model");
const SHA256 = require("js-sha256");
const LocalStrategy = require("passport-local").Strategy;
const session = require("express-session");
module.exports = function (app) {
passport.use(
new LocalStrategy(
{
usernameField: "email",
passwordField: "password",
},
async (email, password, done) => {
const user = await User.findUser(email, SHA256(password));
if (user == null) {
return done(null, false);
}
return done(null, user.user_id);
}
)
);
passport.serializeUser((userId, done) => {
return done(null, userId);
});
passport.deserializeUser(async function (userId, done) {
const user = await User.getUserByUserId(userId);
return done(null, user);
});
app.use(
session({ secret: "anything", resave: false, saveUninitialized: false })
);
app.use(passport.initialize());
app.use(passport.session());
return passport;
};
I feel like the serialisation isn't working correctly.
Many thanks in advance for your help!
Made a Question a few days ago on here, thought I had it figured out, even accepted the answer, because it was right regardless. but now I have the Same issue, same error.
Heres the Error.
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:558:11)
at ServerResponse.header (/Users/apple/Documents/Web Dev/collab/Backend/node_modules/express/lib/response.js:771:10)
at ServerResponse.send (/Users/apple/Documents/Web Dev/collab/Backend/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/Users/apple/Documents/Web Dev/collab/Backend/node_modules/express/lib/response.js:267:15)
at /Users/apple/Documents/Web Dev/collab/Backend/routes/index.js:90:23
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
code: 'ERR_HTTP_HEADERS_SENT'
}
Heres Index.js. Line 90 is at the very bottom,
# router.get("/", isAuth, (req, res)
const router = require("express").Router();
const passport = require("passport");
const bodyParser = require("body-parser");
const genPassword = require("../lib/passwordUtils").genPassword;
const connection = require("../config/database");
const mongoose = require("mongoose");
const User = mongoose.models.User;
const isAuth = require("./authMiddleware").isAuth;
// cors is needed with router.use else you have to put routes on the app.js
const cors = require("cors");
router.use(cors({ origin: "http://localhost:3001", credentials: true }));
// const isAdmin = require("./authMiddleware").isAdmin;
router.use(bodyParser.urlencoded({ extended: false }));
/**
* -------------- Post ROUTES ----------------
*
*/
router.post("/login", (req, res, next) => {
passport.authenticate("local", (err, user, info) => {
if (err) {
throw err;
} else if (!user) {
res.send("No User Exists");
} else {
req.logIn(user, (err) => {
if (err) throw err;
res.send(user);
return;
// console.log(req.user);
});
}
})(req, res, next);
});
router.post("/register", (req, res) => {
const saltHash = genPassword(req.body.repeatPassword);
const salt = saltHash.salt;
const hash = saltHash.hash;
const newUser = new User({
username: req.body.firstInput,
fName: "",
lName: "",
title: "",
hash: hash,
salt: salt,
});
newUser.save().then((user) => {});
res.sendStatus(200);
});
/**
* -------------- GET ROUTES ----------------
*
*/
router.post("/user", (req, res) => {
const fName = req.body.firstInput;
const lName = req.body.secondInput;
const title = req.body.repeatPassword;
const user = req.session.passport.user;
User.updateOne(
{ _id: user },
{ fName: fName, lName: lName, title: title },
function (err, result) {
if (err) {
res.sendStatus(401);
console.log(err);
} else {
res.sendStatus(200);
}
}
);
});
router.get("/", isAuth, (req, res) => {
const userMap = {};
User.find({}, function (err, users) {
users.forEach(function (user) {
userMap[user._id] = user;
});
return userMap;
})
.then((response) => {
res.status(200).json({ user: req.user, auth: true, response });
return;
})
.catch((err) => console.log(err));
});
module.exports = router;
Heres App.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require("passport");
const crypto = require("crypto");
const routes = require("./routes");
const isAuth = require("./routes/authMiddleware").isAuth;
const connection = require("./config/database");
const cors = require("cors");
app.use(cors({ origin: "http://localhost:3001", credentials: true }));
const User = mongoose.models.User;
const bodyParser = require("body-parser");
const MongoStore = require("connect-mongo")(session);
require("dotenv").config();
app.use(express.json());
// app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.urlencoded({ extended: true }));
const sessionStore = new MongoStore({
mongooseConnection: mongoose.connection,
collection: "sessions",
});
app.use(
session({
secret: "zdfbdaf",
resave: true,
saveUninitialized: true,
store: sessionStore,
cookie: {
cookie: { secure: false },
maxAge: 1000 * 60 * 60 * 24,
},
})
);
require("./config/passport");
app.use(passport.initialize());
app.use(passport.session());
app.use("/", routes);
app.listen(3000);
heres authMiddleware.js
module.exports.isAuth = (req, res, next) => {
if (req.isAuthenticated()) {
next();
// res.status(200).json({ user: req.user, auth: true });
} else {
res.status(401).json({ auth: false });
}
};
// module.exports.isAdmin = (req, res, next) => {
// if (req.isAuthenticated() && req.user.admin) {
// next();
// } else {
// res.status(401).json({ msg: 'You are not authorized to view this resource because you are not an admin.' });
// }
// }
Heres passport.js
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const connection = require("./database");
const mongoose = require("mongoose");
const User = mongoose.models.User;
const validPassword = require("../lib/passwordUtils").validPassword;
const cors = require("cors");
passport.use(cors({ origin: "http://localhost:3001" }));
const customFields = {
usernameField: "username",
passwordField: "password",
};
passport.use(
new LocalStrategy(customFields, (username, password, done) => {
User.findOne({ username: username })
.then((user) => {
if (!user) {
console.log("No user");
return done(null, false);
} else {
const isValid = validPassword(password, user.hash, user.salt);
if (isValid) {
console.log("Logged in");
return done(null, user);
} else {
console.log("Wrong Password");
return done(null, true);
}
}
})
.catch((err) => {
done(err);
});
})
);
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
})
.then((user) => {
done(null, user);
})
.catch((err) => done(err));
});
It only crashes half the time, kind of? It works at first, until you refresh the page. I am at a loss. Had someone in the discord also not know the issue. I'm begging for some help here. I'm losing my mind.
its because you are calling done twice once after finding the user
and second after .then block in passport.deserializeUser function
this will work:
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user)
});
});
I have been in the process of building a server using node.js, express.js, Mongoose, and MongoDB. After trying to implement passport and JWT authentication, I have encountered an error (seen in the link) every time I try to make a request to my '/login' endpoint. This error occurs when I make a request through Postman using a username and password from my database to test if the user is assigned a JWT token.
https://i.stack.imgur.com/g6e4Z.png
All of my endpoints, except for the one in my auth.js file, work fine in my index.js file, which is the main file where everything gets imported. I do not have any problems getting/staying connected to my database, so this leads me to believe that the issue stems from some mistake in the error handling.
This is how the middleware is set up in the index.js file, right above my endpoints.
'use strict';
const express = require('express');
const morgan = require('morgan');
const mongoose = require('mongoose');
const Models = require('./models');
const Movies = Models.Movie;
const Genres = Models.Genre;
const Directors = Models.Director;
const Users = Models.User;
function displayErrorMsg(err) {
console.error(err);
res.status(500).send(`Error: ${err}`);
}
function resJSON(model, res) {
return model.find().then(data => res.json(data));
}
const app = express();
mongoose
.connect('mongodb://localhost:27017/filmfeverDB', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(res => console.log('DB Connected!'))
.catch(err => console.log(err, err.message));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(`public`));
app.use(morgan('common'));
let auth = require('./auth')(app);
const passport = require('passport');
require('./passport');
passport.js
const passport = require("passport"),
LocalStrategy = require("passport-local").Strategy,
Models = require("./models.js"),
passportJWT = require("passport-jwt"),
config = require('./configs').config
let Users = Models.User,
JWTStrategy = passportJWT.Strategy,
ExtractJWT = passportJWT.ExtractJwt;
passport.use(
new LocalStrategy(
{
usernameField: "Username",
passwordField: "Password"
},
(username, password, callback) => {
console.log(username + " " + password);
Users.findOne({ Username: username }, (error, user) => {
if (error) {
console.log(error);
return callback(error);
}
if (!user) {
console.log("incorrect username");
return callback(null, false, {
message: "Incorrect username."
});
}
console.log("finished");
return callback(null, user);
});
}
)
);
passport.use(
new JWTStrategy(
{
jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
secretOrKey: config.passport.secret
},
(jwtPayload, callback) => {
return Users.findById(jwtPayload._id)
.then(user => {
return callback(null, user);
})
.catch(error => {
return callback(error);
});
}
)
);
auth.js
const jwt = require("jsonwebtoken"),
passport = require("passport");
require("./passport");
let generateJWTToken = user => {
return jwt.sign(user, config.passport.secret, {
subject: user.Username,
expiresIn: config.passport.expiresIn,
algorithm: "HS256"
});
};
/* POST login. */
module.exports = router => {
router.post("/login", (req, res) => {
passport.authenticate("local", { session: false }, (error, user, info) => {
if (error || !user) {
return res.status(400).json({
message: "something is not right",
user: user
});
}
req.login(user, { session: false }, error => {
if (error) {
res.send(error);
}
let token = generateJWTToken(user.toJSON());
return res.json({ user, token });
});
})(req, res);
});
};
Here is my Mongoose connection and my imports of the auth.js, passport.js, and passport module files located in my index.js file.
mongoose
.connect('mongodb://localhost:27017/filmfeverDB', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(res => console.log('DB Connected!'))
.catch(err => console.log(err, err.message));
let auth = require('./auth')(app);
const passport = require('passport');
require('./passport');
If anyone has any ideas, please let me know.
I have a nodejs backend with sessions made using express-session npm module. I want to test the sessions using postman.
What I want is a user should be allowed to access the users list via the /getUsers route only if he is currently in a session. But what is happening is when I test the backend using postman even after logging in the user is unable to access the users using the /getUsers route. Is this something to do with postman?
Here is my app.js
const express = require("express");
const app = express();
const authRoutes=require('./routes/auth');
const mongoose=require('mongoose');
const bodyParser = require("body-parser");
require("dotenv").config();
const nodemailer = require("nodemailer");
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const cors = require('cors');
app.use(cors({
origin:['http://localhost:8080'],
methods:['GET','POST'],
credentials: true // enable set cookie
}));
app.use(
// Creates a session middleware with given options.
session({
name: 'sid',
saveUninitialized: false,
resave: false,
secret: 'sssh, quiet! it\'s a secret!',
cookie: {
httpOnly: true,
maxAge: 1000 * 60 * 60 * 2,
sameSite: true,
secure: true
}
})
);
mongoose.connect(process.env.LOCAL_MONGO_URI,{useNewUrlParser:true},function (err) {
if (err) throw err
console.log("Connected to local mongo db database");
});
app.get("/",(req,res)=> {console.log("A request was made to /")
console.log("/GET called");
});
app.use(bodyParser.json());
app.use("/",authRoutes);
const port = process.env.PORT||8080
app.listen(port,()=> {
console.log("Hello world");
})
Here is my routes/auth.js:
const express = require("express");
const {
signup,login,verifyemail,requiresLogin,getUsers,logout
} = require("../handler/auth")
const router = express.Router();
router.post("/signup",signup);
router.post("/login",login);
router.get("/verifyemail/:token",verifyemail);
router.get("/getUsers",requiresLogin,getUsers);
router.get("/getUsers",requiresLogin,getUsers);
router.get("/logout",requiresLogin,logout);
module.exports=router;
Here is my handler/auth.js
const User = require("../models/user");
const bcrypt = require('bcrypt');
const crypto = require('crypto');
exports.signup = async (req, res) => {
const email = req.body.email;
User.findOne({email},function(err,user){
if(err) return res.status(500).json({message:err.message});
else if(user) return res.status(403).json({"message":"User exists"});
const password = req.body.password;
const name = req.body.name;
bcrypt.hash(password, 10)
.then(async function(hashed_password) {
const user = await new User({email,name,hashed_password});
user.emailVerificationToken = crypto.randomBytes(20).toString('hex');
user.emailVerificationTokenExpires = Date.now() + 3600000*24;
await user.save(function(err) {
if(!err) {
const resetURL = `http://${req.headers.host}/verifyemail/${user.emailVerificationToken}`;
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
from: 'admin#pinclone.com',
to: email,
subject: 'Email verification link',
html: `Verify your email here to login to your account`,
};
sgMail.send(msg);
return res.json({message:"verify email address to login"});
}
return res.status(500).send({ message: err.message });
});
})
.catch(function(error){
res.status(500).send({message:error.message});
});
});
};
exports.login = (req,res) => {
const email = req.body.email;
const password = req.body.password;
User.findOne({email},function(err,user) {
if(err) return res.status(500).json({message:err.message});
if(!user) return res.status(403).json({"message":"User does not exists"});
bcrypt.compare(password,user.hashed_password,(err,result) => {
if(result) {
if(user.isVerified)
return res.status(200).json({"message":"successfully logged in"});
else
return res.status(403).json({"message":"user is not verified"});
}
else return res.status(403).json({message: "email address password do not match"});
});
});
};
exports.verifyemail = async (req,res) => {
User.findOneAndUpdate({emailVerificationToken: req.params.token,emailVerificationTokenExpires: { $gt: Date.now() }}, {$set:{isVerified:true}}, {new: true}, (err, user) => {
if (err) {
res.status(403).send({message:"Link invalid or expired"});
// res.status(500).send({message:"Something wrong when updating data!"});
}
if(user) {
res.status(200).send({"message":"email verification successful you can login now!"});
}
});
};
exports.requiresLogin = (req, res, next) => {
if (req.cookies.sid) {
return next();
} else {
var err = new Error('You must be logged in to view this page.');
err.status = 401;
return next(err);
}
};
exports.logout = (req, res) => {
res.clearCookie('sid');
res.send("logout success");
};
exports.getUsers = (req,res) => {
User.find({},function(err,users){
res.send(users);
});
};
You can set session in tab Header with your key.
You can read https://www.toolsqa.com/postman/sessions-in-postman/ for more detail.
You should read at How to use Sessions in Postman? part.