简体   繁体   中英

Express Static for Authenticated Users

How can I enable static directories just for a user's session in express? Using some HTML files as an examples, I know I can serve a directory called private via the call below

app.use("/private", express.static(appDir + '/private'));

What I would like to do is just enable the static resource once a user has been authenticated (using stormpath as my example).

For example, the function below would check if the user existed in stormpath and if they did, the app would then serve the static directory of maps.

app.get('/getPrivate', stormpath.getUser, function(req, res) {
    if(req.user){
      app.use("/private", express.static(appDir + '/private'));
      res.redirect('/private/index.html');      
    }else{
      //your not logged in.... redirect to login page      
    }
});

This does not work as I've found once I enable the static directory for a user, another user would then be able to visit the private directory without logging in.

If you want to require authentication for a route, you should use stormpath.loginRequired . If the user is not logged in, they will be redirected to the login page.

Using app.all in my routes did the trick

var path = require('path');
var express = require('express');
var appDir = path.dirname(require.main.filename);

app.all('/private/*', stormpath.getUser, function(req, res, next) {
    if(req.user){      
       next();      
    }else{
      //you are not logged in.... redirect to login page
      res.redirect('/');            
    }
});

app.use("/private", express.static(appDir + '/private'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM