user9554056
user9554056

Reputation:

nodejs: display an image not in public folder

I would like to display an image which is not in the public folder in my webroot. My hirarchy:

Webroot
--core
----views
----public <- Here is where stylesheets and other images are
------index.ejs <- Here I want to display the file.jpg
--data
----userdata
------username <- this folder is named by the user
--------assignment <- this folder is named by the assignment
----------file.jpg

I have no idea, i could move this into the public folder and rule it by the robots.txt, but I thought, maybe there is a better solution.

Upvotes: 0

Views: 2164

Answers (1)

Jake Holzinger
Jake Holzinger

Reputation: 6063

You can serve the data directory as a static directory, like your public directory -- Serving static files in Express. You'll probably want to set up some authentication middleware before the static route or everyone will be able to see each others data.

Here's an example of what that might look like:

// User authentication middleware
app.use(function(req, res, next) {
    // Some implementation that determines the user that made the request.
    req.username = 'foo';
    next();
});

// Serve the public assets to all authenticated users
app.use(express.static('public'));

// Prevent users from accessing other users data
app.use('/data/userdata/{username}/*', function(req, res, next) {
    if (req.username === req.path.username) {
        next();
    } else {
        res.sendStatus(401); // Unauthorized
    }
});

// Serve the data assets to users that passed through the previous route
app.use('/data', express.static('data'));

Upvotes: 1

Related Questions