junobuild_collections/assert/
stores.rs

1use crate::types::rules::Permission;
2use candid::Principal;
3use junobuild_shared::controllers::controller_can_write;
4use junobuild_shared::types::state::{Controllers, UserId};
5use junobuild_shared::utils::{principal_not_anonymous, principal_not_anonymous_and_equal};
6
7pub fn assert_permission(
8    permission: &Permission,
9    owner: Principal,
10    caller: Principal,
11    controllers: &Controllers,
12) -> bool {
13    assert_permission_with(permission, owner, caller, controllers, controller_can_write)
14}
15
16pub fn assert_permission_with(
17    permission: &Permission,
18    owner: Principal,
19    caller: Principal,
20    controllers: &Controllers,
21    is_allowed_controller: fn(UserId, &Controllers) -> bool,
22) -> bool {
23    match permission {
24        Permission::Public => true,
25        Permission::Private => assert_caller(caller, owner),
26        Permission::Managed => {
27            assert_caller(caller, owner) || controller_can_write(caller, controllers)
28        }
29        Permission::Controllers => is_allowed_controller(caller, controllers),
30    }
31}
32
33/// If a document or asset is about to be created for the first time, it can be initialized without further rules unless the collection is set as controller and the caller is not a controller.
34/// This can be useful e.g. when a collection read permission is set to public but only the administrator can add content.
35pub fn assert_create_permission(
36    permission: &Permission,
37    caller: Principal,
38    controllers: &Controllers,
39) -> bool {
40    assert_create_permission_with(permission, caller, controllers, controller_can_write)
41}
42
43pub fn assert_create_permission_with(
44    permission: &Permission,
45    caller: Principal,
46    controllers: &Controllers,
47    is_allowed_controller: fn(UserId, &Controllers) -> bool,
48) -> bool {
49    match permission {
50        Permission::Public => true,
51        Permission::Private => assert_not_anonymous(caller),
52        Permission::Managed => assert_not_anonymous(caller),
53        Permission::Controllers => is_allowed_controller(caller, controllers),
54    }
55}
56
57fn assert_caller(caller: Principal, owner: Principal) -> bool {
58    principal_not_anonymous_and_equal(caller, owner)
59}
60
61fn assert_not_anonymous(caller: Principal) -> bool {
62    principal_not_anonymous(caller)
63}
64
65pub fn public_permission(permission: &Permission) -> bool {
66    matches!(permission, Permission::Public)
67}