how to check every request have the cookie in express js - javascript

I am building a crud application using react and node , so i need to check for every request whether the cookie is present or not.
app.all("*", (req,res) => {
// cookie doesn't exist redirect to login
if(cookieExist(req.headers.cookie)){
// how to pass to the next layer ? load the routes below code etc..
next();
}else{
res.redirect("/login")
}
})
const routes = require("./routes/route");
app.use(bodyParser.json());
app.use(cors());
app.use("/apiServices", apiRoutes)
what i am missing here, getting next() as not defined.

Define next as argument
app.all("*", (req,res, next) => {
// cookie doesn't exist redirect to login
if(cookieExist(req.headers.cookie)){
// how to pass to the next layer ? load the routes below code etc..
next();
}else{
res.redirect("/login")
}
})

Related

What is the difference between redirect and next in NodeJs?

I quite don't understand the difference between these two:
app.get('*', function(req, res, next) {
next();
//ROUTE 1
});
app.get('*', function(req, res) {
res.redirect('/some');
//ROUTE 2
});
app.get('/some', function(req, res) {
res.send("success");
//ROUTE 3
});
When I try making request to ROUTE 1, I get response success but ROUTE 2 doesn't show this response. Why is that?
What I want to do is:
Every request should pass from ROUTE 1 and the control should be handled to a SPECIFIC route, which I would write in it ROUTE if-else statement (not like next(), which sends control to next MATCHING route).
For example:
app.get('*', function(req, res, next) {
if(x==y){
//call SPECIFIC route 3
} else {
// call SPECIFIC route 4 (another route)
//ROUTE 1
});
I tried to do it with redirect but it's not working.
Thank you.
EDIT:
Routes would be: /checkIfSession exists. I would use express-session to check if user's username exists or not in session.
If exists, I want to send control to if otherwise else.
Assume the requests are:
http://198.168.43.200:3000/checkIfSession
http://198.168.43.200:3000/some
(I will call only 1st request).
EDIT 2: I tried following but I don't get any response when I request:
app.use(function (req, res, next) {
if(2==2){
res.redirect("/session");
} else {
res.end("else");
}
});
app.get("/session", function(req, res){
res.write("session");
res.end();
});
app.get("/some", function(req, res){
res.write("some");
res.end();
});
Request: /some
I suppose if you want your routes to go through some kind of authentication first you can use middleware in your routes.
Below is sample code:
app.get('/some', checkSession, function(req, res) {
res.send("success");
});
// this is the middleware function
function checkSession(req, res, next) {
// do your checking here
if (x===y) {
next();
//continue users access to protected API
}
else {
res.redirect('/');
// redirect user to the default login page
}
}
In this above example there are 2 Cases
Case1:
x === y as from your given example I'am assuming users is logged in, so when the user is accessing /some section of your website he will receive Success from the server.
This is the use of your next() function i.e. it continues the execution of that api or sends the data whatever the user is requesting. Something similar to continue in your programming.
Case2:
x!==y now this will be the case where user is not authenticated or logged in and user is still trying to access the /some section of your website. In this case user will be redirected to login page of whatever you have designed for your website for him/her to re-enter his/her credentials.
Here your redirect function redirects the user without sending any data. Something similar to the break.

express.js static html with get

On the front page of my app, the user can register an account and then login. It is expressed as a login and register button on the front page which then show the appropriate form when either are clicked.
I would like to replace the two buttons with a log out button if the user is already logged in but I need to inform the client of that first.
In my index.js, I am serving static html like so
app.use(express.static('public'));
I thought I could then do the following
app.get('/', function(req, res) {
// inform the client if req.user isn't null
});
but the callback is never called
I have found a solution.
In my index.js, I have this
app.get('/isloggedin', function(req, res) {
res.json({ loggedin: (req.user != null) });
});
And then I can just send a get request for /isloggedin and handle the result
$.get('/isloggedin', {}, function(data) {
if (!data.loggedin) {
// remove logged-in only elements
} else {
// remove logged-out only elements
}
});
Umm! i guess there would be a login/register form so there has to be two routes one with .get() and second one with .post():
app.get('/', function(req, res) {
// This is for navigation to the home page
}).post('/', function(req, res){
// inform the client here about the req.body.user
});
and i guess you have set up this:
app.use(bodyParser.urlencoded({extended:true})); // for "formurlencoded"
app.use(bodyParser.json()); // for "application/json"
if not then you have to load this module require('body-parser') first and require it only if you are using express 4.

Is it possible to get an express session by sessionID?

I have a NodeJS Express app that uses express-session. This works great, as long as session cookies are supported.
Unfortunately it also needs to work with a PhoneGap app that does not support cookies of any kind.
I am wondering: Is it possible to get an express session and access the data in that session, using the sessionID?
I am thinking I could append the sessionID as a querystring parameter for every request sent by the PhoneGap app like so:
https://endpoint.com/dostuff?sessionID=whatever
But I don't know how to tell express to retrieve the session.
You can certainly create an express route/middleware that tricks express-session that the incoming request contains the session cookie. Place something like this before the session middleware:
app.use(function getSessionViaQuerystring(req, res, next) {
var sessionId = req.query.sessionId;
if (!sessionId) return res.send(401); // Or whatever
// Trick the session middleware that you have the cookie;
// Make sure you configure the cookie name, and set 'secure' to false
// in https://github.com/expressjs/session#cookie-options
req.cookies['connect.sid'] = req.query.sessionId;
next();
});
Seems like req.cookies isn't accessible in my case. Here's another solution that recreates the session using the 'x-connect.sid' header (you may use any name or even a query param if you like).
Put this middleware after the session middleware
// FIRST you set up your default session like: app.use(session(options));
// THEN you recreate it using your/custom session ID
app.use(function(req, res, next){
var sessionId = req.header('x-connect.sid');
function makeNew(next){
if (req.sessionStore){
req.sessionStore.get(sessionId, function(err, session){
if (err){
console.error("error while restoring a session by id", err);
}
if (session){
req.sessionStore.createSession(req, session);
}
next();
});
} else {
console.error("req.sessionStore isn't available");
next();
}
}
if (sessionId) {
if (req.session){
req.session.destroy(function(err){
if (err) {
console.error('error while destroying initial session', err);
}
makeNew(next);
});
} else {
makeNew(next);
}
} else {
next();
}
});

Node.js detect if a variable exists in req for every page a user goes to

More specifically, I have an auth system that uses passportjs and req.user is defined if the user is authenticated.
Right now my website only has about 5 pages, but it's growing, and at the top of every route, I check if req.user exists and I pass a true or false variable to the rendered template, and the template renders accordingly.
I messed around with things such as app.get("*") but I didn't end up finding anything good.
How could I check if req.user (or anything else that could exist within req...) exists -- when a user goes to any page of my website, without repeting code?
Progress:
Using this code in app.js:
app.use(function (req, res, next) {
// Using req.locals.isAuthenticated would be better, as it's automatically passed to every rendered templates.
req.context = {};
req.context.isLoggedIn = req.isAuthenticated();
// req.locals.isAuthenticated = req.isAuthenticated();
next();
});
app.use('/dashboard', dashboard);
and this in the routes/dashboard route:
router.get('/', function (req, res) {
res.render('dashboard', { isLoggedIn: req.context.isLoggedIn });
});
Works - I can then see if the user is logged in by doing for example {{ isLoggedIn }}.
However when I uncomment the req.locals line in the first code snippet, I get a 500 error.
Two things to note:
Usually when your application needs to do something for a bunch of different pages, you want to setup a middleware function via app.use
Express has a res.locals variable whose properties will be included in any rendered template
With the above points in mind, you can construct something like the following:
app.use(function(res, req, next) {
res.locals.isAuthenticated = typeof(req.user) !== 'undefined';
next();
});
You then supply your additional template variables when your routes call res.render. For example:
app.get('/about', function(res, req) {
res.render('about', { 'testValue': 14} );
});
Your template will have access to both isAuthenticated and testValue.
I recommend you put some middleware in place before your route handlers but after passport's.
app.use(function(req, res, next) {
// Create a `context` object for use in any view.
// This allows the context to grow without impacting too much.
req.context = {};
// Assign your flag for authenticated.
req.context.isAuthenticated = typeof req.user !== 'undefined';
// Let the next middleware function perform it's processing.
next();
});
Then you can render each view with the context.
app.use('/', function(req, res) {
res.render('index', req.context); // Context is passed to view for usage.
});
This is all untested code.
You can do it as is already mentioned here ,but in this case you are going to check completely every request. Maybe you have got / you are going to have some pages that don't require any authentification and in this case you have to make some statement that will skip auth for that particular page or you can use something like this:
function checkUser(req, res, next) {
req.userAuth = (req.user !== undefined);
next();
}
app.post("settings", checkUser, doSomething);
app.post("administration", checkUser, doSomething);
app.post("index", doSomething); // Doesn't require any authentification
Or you can straight a way redirect a user
function checkUser(req, res, next) {
if (req.user === undefined) {
res.redirect("/login"); // res.render
}
else {
next();
}
}

Node.js Express disable automatic session creation

If I enable the session feature of express via app.use(express.session({secret: "12345"})); the session cookie is set when the user first hits a page.
How can I disable this behavior and decide manually when to create a cookie, for example after a successful login? I am aware that I could just construct a cookie-header manually, but I would like to stay with express.session.
Define the session support as middleware, but don't use use:
var sessions = express.session({
// etc
});
...
app.get('/', function (req, resp) {
// No session
});
app.post('/user', sessions, function (req, resp) {
// Has sessions
I'm not sure if this option existed when this question was originally was posted but I was able to set the saveUninitialized option as false to do this.
https://github.com/expressjs/session#saveuninitialized
Imagine you have a login method... I SUPPOSE you could do like that.
var sessionMW = express.session({secret:"12345"});
function login(req, res, next){
//...
if(success){
return expressMW(req, res, next);
}
}

Categories