问题
can we have an express app, with 2 different views/routes based on user type?
Example: I have 2 user types admin and normal user, based on the user alter login, how can i redirect each user to different views/routes
like after login admin user goes to admin dashboard and normal user goes to profile page, also keeping in mind that one type of user cannot assess other type of user's routes.
Any input will be helpful
Thanks
回答1:
In a simplest way you could just change a view based on user's type something like this:
function homeMiddleware (req, res, next) {
var view = user.admin ? 'admin' : 'profile';
res.render(view);
}
app.get('/home', homeMiddleware);
But if you want separate code of your routes then you should following Strategy pattern with the following refactoring:
// Define your routes for each user types
var UserRouteStrategy = {
home: require('./routes/user/profile')
};
var AdminRouteStrategy = {
home: require('./routes/admin/dashboard')
};
// Early as possible assign current strategy based on user type
function (req, res, next) {
req.routeStrategy = req.user.admin ? AdminRouteStrategy : UserRouteStrategy
next(); // don't forget this
}
// And handle your routes with current strategy
app.get('/home', function (req, res, next) {
req.routeStrategy.home(req, res, next);
});
With the approach above you may extend your application by adding new user types and control access in a single place.
来源:https://stackoverflow.com/questions/32032561/different-views-routes-by-the-type-of-user-in-express-js