我是一位首次从事前端工作,stradi和javascript的开发人员。我希望有人可以怜悯我,并提供一个示例,说明如何通过bootstrap.js脚本设置公共角色权限。
node.js v10.16.0
Strapi v3.0.0-next.11
Graphql 14.3.1
MongoDB:3.6
全部在Windows 10上
在Strapi UI中,它是公共角色的角色和权限 我想将这些框设置为CHECKED
另一个开发人员已使用bootstrap.js文件将项目添加到我们创建的服务(菜单)中。我什至不知道如何返回有关角色权限的最基本信息。 我的函数称为test(),我在其中搜索了示例,发现的最好的是在stackoverflow上: Strapi Plugin Route Default Permission:
strapi.plugins['users-permissions'].models.role.find
但我不知道如何使用它:
WORKING
function add_widgets_from_sheet(sheet_name, model_object){
console.log(`adding ${sheet_name}`)
let xlsxSheet = Sheets[sheet_name]
const widgets = XLSX.utils.sheet_to_json(xlsxSheet)
widgets.forEach(function (widget) {
//See if the object is already in the db before adding it
model_object.count(widget)
.then(result => {
if (result == 0) {
console.log('Adding '+sheet_name+': ' + JSON.stringify(widget))
return model_object.add(widget)
}
})
})
}
NOT WORKING
function test(){
console.log(`Testing ${strapi.plugins['users-permissions'].models.role.find}`)
}
module.exports = next => {
console.log('Starting Strapi bootstrap')
add_widgets_from_sheet('Menus', strapi.services.menu) //adding menus
test() // Returning nothing
console.log('Ending Strapi bootstrap')
next()
}
我想将这些复选框切换为TRUE,CHECKED或其他名称。这样我们就不必在每次转储数据库时都通过UI手动进行操作。
我从例子中学习得最好……希望您能提供帮助。谢谢!
答案 0 :(得分:1)
我觉得这更简单。
// In your bootstrap.js file
'use strict';
module.exports = async () => {
const authenticated = await strapi.query('role', 'users-permissions').findOne({ type: 'authenticated' });
authenticated.permissions.forEach(permission => {
if (permission.type === 'application'){ // Whatever permissions you want to change
let newPermission = permission;
newPermission.enabled = true; // Editing permission as needed
strapi.query('permission', 'users-permissions').update( { id: newPermission.id }, newPermission ); // Updating Strapi with the permission
}
});
return;
};
答案 1 :(得分:1)
在上述两个答案的基础上,您似乎可以摆脱一个循环,并且可以为public
和authenticated
用户设置权限。
这是针对trapi 3.2.4
编写的,而我正在使用NodeJS 12,因此可以使用诸如散布运算符...
之类的东西。
const permOrm = strapi.query('permission', 'users-permissions')
const perms = await permOrm.find({ type: 'application' })
for (const curr of perms) {
if (curr.role.type === 'authenticated') {
strapi.log.info(
`Allowing authenticated to call ${curr.controller}.${curr.action}`,
)
permOrm.update({ id: curr.id }, { ...curr, enabled: true })
continue
}
// permission is for public
const isReadEndpoint = ['find', 'findone', 'count'].includes(curr.action)
if (isReadEndpoint) {
strapi.log.info(
`Allowing public to call ${curr.controller}.${curr.action}`,
)
permOrm.update({ id: curr.id }, { ...curr, enabled: true })
continue
}
// TODO add custom logic for any non-standard actions here
strapi.log.info(
`Disallowing public from calling ${curr.controller}.${curr.action}`,
)
permOrm.update({ id: curr.id }, { ...curr, enabled: false })
}
答案 2 :(得分:0)
因此,以下代码来自名为PROJECT / STRAPI / config / functions / bootstrap.js的文件 这会利用我们保存在excel电子表格中的信息自动创建内容类型和内容。但是,为了使用这些内容类型,必须激活一些角色和权限,以便Web ui可以访问它们。 基本上,我们不想手动进入Strapi UI来创建您的用户,创建内容类型,创建内容或更新权限。我们希望脚本能够完成所有这些工作。
'use strict'
我们的环境变量
require('dotenv').config({ path:'../.env' })
保存我们的数据的Excel电子表格(随附)
const XLSX = require('xlsx')
const BOOTSTRAP_DATA = XLSX.readFile(process.env.BOOTSTRAP_DATA).Sheets
从.env中提取的变量
const ADMIN_USERNAME = process.env.ADMIN_USERNAME
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD
const ADMIN_EMAIL = process.env.ADMIN_EMAIL
在XLSX中阅读
async function bootstrap_resource(resource_type, resource_service) {
strapi.log.info(`Bootstrapping ${resource_type}`)
const resources = XLSX.utils.sheet_to_json(BOOTSTRAP_DATA[resource_type])
for (let resource of resources) {
if (await resource_service.count(resource) === 0) {
strapi.log.warn(`Bootstrapping ${resource_type}: ${JSON.stringify(resource)}`)
await resource_service.create(resource)
}
}
}
为trapi创建初始用户
async function bootstrap_admin() {
strapi.log.info(`Bootstrapping Admin`)
const admin_orm = strapi.admin.queries('administrator', 'admin')
const admins = await admin_orm.find({username: ADMIN_USERNAME})
if ( admins.length === 0) {
const blocked = false
const username = ADMIN_USERNAME
const password = await strapi.admin.services.auth.hashPassword(ADMIN_PASSWORD)
const email = ADMIN_EMAIL
const user = { blocked, username, password, email }
const data = await admin_orm.create(user)
strapi.log.warn(`Bootstrapped Admin User: ${JSON.stringify(user)}`)
}
}
以下是get_roles()-get_permissions()必需,而get_permissions()是enable_permissions()必需。在这里,我们打开这些内容类型,以便Web ui可以看到它。
async function get_roles() {
const role_orm = strapi.plugins['users-permissions'].queries('role', 'users-permissions')
const role_list = await role_orm.find({}, [])
const roles = {}
for (let role of role_list) {
roles[ role._id ] = role
roles[ role.name ] = role
}
return roles
}
async function get_permissions( selected_role, selected_type, selected_controller ) {
const roles = await get_roles()
const permission_orm = strapi.plugins['users-permissions'].queries('permission', 'users-permissions')
let permission_list = await permission_orm.find({_limit: 999}, [])
if ( selected_role ) permission_list = permission_list.filter( ({ role }) => `${role}` === `${roles[selected_role]._id}` )
if ( selected_type ) permission_list = permission_list.filter( ({ type }) => `${type}` === `${selected_type}` )
if ( selected_controller ) permission_list = permission_list.filter( ({ controller }) => `${controller}` === `${selected_controller}` )
return permission_list
}
async function enable_permissions(role, type, controller) {
strapi.log.info(`Setting '${controller}' permissions for '${role}'`)
const permission_orm = strapi.plugins['users-permissions'].queries('permission', 'users-permissions')
const permissions = await get_permissions(role, type, controller)
for (let { _id } of permissions) {
permission_orm.update({ _id }, { enabled: true })
}
}
最后,我们运行程序
module.exports = async next => {
await bootstrap_admin()
await bootstrap_resource( 'Clients', strapi.services.client )
await bootstrap_resource( 'Menus', strapi.services.menu )
enable_permissions('Public', 'application', 'client' )
enable_permissions('Public', 'application', 'github' )
enable_permissions('Public', 'application', 'menu' )
enable_permissions('Public', 'application', 'confluence' )
next()
}
拿出我的评论,您便拥有了完整的bootstrap.js文件。下图显示了demo.xlsx工作簿的3个选项卡,这些选项卡用于填充所有内容。
答案 3 :(得分:0)
对于trapi 3.3.x
以及可能的将来版本
效率略高(一次查询角色,使用查询过滤权限)
'use strict';
module.exports = async () => {
const publicRole = await getRoleByName('Public')
await grantPermissions(publicRole, 'application', 'images', ['upload', 'remove']) // upload, remove in 'images' controller
await grantPermissions(publicRole, 'application', 'project') // any action in 'project' controller
};
async function getRoleByName(name) {
return strapi.query('role', 'users-permissions').findOne({ name }, [])
}
async function getPermissions(role, permissionType, controller, actions = null) {
const permissionQuery = strapi.query('permission', 'users-permissions')
const permissionRequest = {
_limit: 1000,
role: role.id,
type: permissionType,
controller: controller
}
if (actions) {
permissionRequest.action_in = Array.isArray(actions) ? actions : [actions]
}
return permissionQuery.find(permissionRequest, [])
}
async function grantPermissions(role, permissionType, controller, actions) {
if (actions && !Array.isArray(actions)) {
actions = [ actions ]
}
strapi.log.info(`Setting '${controller}' [${actions ? actions.join(', ') : '*'}] permissions for '${role.name}'`)
const permissionQuery = strapi.query('permission', 'users-permissions')
const permissions = await getPermissions(role, permissionType, controller, actions)
if (permissions.length === 0) {
throw new Error(`Error enabling permissions: ${role.name}, ${permissionType}, ${controller}, ${actions}`)
}
for (const { id } of permissions) {
await permissionQuery.update({ id }, { enabled: true })
}
}