How to protect a route with a referrer in Node.js - javascript

I am trying to protect a route in my node.js application such that if the user wants to go to the page /post they have to come from /blog. If the user comes from anything other than /blog they are to be redirected to /. I have the following code that uses the http referrer
let ref = req.headers.referer;
if ((ref === undefined) || (!ref.includes('blog'))) {
res.redirect('/')
}
It seems to work well if I console.log for testing but if I do res.redirect, I get the error
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client.
How can I use the referrer to protect the route.
Should there be any other way of accomplishing this without using referring: all suggestions are welcome.
Thanks in advance

Try this, In your app.js file include this.
const express = require('express');
const app = express();
app.get('/',(req, res, next)=>{
res.send('Ready')
});
app.get('/test',(req, res, next)=>{
res.send('Ready')
});
// Below (*) will consider unwanted urls
app.use('/*', function(req, res, next) {
res.redirect('/')
});
app.listen(4000);
FYI, If you try demo.com/unkownurl will redirect to root like demo.com/

Related

express static routes are not working when adding a validation middleware

I am trying to add a validation middleware in order to protect my server data. When I get request (http://localhost:3000/filepath) the static route without the middleware:
app.use(express.static('data'));
I get a status 200 OK. But when I tried to get request the same route, but this time using a simple middleware as recommended in this other question (Is it possible to use validation with express static routes?)
var staticMiddleware = function(req, res, next){
console.log("middleware")
next();
}
app.use(staticMiddleware, express.static('data'));
I`ve got a status 404 not found.
How can I add another middleware to app.use before the express.static middleware?
You need to add them seperately.
app.use(express.static('data'));
var staticMiddleware = function(req, res, next){
console.log("middleware")
next();
}
app.use(staticMiddleware );

Why is Express redirecting infinitely redirecting me?

I am trying to setup a multi language website with Express and NodeJs. My problem is I get redirected what it feels like 100 times and my browser is giving me a error that the webpage is not working because it redirected me too many times.
app.js
app.use('/', (req,res,next) => {
res.redirect('/en-US');
next();
});
app.use('/:lang', indexRouter);
app.use('/:lang/users', usersRouter);
index.js (indexRouter)
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index');
});
module.exports = router;
The problem is that this route handler:
app.use('/', (req,res,next) => {
res.redirect('/en-US');
next();
});
will get hit for not only /, but also /en-US. app.use() matches any route handler for which the path is equal to or a subset of the requested path. So, the browser requests "/", you redirect to "/en-US", which then redirects to "/en-US" and so on, an infinite loop.
I don't know the overall URL design of your site to know what the best overall solution is. You can prevent the infinite redirect loop by just changing app.use() to app.get():
app.get('/', (req,res,next) => {
res.redirect('/en-US');
});
But, that will make the redirect only work for GET requests which may or may not be OK. If you want all HTTP verbs to redirect, you could change to app.all():
app.all('/', (req,res,next) => {
res.redirect('/en-US');
});
The important thing to understand here is that app.get(), app.post(), app.all(), etc... all require an exact match for the URL path, whereas app.use() just requires a subset match. This is a little understood aspect of the Express design.
In addition, remove the call to next() after you do res.redirect(). At that point, you've sent the response, you don't want any other request handlers to see the request. You're done with routing.
under your app.js
Try using
app.use('/', router )
How about you try dealing with the '/' route through the app.js directly instead of index.js

app.get() being called multiple times express

I'm fairly new to node.js and trying to make a simple website which first asks the authentication and then redirects the user to a page.
so, what i do is that i create a middleware which listenes to every request made to my website.
what this middleware does that it checks if the the user is logged in with my website or not is yes then redirect to the requested page if not, then redirect to the login page, here is my code for that.
var express = require('express');
var app = express();
// middleware for using static files
app.use('/public', express.static(__dirname + '/public')); // all the js files for check_before.html
app.use('/templates', express.static(__dirname + '/templates')); // here are css/js files for login.html
// setting up views folder
app.set('views', __dirname + '/views'); // check_before.html is sitting here
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use((req, res, next) => {
res.render('check_before.html');
// here in the html I implement the logic using js files which are located in public folder.
next();
});
// if not logged in , the user gets here
app.get('/login', (req, res, next) => {
res.render('login.html')
});
// if logged in redirect to some page
app.get('/welcome_page', (req, res) => {
return 'welcome'
});
everything goes well untill the user hits the http://localhost:8000/login page (after the check if they are signed in or not) the page keeps on loading multiple times and it won't stop reloading.
I have defined all the css, js files of login.html page in the templates folder which is loaded above the middleware by reffereing to this question
Express middleware getting called many times. could that be a problem?
what could be the reason for this?
here is the error i'm getting in the console.
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
any guesses?
Edit1
I went through this question Error: Can't set headers after they are sent to the client , and i guess it concludes that setting headers explicitly could be problematic.
Could this be a reason? because in my logic if the user is not signed In, I'm just using window.location.replace('http://localhost:8000/login') to redirect the user to login page.
should I use any another method for redirection?
Edit2
There are suggestions that i must write a middleware to check is the user is authenticated or not, and get a sort of flag for that, but as i've stated above that i'm implementing the logic in check_before.html(client side). so it won't be possible to use that.
I have two guesses:
You shouldn't call send (or any other function )after res.render.
Middleware to verify user is logged in should be something like this (applied only to routes you want to verify user)
Middleware should be something like this
const isAuthenticated = (req, res, next) => {
if(req.isAuthenticated()) {
next();
} else {
res.redirect('/');
}
}
app.get('/welcome_page', isAuthenticated, (req, res) => {
return 'welcome'
});
The reason is that middleware is called before your /login request. To fix it, you need to modify your middleware function. It should be something like:
app.use((req, res, next) => {
if(isLoggedIn) { //isLoggedIn is a flag that checks whetehr user is logged-in or not
res.render('check_before.html');
} else {
// here in the html I implement the logic using js files which are located in public folder.
next();
}
});

Expressjs rerouting

I need to make routing flexible for slashes, for example
app.get('/home/pages')
router must handle
////home///pages
/home/pages////
etc...
requests.
Currently I have one idea to implement this, but for that I need to know how to reroute request via middleware,
If you can answer this question or suggest something else I will be grateful to you.
Also please don't suggest using regex for defining routers, because project is already done and there is a lot of already defined routes.
You need to rewrite url in a middleware:
var express = require('express');
var app = express();
app.use(function (req, res, next) {
req.url = req.url.replace(/\/+/g, '/');
next();
});
app.get('/home/pages', function (req, res) {
res.send('some pages');
});
app.listen(3000);

How protect a RestFul Api in Nodejs?

Nowadays i am using https://github.com/baugarten/node-restful wich helpme to work in an API, the question is?
I am working in Express framework, are there a way to protect the "GET" request from other site to mine.
I use the CSRF from express but only work by POST,PUT,DELETE methods with a message of FOrbidden 403 when treat make anithing since curl in console but if I make a curl toward a Get method curl localhost:3000/posts that giveme an array with all the posts.
app.use(express.csrf());
app.use(function(req, res, next){
res.locals.token = req.session._csrf;
next();
});
app.use(app.router);
What you advice me? are there other modules to work an Api better? How can protect an Api in nodejs? What are the best practices that a haver to learn?
Thanks by your Help.
Try Express middleware which is designed to do so. For example:
var express = require('express');
var app = express();
// simple middle ware to protect your URI
app.use(function(req, res, next){
if (req.method == 'GET') {
if (!req.locale.token) { res.send(403); } // custom to fit your policy
else if (req.protocol !== "https") {res.redirect("your-secure-url");}
else { next(); }
}
});

Categories