根据用户身份验证,使路由端点响应不同的内容



说我正在构建一个简单的web应用程序与REST后端,其中用户有自己的页面与用户信息。

我想实现的是,如果一个未经身份验证的用户向

发出请求

www.mywebapp.com/api/user/john

他们将被提供有限的信息(例如只有年龄和电子邮件)。但是,如果用户登录并发出相同的请求,服务器也将响应更多信息(如个人偏好等)。

我想可能是验证用户令牌的中间件,在请求(req)上传递权限。角色= guest或req。角色=用户)。然后在user/:name端点中,它将检查角色并使用不同的内容进行响应。

另一种选择是为经过身份验证的用户创建一个新的路由端点,然后检查在客户端调用哪一个。

这里的最佳实践是什么?

我最后是这样做的:

let router = express.Router();
router.get('/profile', authenticate, hasRole("Admin", true), controller.showProfileAdmin);
router.get('/profile', hasRole("User", true), controller.showProfileUser);
// will not call next('route') if Guest requirements is not met
router.get('/profile', hasRole("Guest"), controller.showProfile); 
// hasRole() returns a middleware function that checks if user meets role requirement.
// If nextRoute is true, the function calls next('route'). If nextRoute is false
// or undefined, the function responds with a 403
function hasRole(roleRequired, nextRoute) {
    return (req, res, next) => {
        // Just checking so that the user has authority for this role.
        if (config.userRoles.indexOf(req.user.role) >= config.userRoles.indexOf(roleRequired)) {
            return next();
        //else client is not authorized
        } else {
            // If nextRoute is true, continue to the next route.
            if(nextRoute){
                return next('route');
            //Else respond with a forbidden status.
            } else {
                res.sendStatus(403);
            }
        }
    }
}

最新更新