I'm currently learning Express with Sequelize and I don't know how to securely verify user ownership of a resource that is being manipulated.
Database:
- User has many Products
- Each Product belongs to one User(ForeignKey = userId)
For the sake of simplicity here is the router:
router.patch('/product/:id', (req, res) => {
// service layer call
const productInstance = await ProductService.update(args);
return res.json(productInstance);
});
I thought about three possible solutions:
- Verify ownership in custom middleware
- Verify ownership in service layer
- Verify ownership with custom validation in Sequelize
Middleware
Here's an example of what I'm thinking about:
var isOwner = async (req, res, next) => {
const product = await ProductModel.findOne({ where: { id: req.params.id }});
if (product.userId === req.user.id) {
next();
}
return res.send(401, 'Unauthorized');
};
This solution however makes me think my API will be prone to mistakes later on.
Service Layer
I'm pretty sure that validation doesn't really belong to business logic, but rather to model layer of the application.
Sequelize(Model) Layer
I haven't found any resources on passing arguments to custom validation methods in Sequelize(I'd have to pass request user object somehow). Is it even possible?
Summary
I'm lost and don't know which way of verifying users ownership I should choose.