different views/routes by the type of user in express.js

a 夏天 提交于 2019-12-13 07:16:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!