Перейти к основному контенту

RBAC API

The RBAC API is a convenience layer for role-based operations (roles for user, users for role, permissions, etc.). It is a subset of the Management API aimed at RBAC use cases.

Ссылка​

The global variable e represents an Enforcer instance.

e, err := NewEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv")

GetRolesForUser()​

Retrieves all roles assigned to a user.

Например:

res := e.GetRolesForUser("alice")

GetUsersForRole()​

Retrieves all users assigned to a role.

Например:

res := e.GetUsersForRole("data1_admin")

HasRoleForUser()​

Checks whether a user has a specific role.

Например:

res := e.HasRoleForUser("alice", "data1_admin")

AddRoleForUser()​

Assigns a role to a user. Возвращает false, если у пользователя уже есть роль (то есть не затронуто).

Например:

e.AddRoleForUser("alice", "data2_admin")

AddRolesForUser()​

Assigns multiple roles to a user. Возвращает false, если у пользователя уже есть одна из этих ролей (то есть не затронуто).

Например:

var roles = []string{"data2_admin", "data1_admin"}
e.AddRolesForUser("alice", roles)

DeleteRoleForUser()​

Removes a role from a user. Возвращает false, если у пользователя нет роли (то есть не затронуто).

Например:

e.DeleteRoleForUser("alice", "data1_admin")

DeleteRolesForUser()​

Removes all roles from a user. Возвращает false, если у пользователя нет никаких ролей (то есть не затронуто).

Например:

e.DeleteRolesForUser("alice")

DeleteUser()​

Removes a user from the system. Возвращает false, если пользователя не существует (то есть не затронуто).

Например:

e.DeleteUser("alice")

DeleteRole()​

Removes a role from the system.

Например:

e.DeleteRole("data2_admin")

DeletePermission()​

Removes a permission from the system. Возвращает false, если разрешение не существует (т.е. не затронуто).

Например:

e.DeletePermission("read")

AddPermissionForUser()​

Grants a permission to a user or role. Возвращает false, если у пользователя или роли уже есть разрешение (т.е. не затронуто).

Например:

e.AddPermissionForUser("bob", "read")

AddPermissionsForUser()​

Grants multiple permissions to a user or role. Возвращает false, если у пользователя или роли уже есть одно из разрешений (т.е. не затронуто).

Например:

var permissions = [][]string{{"data1", "read"},{"data2","write"}}
for i := 0; i < len(permissions); i++ {
e.AddPermissionsForUser("alice", permissions[i])
}

DeletePermissionForUser()​

Revokes a permission from a user or role. Возвращает false, если у пользователя или роли нет разрешения (т.е. не затронуто).

Например:

e.DeletePermissionForUser("bob", "read")

DeletePermissionsForUser()​

Revokes all permissions from a user or role. Возвращает false, если у пользователя или роли нет никаких разрешений (т.е. не затронуто).

Например:

e.DeletePermissionsForUser("bob")

GetPermissionsForUser()​

Retrieves all permissions for a user or role.

Например:

e.GetPermissionsForUser("bob")

GetNamedPermissionsForUser()​

GetNamedPermissionsForUser gets permissions for a user or role by named policy.

Например:

p, alice, data1, read
p, bob, data2, write
p2, admin, create
g, alice, admin

GetNamedPermissionsForUser("p", "alice") will return [["alice", "data1", "read"]]. GetNamedPermissionsForUser("p2", "alice") will return [["admin", "create"]].

permissions, err := e.GetNamedPermissionsForUser("p", "alice")

HasPermissionForUser()​

HasPermissionForUser определяет, есть ли у пользователя разрешение.

Например:

e.HasPermissionForUser("alice", []string{"read"})

GetImplicitRolesForUser()​

GetImplicitRolesForUser получает неявные роли, которые имеет пользователь. По сравнению с GetRolesForUser(), эта функция извлекает косвенные роли помимо прямых ролей.

Например:

g, alice, role:admin  
g, role:admin, role:user

GetRolesForUser("alice") может получить только: ["role:admin"].
Но GetImplicitRolesForUser("alice") получит: ["role:admin", "role:user"].

Например:

e.GetImplicitRolesForUser("alice")

GetNamedImplicitRolesForUser()​

GetNamedImplicitRolesForUser gets implicit roles that a user has by named policy.

Например:

g, alice, admin
g, admin, super_admin
g2, alice, user
g2, user, guest

GetNamedImplicitRolesForUser("g", "alice") will return ["admin", "super_admin"]. GetNamedImplicitRolesForUser("g2", "alice") will return ["user", "guest"].

roles, err := e.GetNamedImplicitRolesForUser("g", "alice")

GetImplicitUsersForRole()​

GetImplicitUsersForRole получает всех пользователей, наследующих роль. По сравнению с GetUsersForRole(), эта функция извлекает косвенных пользователей.

Например:

g, alice, role:admin  
g, role:admin, role:user

GetUsersForRole("role:user") может получить только: ["role:admin"].
Но GetImplicitUesrsForRole("role:user") вернет: ["role:admin", "alice"].

Например:

users := e.GetImplicitUsersForRole("role:user")

GetImplicitPermissionsForUser()​

GetImplicitPermissionsForUser получает неявные разрешения для пользователя или роли.
По сравнению с GetPermissionsForUser(), эта функция извлекает разрешения для унаследованных ролей.

Например:

p, admin, data1, read  
p, alice, data2, read
g, alice, admin

GetPermissionsForUser("alice") может получить только: [["alice", "data2", "read"]].
Но GetImplicitPermissionsForUser("alice") получит: [["admin", "data1", "read"], ["alice", "data2", "read"]].

Например:

e.GetImplicitPermissionsForUser("alice")

GetNamedImplicitPermissionsForUser()​

GetNamedImplicitPermissionsForUser получает неявные разрешения для пользователя или роли по именованной политике. По сравнению с GetImplicitPermissionsForUser(), эта функция позволяет вам указать имя политики.

Например:

p, admin, data1, read
p2, admin, create
g, alice, admin

GetImplicitPermissionsForUser("alice") получает только: [["admin", "data1", "read"]], у которого политика по умолчанию "p"

Но вы можете указать политику как "p2", чтобы получить: [["admin", "create"]] с помощью GetNamedImplicitPermissionsForUser("p2","alice")

Например:

e.GetNamedImplicitPermissionsForUser("p2","alice")

GetDomainsForUser()​

GetDomainsForUser получает все домены, которые есть у пользователя.

Например:

p, admin, domain1, data1, read
p, admin, domain2, data2, read
p, admin, domain2, data2, write
g, alice, admin, domain1
g, alice, admin, domain2

GetDomainsForUser("alice") может получить ["domain1", "domain2"]

Например:

result, err := e.GetDomainsForUser("alice")

GetImplicitResourcesForUser()​

Returns all policies that apply to a user, including those inherited through roles.

Например:

p, alice, data1, read
p, bob, data2, write
p, data2_admin, data2, read
p, data2_admin, data2, write

g, alice, data2_admin

GetImplicitResourcesForUser("alice") вернет [[alice data1 read] [alice data2 read] [alice data2 write]]

resources, err := e.GetImplicitResourcesForUser("alice")

GetImplicitUsersForPermission()​

Retrieves all users with a specific permission, including those with implicit permissions through roles.

Например:

p, admin, data1, read
p, bob, data1, read
g, alice, admin

GetImplicitUsersForPermission("data1", "read") вернет: "alice", "bob".

Примечание: будут возвращены только пользователи, роли (2-й аргумент в "g") будут исключены.

users, err := e.GetImplicitUsersForPermission("data1", "read")

GetImplicitObjectPatternsForUser()​

Returns all object patterns (including wildcards) that a user can access for a given domain and action.

Например:

p, admin, chronicle/123, location/*, read
p, user, chronicle/456, location/789, read
g, alice, admin
g, bob, user

GetImplicitObjectPatternsForUser("alice", "chronicle/123", "read") will return ["location/*"]. GetImplicitObjectPatternsForUser("bob", "chronicle/456", "read") will return ["location/789"].

patterns, err := e.GetImplicitObjectPatternsForUser("alice", "chronicle/123", "read")

GetAllowedObjectConditions()​

Returns object conditions that a user can access.

Например:

p, alice, r.obj.price < 25, read
p, admin, r.obj.category_id = 2, read
p, bob, r.obj.author = bob, write

g, alice, admin

e.GetAllowedObjectConditions("alice", "read", "r.obj.") вернет "price < 25", "category_id = 2", nil

Примечание:

  1. prefix: Вы можете настроить префикс условий объекта, и "r.obj." обычно используется в качестве префикса. После удаления префикса остается условие объекта. Если есть политика obj, которая не соответствует требованию префикса, будет возвращена errors.ERR_OBJ_CONDITION.

  2. Если массив 'objectConditions' пуст, верните errors.ERR_EMPTY_CONDITION. Эта ошибка возвращается, потому что некоторые адаптеры данных ORM по умолчанию возвращают полные данные таблицы, когда они получают пустое условие, что часто противоречит ожиданиям (например, GORM). Если вы используете адаптер, который не ведет себя так, вы можете выбрать игнорирование этой ошибки.

conditions, err := e.GetAllowedObjectConditions("alice", "read", "r.obj.")

GetImplicitUsersForResource()​

Returns all users with access to a resource, including those with implicit permissions through roles.

Например:

p, alice, data1, read
p, bob, data2, write
p, data2_admin, data2, read
p, data2_admin, data2, write
g, alice, data2_admin

GetImplicitUsersForResource("data2") вернет ["bob", "data2", "write"], ["alice", "data2", "read"] ["alice", "data2", "write"]], nil.

GetImplicitUsersForResource("data1") вернет ["alice", "data1", "read"]], nil.

ImplicitUsers, err := e.GetImplicitUsersForResource("data2")
заметка

Будут возвращены только пользователи, роли (2-й аргумент в "g") будут исключены.

GetNamedImplicitUsersForResource()​

Returns all users with access to a resource through a named policy, including those with implicit permissions through roles. This function handles resource role relationships through named policies (e.g., g2, g3, etc.).

Например:

p, admin_group, admin_data, *
g, admin, admin_group
g2, app, admin_data

GetNamedImplicitUsersForResource("g2", "app") will return users who have access to admin_data through g2 relationship.

ImplicitUsers, err := e.GetNamedImplicitUsersForResource("g2", "app")

Comments are powered by giscus and GitHub Discussions. They load from giscus.app and GitHub only after you click the button below.