I have created an API that contains many pieces of information related to each "User". By default "User" only have a model containing e-mail, password, username and lang. So I have created a "UserInfo" API/Model that contains firstName, lastName, age, address and so on. I want to give non-admin users access to it's own "UserInfo" data, which means the user would be able to access the api using localhost/userinfo/:id. But each user will only get authorized to call it's own ID and not other users IDs. How can I create such a "policy"/ restriction for the final users "role"? Hope I have been clear enough. My questions is probably quite trivial.
2 Answers
You will have to play with role's permissions or policies. I think this issue is really close to what you want: https://github.com/strapi/strapi/issues/624
Comments
In strapi after the authentication the ctx.state.user.id is assigned with the user entity so you can use it to validate.
you can either create a policy
module.exports = async (ctx, next) => {
const { params } = ctx;
if (ctx.state.user.id === params.id) {
return next();
} else {
return ctx.badRequest(
'Not Authorized'
);
}
};
and set policy in the route file
{
"method": "GET",
"path": "/userinfo/:id",
"handler": "userinfo.findOne",
"config": {
"policies": [
"admin::hasPermissions",
"isOwner"]
}
}
Or custom write the findOne method
async findOne(ctx) {
const { query, params } = ctx;
if (ctx.state.user.id === params.id) {
const entity = await service.findOne({ ...query, id: params.id });
}
else {
return ctx.badRequest(
'Not Authorized'
)
}
return sanitize(entity);
},