Skip to main content

casdoor_rust_sdk/
enforce.rs

1// Copyright 2026 The Casdoor Authors. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use serde::{Deserialize, Serialize};
16use serde_json::Value;
17
18use crate::client::{Client, PostBody, Response};
19use crate::error::{CasdoorError, Result};
20
21/// PermissionRule has the same definition as
22/// <https://github.com/casdoor/casdoor/blob/master/object/permission_rule.go>.
23#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "camelCase", default)]
25pub struct PermissionRule {
26    pub ptype: String,
27    pub v0: String,
28    pub v1: String,
29    pub v2: String,
30    pub v3: String,
31    pub v4: String,
32    pub v5: String,
33    pub id: String,
34}
35
36/// A Casbin request, such as `["alice", "data1", "read"]`.
37pub type CasbinRequest = Vec<Value>;
38
39impl Client {
40    /// Check whether a Casbin request is allowed by a permission, a model, a resource or
41    /// an enforcer. Only one of `permission_id`, `model_id`, `resource_id` and
42    /// `enforcer_id` needs to be given, the others can be empty.
43    pub async fn enforce(
44        &self,
45        permission_id: &str,
46        model_id: &str,
47        resource_id: &str,
48        enforcer_id: &str,
49        owner: &str,
50        casbin_request: &CasbinRequest,
51    ) -> Result<bool> {
52        let post_bytes = serde_json::to_vec(casbin_request)?;
53
54        let response = self
55            .do_enforce(
56                "enforce",
57                permission_id,
58                model_id,
59                resource_id,
60                enforcer_id,
61                owner,
62                post_bytes,
63            )
64            .await?;
65
66        let results = response.data.as_array().ok_or(CasdoorError::InvalidData)?;
67
68        for result in results {
69            let is_allowed = result.as_bool().ok_or(CasdoorError::InvalidData)?;
70            if is_allowed {
71                return Ok(true);
72            }
73        }
74
75        Ok(false)
76    }
77
78    /// Check a batch of Casbin requests at once, the returned matrix has one row per
79    /// permission and one column per request.
80    pub async fn batch_enforce(
81        &self,
82        permission_id: &str,
83        model_id: &str,
84        resource_id: &str,
85        enforcer_id: &str,
86        owner: &str,
87        casbin_requests: &[CasbinRequest],
88    ) -> Result<Vec<Vec<bool>>> {
89        let post_bytes = serde_json::to_vec(casbin_requests)?;
90
91        let response = self
92            .do_enforce(
93                "batch-enforce",
94                permission_id,
95                model_id,
96                resource_id,
97                enforcer_id,
98                owner,
99                post_bytes,
100            )
101            .await?;
102
103        serde_json::from_value(response.data).map_err(|_| CasdoorError::InvalidData)
104    }
105
106    #[allow(clippy::too_many_arguments)]
107    async fn do_enforce(
108        &self,
109        action: &str,
110        permission_id: &str,
111        model_id: &str,
112        resource_id: &str,
113        enforcer_id: &str,
114        owner: &str,
115        post_bytes: Vec<u8>,
116    ) -> Result<Response> {
117        self.do_post(
118            action,
119            &[
120                ("permissionId", permission_id),
121                ("modelId", model_id),
122                ("resourceId", resource_id),
123                ("enforcerId", enforcer_id),
124                ("owner", owner),
125            ],
126            PostBody::Raw(post_bytes),
127        )
128        .await
129    }
130}