@aclify/aclify 中文文档教程
@aclify/aclify
Description
该模块提供受 ZendACL 和节点acl 包启发的节点访问控制列表实现。
当您开发网站或应用程序时,您很快就会注意到会话不足以保护所有 可用资源。 避免恶意用户访问其他用户的内容证明了更多 比预期复杂的任务。 ACL可以灵活优雅的方式解决这个问题。
创建角色并将角色分配给用户。 有时为每个用户创建一个角色甚至可能很有用, 以获得尽可能最好的粒度,而在其他情况下,您将授予星号权限 对于管理员类型的功能。
Install
$ yarn add @aclify/aclify
Features
- Users
- Roles
- Hierarchies
- Resources
- Express middleware for protecting resources.
- Robust implementation with good unit test coverage.
- Strict typing
Documentation
- addUserRoles
- removeUserRoles
- removeUser
- userRoles
- roleUsers
- hasRole
- addRoleParents
- removeRoleParents
- removeRole
- removeResource
- allow
- removeAllow
- allowedPermissions
- isAllowed
- areAnyRolesAllowed
- whatResources
- middleware
- store
Stores
Aclify 提供了多种存储数据的可能性:
- Memory
- Redis
- MongoDB
Examples
通过要求它并使用有效的存储实例实例化它来创建 acl 模块:
From import
import * as Aclify from '@aclify/aclify';
// Using Redis store
const acl = new Aclify.Acl(new Aclify.RedisStore(RedisClient, {prefix: 'acl_'}));
// Or Using the Memory store
const acl = new Aclify.Acl(new Aclify.MemoryStore());
// Or Using the MongoDB store
const acl = new Aclify.Acl(new Aclify.MongoDBStore(db, {prefix: 'acl_'}));
以下所有函数都返回一个 Promise。
通过授予权限隐式创建角色:
// guest is allowed to view blogs
await acl.allow('guest', 'blogs', 'view');
// allow function accepts arrays as any parameter
await acl.allow('member', 'blogs', ['edit', 'view', 'delete']);
同样通过为用户分配角色来隐式创建用户:
await acl.addUserRoles('joed', 'guest');
可以通过将父级分配给角色来创建角色层次结构:
await acl.addRoleParents('baz', ['foo', 'bar']);
请注意,调用所有函数的顺序是无关紧要的(您可以先添加父级,然后再添加父级) assign permissions to roles later)
await acl.allow('foo', ['blogs', 'forums', 'news'], ['view', 'delete']);
Use the wildcard to give all permissions:
await acl.allow('admin', ['blogs', 'forums'], '*');
有时需要对许多不同的角色和资源设置权限。 这个会 导致不必要的嵌套回调来处理错误。 而是使用以下方法:
await acl.allow([
{
roles:['guest', 'member'],
allows:[
{resources:'blogs', permissions:'get'},
{resources:['forums', 'news'], permissions:['get', 'put', 'delete']}
]
},
{
roles:['gold', 'silver'],
allows:[
{resources:'cash', permissions:['sell', 'exchange']},
{resources:['account', 'deposit'], permissions:['put', 'delete']}
]
}
]);
您可以使用 isAllowed 检查用户是否有权访问给定资源:
const isAllowed = await acl.isAllowed('joed', 'blogs', 'view');
if (isAllowed) {
console.log("User Joed is allowed to view blogs");
}
当然,此函数也接受数组:
await acl.isAllowed('jsmith', 'blogs', ['edit', 'view', 'delete'])
请注意,必须满足所有权限才能获得 < em>是的。
有时需要知道给定用户对某些资源具有哪些权限:
const permissions = await acl.allowedPermissions('james', ['blogs', 'forums']);
它会返回一个资源数组:[权限],如下所示:
[
{
blogs: ['get', 'delete']
},
{
forums:['get', 'put']
}
]
最后,我们为 Express 提供了一个中间件,以便于保护资源。
acl.middleware()
我们可以这样保护资源:
app.put('/blogs/:id', acl.middleware(), function(req, res, next) {...}
中间件将保护由 req.url 命名的资源,从 req.session.userId 中选择用户并检查 的权限>req.method,所以上面的内容等价于这样的东西:
await acl.isAllowed(req.session.userId, '/blogs/12345', 'put')
中间件接受 3 个可选参数,这在某些情况下很有用。 例如,有时我们 不能将整个 url 视为资源:
app.put('/blogs/:id/comments/:commentId', acl.middleware(3), function(req, res, next) {…}
在这种情况下,资源将只是 url 的前三个组成部分(没有结尾斜杠)。
也可以添加自定义用户 ID 或检查除以下方法以外的其他权限:
app.put('/blogs/:id/comments/:commentId', acl.middleware(3, 'joed', 'post'), function(req, res, next) {…}
Methods
addUserRoles( userId, roles )
将角色添加到给定用户 ID。
参数
userId {String|Number} User id.
roles {String|Array} Role(s) to add to the user id.
removeUser( userId )
删除用户。
参数
userId {String|Number} User id.
removeUserRoles( userId, roles )
删除给定用户的角色。
参数
userId {String|Number} User id.
roles {String|Array} Role(s) to remove to the user id.
userRoles( userId )
返回给定用户的所有角色。
参数
userId {String|Number} User id.
roleUsers( rolename )
返回具有给定角色的所有用户。
Arguments
rolename {String|Number} User id.
hasRole( userId, rolename )
返回布尔值用户是否具有角色
Arguments
userId {String|Number} User id.
rolename {String|Number} role name.
addRoleParents( role, parents )
将父项或父项列表添加到角色。
参数
role {String} Child role.
parents {String|Array} Parent role(s) to be added.
removeRoleParents( role, parents )
从角色中移除父项或父项列表。
如果未指定 parents
,则删除所有父级。
参数
role {String} Child role.
parents {String|Array} Parent role(s) to be removed [optional].
removeRole( role )
从系统中删除一个角色。
Arguments
role {String} Role to be removed
removeResource( resource )
从系统中删除资源
Arguments
resource {String} Resource to be removed
allow( roles, resources, permissions )
将给定权限添加到给定资源上的给定角色。
Arguments
roles {String|Array} role(s) to add permissions to.
resources {String|Array} resource(s) to add permisisons to.
permissions {String|Array} permission(s) to add to the roles over the resources.
allow( permissionsArray )
Arguments
permissionsArray {Array} Array with objects expressing what permissions to give.
[{roles: {String|Array}, allows: [{resources:{String|Array}, permissions:{String|Array}]]
removeAllow( role, resources, permissions )
从给定角色拥有的给定角色移除权限角色。
注意:我们在删除空的 role_resources 时失去了原子性。
参数
role {String}
resources {String|Array}
permissions {String|Array}
allowedPermissions( userId, resources )
返回给定用户必须拥有的所有允许权限 访问给定的资源。
它返回一个对象数组,其中每个对象映射一个 资源名称到该资源的权限列表。
参数
userId {String|Number} User id.
resources {String|Array} resource(s) to ask permissions for.
isAllowed( userId, resource, permissions )
检查是否允许给定用户访问给定的资源 权限(注意:它必须满足所有权限)。
参数
userId {String|Number} User id.
resource {String} resource to ask permissions for.
permissions {String|Array} asked permissions.
areAnyRolesAllowed( roles, resource, permissions )
如果任何给定角色具有正确的权限,则返回 true。
参数
roles {String|Array} Role(s) to check the permissions for.
resource {String} resource to ask permissions for.
permissions {String|Array} asked permissions.
whatResources( role )
返回给定角色有权访问的资源。
参数
role {String|Array} Roles
whatResources(role, permissions )
返回角色对哪些资源具有给定权限。
参数
role {String|Array} Roles
permissions {String|Array} Permissions
middleware( [numPathComponents, userId, permissions] )
用于 express 的中间件。
要为 userId 创建自定义 getter,请传递一个函数 (req, res),该函数在调用时返回 userId(不能是异步的)。
参数
numPathComponents {Number} number of components in the url to be considered part of the resource name.
userId {String|Number|Function} the user id for the acl system (defaults to req.session.userId)
permissions {String|Array} the permission(s) to check for (defaults to req.method.toLowerCase())
使用 Redis 客户端 client
创建一个新的 Redis 存储。
Tests
$ yarn test
Scripts
使用 yarn
@aclify/aclify
Description
This module provides a Node Access Control Lists implementation inspired by ZendACL and nodeacl package.
When you develop a web site or application you will soon notice that sessions are not enough to protect all the available resources. Avoiding that malicious users access other users content proves a much more complicated task than anticipated. ACL can solve this problem in a flexible and elegant way.
Create roles and assign roles to users. Sometimes it may even be useful to create one role per user, to get the finest granularity possible, while in other situations you will give the asterisk permission for admin kind of functionality.
Install
$ yarn add @aclify/aclify
Features
- Users
- Roles
- Hierarchies
- Resources
- Express middleware for protecting resources.
- Robust implementation with good unit test coverage.
- Strict typing
Documentation
- addUserRoles
- removeUserRoles
- removeUser
- userRoles
- roleUsers
- hasRole
- addRoleParents
- removeRoleParents
- removeRole
- removeResource
- allow
- removeAllow
- allowedPermissions
- isAllowed
- areAnyRolesAllowed
- whatResources
- middleware
- store
Stores
Aclify offers several possibilities to store your data:
- Memory
- Redis
- MongoDB
Examples
Create your acl module by requiring it and instantiating it with a valid store instance:
From import
import * as Aclify from '@aclify/aclify';
// Using Redis store
const acl = new Aclify.Acl(new Aclify.RedisStore(RedisClient, {prefix: 'acl_'}));
// Or Using the Memory store
const acl = new Aclify.Acl(new Aclify.MemoryStore());
// Or Using the MongoDB store
const acl = new Aclify.Acl(new Aclify.MongoDBStore(db, {prefix: 'acl_'}));
All the following functions return a Promise.
Create roles implicitly by giving them permissions:
// guest is allowed to view blogs
await acl.allow('guest', 'blogs', 'view');
// allow function accepts arrays as any parameter
await acl.allow('member', 'blogs', ['edit', 'view', 'delete']);
Users are likewise created implicitly by assigning them roles:
await acl.addUserRoles('joed', 'guest');
Hierarchies of roles can be created by assigning parents to roles:
await acl.addRoleParents('baz', ['foo', 'bar']);
Note that the order in which you call all the functions is irrelevant (you can add parents first and assign permissions to roles later)
await acl.allow('foo', ['blogs', 'forums', 'news'], ['view', 'delete']);
Use the wildcard to give all permissions:
await acl.allow('admin', ['blogs', 'forums'], '*');
Sometimes is necessary to set permissions on many different roles and resources. This would lead to unnecessary nested callbacks for handling errors. Instead use the following:
await acl.allow([
{
roles:['guest', 'member'],
allows:[
{resources:'blogs', permissions:'get'},
{resources:['forums', 'news'], permissions:['get', 'put', 'delete']}
]
},
{
roles:['gold', 'silver'],
allows:[
{resources:'cash', permissions:['sell', 'exchange']},
{resources:['account', 'deposit'], permissions:['put', 'delete']}
]
}
]);
You can check if a user has permissions to access a given resource with isAllowed:
const isAllowed = await acl.isAllowed('joed', 'blogs', 'view');
if (isAllowed) {
console.log("User Joed is allowed to view blogs");
}
Of course arrays are also accepted in this function:
await acl.isAllowed('jsmith', 'blogs', ['edit', 'view', 'delete'])
Note that all permissions must be fulfilled in order to get true.
Sometimes is necessary to know what permissions a given user has over certain resources:
const permissions = await acl.allowedPermissions('james', ['blogs', 'forums']);
It will return an array of resource:[permissions] like this:
[
{
blogs: ['get', 'delete']
},
{
forums:['get', 'put']
}
]
Finally, we provide a middleware for Express for easy protection of resources.
acl.middleware()
We can protect a resource like this:
app.put('/blogs/:id', acl.middleware(), function(req, res, next) {...}
The middleware will protect the resource named by req.url, pick the user from req.session.userId and check the permission for req.method, so the above would be equivalent to something like this:
await acl.isAllowed(req.session.userId, '/blogs/12345', 'put')
The middleware accepts 3 optional arguments, that are useful in some situations. For example, sometimes we cannot consider the whole url as the resource:
app.put('/blogs/:id/comments/:commentId', acl.middleware(3), function(req, res, next) {…}
In this case the resource will be just the three first components of the url (without the ending slash).
It is also possible to add a custom userId or check for other permissions than the method:
app.put('/blogs/:id/comments/:commentId', acl.middleware(3, 'joed', 'post'), function(req, res, next) {…}
Methods
addUserRoles( userId, roles )
Adds roles to a given user id.
Arguments
userId {String|Number} User id.
roles {String|Array} Role(s) to add to the user id.
removeUser( userId )
Remove user.
Arguments
userId {String|Number} User id.
removeUserRoles( userId, roles )
Remove roles from a given user.
Arguments
userId {String|Number} User id.
roles {String|Array} Role(s) to remove to the user id.
userRoles( userId )
Return all the roles from a given user.
Arguments
userId {String|Number} User id.
roleUsers( rolename )
Return all users who has a given role.
Arguments
rolename {String|Number} User id.
hasRole( userId, rolename )
Return boolean whether user has the role
Arguments
userId {String|Number} User id.
rolename {String|Number} role name.
addRoleParents( role, parents )
Adds a parent or parent list to role.
Arguments
role {String} Child role.
parents {String|Array} Parent role(s) to be added.
removeRoleParents( role, parents )
Removes a parent or parent list from role.
If parents
is not specified, removes all parents.
Arguments
role {String} Child role.
parents {String|Array} Parent role(s) to be removed [optional].
removeRole( role )
Removes a role from the system.
Arguments
role {String} Role to be removed
removeResource( resource )
Removes a resource from the system
Arguments
resource {String} Resource to be removed
allow( roles, resources, permissions )
Adds the given permissions to the given roles over the given resources.
Arguments
roles {String|Array} role(s) to add permissions to.
resources {String|Array} resource(s) to add permisisons to.
permissions {String|Array} permission(s) to add to the roles over the resources.
allow( permissionsArray )
Arguments
permissionsArray {Array} Array with objects expressing what permissions to give.
[{roles: {String|Array}, allows: [{resources:{String|Array}, permissions:{String|Array}]]
removeAllow( role, resources, permissions )
Remove permissions from the given roles owned by the given role.
Note: we loose atomicity when removing empty role_resources.
Arguments
role {String}
resources {String|Array}
permissions {String|Array}
allowedPermissions( userId, resources )
Returns all the allowable permissions a given user have to access the given resources.
It returns an array of objects where every object maps a resource name to a list of permissions for that resource.
Arguments
userId {String|Number} User id.
resources {String|Array} resource(s) to ask permissions for.
isAllowed( userId, resource, permissions )
Checks if the given user is allowed to access the resource for the given permissions (note: it must fulfill all the permissions).
Arguments
userId {String|Number} User id.
resource {String} resource to ask permissions for.
permissions {String|Array} asked permissions.
areAnyRolesAllowed( roles, resource, permissions )
Returns true if any of the given roles have the right permissions.
Arguments
roles {String|Array} Role(s) to check the permissions for.
resource {String} resource to ask permissions for.
permissions {String|Array} asked permissions.
whatResources( role )
Returns what resources a given role has permissions over.
Arguments
role {String|Array} Roles
whatResources(role, permissions )
Returns what resources a role has the given permissions over.
Arguments
role {String|Array} Roles
permissions {String|Array} Permissions
middleware( [numPathComponents, userId, permissions] )
Middleware for express.
To create a custom getter for userId, pass a function(req, res) which returns the userId when called (must not be async).
Arguments
numPathComponents {Number} number of components in the url to be considered part of the resource name.
userId {String|Number|Function} the user id for the acl system (defaults to req.session.userId)
permissions {String|Array} the permission(s) to check for (defaults to req.method.toLowerCase())
Creates a new Redis store using Redis client client
.
Tests
$ yarn test
Scripts
Run using yarn
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。