Using express.static middleware in an authorized route
Asked Answered
T

2

13

I'm using node with express and passportjs to restrict access to files located in a private folder. I have reduced my code to the following. Everything in the public static folder works great but route targeting the private folder through the use of the staticMiddleware returns 404 errors.

var express = require('express')
,   util = require('util');

var app = express.createServer();
var staticMiddleware = express.static(__dirname + '/private');

app.configure(function() {
  app.use(app.router);
  app.use(express.logger('dev')); 
  app.use('/public',express.static(__dirname + '/public'));
});

app.get('/private/:file', function(req, res, next){
    console.log('about to send restricted file '+ req.params.file);
    staticMiddleware(req, res, next);
});
app.listen(16000);

I was using the following references that seems to work for others, so I must be missing something. It won't work for me showing only 404 responses for the content located in the private area.

Node.js module-specific static resources

NodeJS won't serve static files, even when using express.static

Redirecting to a static file in express.js

I could have sworn I had this working before, maybe it was broken in a new version of something.

Teodora answered 13/7, 2012 at 15:19 Comment(1)
I was looking for the exact same thing. Had a few ideas on how to do it, but thanks for answering it yourself. This was a very nice solution.Paragon
T
18

sheesh staring at me the whole time

app.get('/private/:file', function(req, res, next){
    console.log('about to send restricted file '+ req.params.file);
    req.url = req.url.replace(/^\/private/, '')
    staticMiddleware(req, res, next);
});

Edit 11-29-2014

So after someone posted to the question I came back to this answer to find that even though I mention passportjs I never showed how I ended up using this function.

var staticMiddlewarePrivate = express['static'](__dirname + '/private');

app.get('/private/*/:file', auth.ensureAuthenticated, function(req, res, next){
    console.log('**** Private ****');
    req.url = req.url.replace(/^\/private/, '');
    staticMiddlewarePrivate(req, res, next);
});
Teodora answered 13/7, 2012 at 15:28 Comment(0)
S
0

You can also add express.static(__dirname + '/private'); to your app.config.

app.configure(function() {
  app.use(app.router);
  app.use(express.logger('dev')); 
  app.use('/public',express.static(__dirname + '/public'));
  app.use('/private',express.static(__dirname + '/private'));
});

The private path middleware would be executed anytime a path began with private.

Selfinsurance answered 7/11, 2014 at 19:47 Comment(1)
This would expose the static files correctly, but it wouldn't keep them password protected. My understanding is that @Teodora wanted to have them served but also password protected through passwordJS.Paragon

© 2022 - 2024 — McMap. All rights reserved.