如何以编程方式设置Strapi用户角色?

发布于 2025-01-29 04:31:52 字数 536 浏览 2 评论 0原文

我正在使用Strapi 3.6.10。

当我通过http:// host:1337/auth/local/寄存器创建用户时,我将无法实现理想的用户角色。它始终是认证的,即使我在请求中直接将其设置为另一个,

{  
    "username": "user",   
    "email": "[email protected]",  
    "password": "123456789",   
    "role": {   
        "_id": "626eacea45f0a420ccb35094"
    }
}

我也尝试使用文档插件生成的API - put/uders/{id}。但是,如果我发送带有新角色的请求,我的用户的条目什么都不会发生

I'm using Strapi 3.6.10.

When I create user via http://host:1337/auth/local/register, I'm not able to achieve desirable user's role. It's always Authenticated, even if I directly set it to another in my request

{  
    "username": "user",   
    "email": "[email protected]",  
    "password": "123456789",   
    "role": {   
        "_id": "626eacea45f0a420ccb35094"
    }
}

I've also tried using API documented in generated by Documentation plugin Swagger - PUT /users/{id}. But if I send request with new role nothing happens to my user's entry

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暗喜 2025-02-05 04:31:52

对于Strapi V4,现在主要使用:

如果您想要所有新用户的特定角色,我建议您通过在Strapi Admin面板上进行编辑默认注册的用户角色,请转到settings>高级设置

您将能够编辑“已验证用户的默认角色”。这是归因于新帐户的默认角色。

如果您只想编辑用户角色,则可以通过更新相关用户来完成此操作。

您首先必须检索要分配的角色的ID。对于典范,我想为用户分配角色作者

// You cannot find your role with its id, because it is what we are looking for,
// so we have to use the `findMany` method, that returns an array
const roles = await strapi.entityService.findMany(
    "plugin::users-permissions.role",
    {
        filters: { type: "author" },
    }
);

// Check if the role has been found
if (!roles || roles.length === 0) {
    // Error handling
}

const authorRole = roles[0];

现在,我们必须使用新角色更新用户。

const user = await strapi.entityService.update(
    "plugin::users-permissions.user",
    ctx.state.user.id,
    {
        data: {
            role: authorRole.id
        }
    }
);

您可以创建一个自定义路由以将此代码放入其中,因此用户可以首先创建一个具有默认角色和有限访问权限的帐户,然后通过调用您的自定义路由来指定他想要的角色,并应用更新。

如果您真的想在用户创建后直接执行此操作,则可以接受此论坛通过创建一个全局中间件来检查请求是否为寄存器,然后执行一些代码:在此之后

执行一些代码-middleware.js 。重要的是要以小写编写文件名。用连字符分开你的话。

// src/middlewares/your-custom-middleware.js
"use strict";

module.exports = () => {
    return async (ctx, next) => {
        // The `next()` call will register your user with the default role
        await next();

        if (ctx.request.url === '/api/auth/local/register' && ctx.response.status === 200) {

            // Now we can apply our logic, but we have to retrieve the user

            const userArray = await strapi.entityService.findMany(
                "plugin::users-permissions.user",
                {
                    filters: { email: ctx.request.body.email }
                }
            );

            if (!userArray || userArray.length === 0) {
                // Handle error, can't find user
            }

            const user = userArray[0];

            const roles = await strapi.entityService.findMany(
                "plugin::users-permissions.role",
                {
                    filters: { type: "author" },
                }
            );

            // Check if the role has been found
            if (!roles || roles.length === 0) {
                // Error handling
            }

            const authorRole = roles[0];

            const updatedUser = await strapi.entityService.update(
                "plugin::users-permissions.user",
                user.id,
                {
                    data: {
                        role: authorRole.id
                    }
                }
            );
        }
    };
};

要完成,您必须通过编辑config/middleware.js文件注册中间件为全局:

module.exports = [
  // The array is pre-populated with internal, built-in middlewares, prefixed by `strapi::`
  'strapi::errors',
  'strapi::security',
  'strapi::cors',
   // ...
  'global::your-custom-middleware'
]

For STRAPI v4, that is mostly used now :

If you want a specific role for all new users, I suggest you to edit your default registered user role by going on your StrAPI admin panel, go to Settings > Advanced Settings.

You will be able to edit your "Default role for authenticated users". It is the default role attributed to new accounts.

If you just want to edit user role, you can do it by updating the concerned user.

You first have to retrieve the id of the role you wanna assign to. For exemple, I want to assign to my user the role author.

// You cannot find your role with its id, because it is what we are looking for,
// so we have to use the `findMany` method, that returns an array
const roles = await strapi.entityService.findMany(
    "plugin::users-permissions.role",
    {
        filters: { type: "author" },
    }
);

// Check if the role has been found
if (!roles || roles.length === 0) {
    // Error handling
}

const authorRole = roles[0];

Now, we have to update our user with the new role.

const user = await strapi.entityService.update(
    "plugin::users-permissions.user",
    ctx.state.user.id,
    {
        data: {
            role: authorRole.id
        }
    }
);

You can create a custom route to put this code into, so the user can first create an account with default role and limited access, and after specify what role he want by calling your custom route, and apply the update.

If you really want to do that directly after user creation, you can take exemple of this forum by creating a global middleware to check if the request is a register, and execute some code after that :

Create a file in src/middlewares/your-custom-middleware.js. It is important that you write your file name in lowercase. Separate your words with hyphens.

// src/middlewares/your-custom-middleware.js
"use strict";

module.exports = () => {
    return async (ctx, next) => {
        // The `next()` call will register your user with the default role
        await next();

        if (ctx.request.url === '/api/auth/local/register' && ctx.response.status === 200) {

            // Now we can apply our logic, but we have to retrieve the user

            const userArray = await strapi.entityService.findMany(
                "plugin::users-permissions.user",
                {
                    filters: { email: ctx.request.body.email }
                }
            );

            if (!userArray || userArray.length === 0) {
                // Handle error, can't find user
            }

            const user = userArray[0];

            const roles = await strapi.entityService.findMany(
                "plugin::users-permissions.role",
                {
                    filters: { type: "author" },
                }
            );

            // Check if the role has been found
            if (!roles || roles.length === 0) {
                // Error handling
            }

            const authorRole = roles[0];

            const updatedUser = await strapi.entityService.update(
                "plugin::users-permissions.user",
                user.id,
                {
                    data: {
                        role: authorRole.id
                    }
                }
            );
        }
    };
};

To finish, you have to register your middleware as global by editing the config/middleware.js file :

module.exports = [
  // The array is pre-populated with internal, built-in middlewares, prefixed by `strapi::`
  'strapi::errors',
  'strapi::security',
  'strapi::cors',
   // ...
  'global::your-custom-middleware'
]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文