Full-Stack React Projects
上QQ阅读APP看书,第一时间看更新

Authorizing signed in users

For some of the protected routes such as update and delete, on top of checking for authentication we also want to make sure the requesting user is only updating or deleting their own user information. To achieve this, the hasAuthorization function defined in auth.controller.js checks if the authenticated user is the same as the user being updated or deleted before the corresponding CRUD controller function is allowed to proceed.

mern-skeleton/server/controllers/auth.controller.js:

const hasAuthorization = (req, res, next) => {
const authorized = req.profile && req.auth && req.profile._id ==
req.auth._id
if (!(authorized)) {
return res.status('403').json({
error: "User is not authorized"
})
}
next()
}

The req.auth object is populated by express-jwt in requireSignin after authentication verification, and the req.profile is populated by the userByID function in the user.controller.js. We will add the hasAuthorization function to routes that require both authentication and authorization.