本文详细介绍了如何在Strapi中创建自定义策略和路由,以增强用户权限管理。包括通过创建strapi-server.js文件来修改现有路由,以及通过创建新的API来实现自定义用户查找功能。
创建policies
# src/policies/is-owner.js
module.exports = (policyContext, config, { strapi }) => {
strapi.log.info('In is-owner policy.');
const { user, auth } = policyContext.state;
const { params } = policyContext;
const canDoSomething = user.id == params.id;
if (canDoSomething) {
return true;
}
return false;
};
方案一、通过创建strapi-server.js来修改
创建strapi-server.js
# src/extensions/users-permissions/strapi-server.js
module.exports = (plugin) => {
for (let i = 0; i < plugin.routes["content-api"].routes.length; i++) {
const route = plugin.routes["content-api"].routes[i];
if (
route.method === "GET" &&
route.path === "/users/:id" &&
route.handler === "user.findOne"
) {
console.log(route);
plugin.routes["content-api"].routes[i] = {
...route,
config: {
...route.config,
policies: route.config.policies
? [...route.config.policies, "global::is-owner"]
: ["global::is-owner"],
},
};
}
}
return plugin;
};
方案二:创建一个新的api
新建controllers
# src/api/custom/controllers/user.js
module.exports = {
find: async (ctx, next) => {
return strapi.plugins["users-permissions"].controllers.user.find(ctx);
}
};
新建routes
# src/api/custom/routes/user.js
module.exports = {
routes: [
{
method: 'GET',
path: '/custom/users',
handler: 'user.find',
config: {
policies: ['global::is-owner'],
middlewares: [],
},
},
],
};