I am currently trying to restrict the routes to users who haven't been logged. My main issue is that even if I define a page with a get method such as:
app.get('/alpha/information', isLoggedIn,
function(req, res){
res.sendFile(path.join(__dirname + '/alpha/pages/Example.html'));
});
The user can sill just edit the url to: http://localhost:3000/alpha/pages/Example.html
and access the page. Now I have read several similar questions on SO but I cannot find the answer. Some of which I was inspired were: Q1,Q2, Q3. Nonetheless I was unable to find a solution to my issue.
My current file structure is: FileStructureLink
I am trying to restrict access to Example.html, ExampleTwo.html and blabla.html
I am using this code to set up the requests but I guess they might not be right:
app.use(express.static(path.join(__dirname, 'Alpha')));
app.use(express.static(path.join(__dirname, '/')));
app.use('/', express.static(__dirname + '/login.html'));
This app.use('/', express.static(__dirname + '/login.html'));
specifically is used to make the default localhost:3000/
load as localhost:3000/login
How can I restrict access to all the static html files without having to write a route for each of them?
middleware function:
function isLoggedIn(req, res, next) {
console.log('here is Authenticated', req.isAuthenticated())
if (req.isAuthenticated()){
return next();
}
res.redirect('/login');
}
You can restrict your express static middleware, by attaching another middleware to it.
var express = require("express");
var path = require( "path" );
var app = express();
function isLoggedIn( req, res, next ) {
console.log("trying restricted file");
next();
}
app.use( '/Alpha', isLoggedIn, express.static( path.join( __dirname, 'Alpha' ) ) );
app.use( express.static( path.join( __dirname, 'anonymous' ) ) );
app.listen( 3000 );
By doing this every time you call localhost:3000/restricted/*
will via isLoggedIn function.
EDIT: Code modified, according to your file structure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With