1use chrono::{DateTime, Utc};
21use rustango::sql::Auto;
22use rustango::Model;
23use serde::{Deserialize, Serialize};
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
28pub enum Action {
29 View,
30 Add,
31 Edit,
32 Publish,
33 Delete,
34 Access,
40 AccessAdmin,
47}
48
49impl Action {
50 #[must_use]
51 pub fn as_str(self) -> &'static str {
52 match self {
53 Self::View => "view",
54 Self::Add => "add",
55 Self::Edit => "edit",
56 Self::Publish => "publish",
57 Self::Delete => "delete",
58 Self::Access => "access",
59 Self::AccessAdmin => "access_admin",
60 }
61 }
62
63 #[must_use]
68 pub fn all() -> &'static [Action] {
69 &[
70 Self::View,
71 Self::Add,
72 Self::Edit,
73 Self::Publish,
74 Self::Delete,
75 ]
76 }
77}
78
79#[derive(Model, Debug, Clone, Serialize, Deserialize)]
83#[rustango(
84 table = "cms_page_permission",
85 app = "cms",
86 admin(
87 list_display = "page_id, role_id, permission",
88 ordering = "page_id, role_id, permission",
89 )
90)]
91pub struct PagePermission {
92 #[rustango(primary_key)]
93 pub id: Auto<i64>,
94
95 #[rustango(fk = "cms_page", on = "id", index)]
96 pub page_id: i64,
97
98 #[rustango(fk = "rustango_roles", on = "id", index)]
99 pub role_id: i64,
100
101 #[rustango(max_length = 32)]
104 pub permission: String,
105
106 #[rustango(auto_now_add)]
107 pub created_at: Auto<DateTime<Utc>>,
108}
109
110pub async fn user_can(
122 pool: &rustango::sql::Pool,
123 user_id: i64,
124 page_id: i64,
125 action: Action,
126) -> Result<bool, rustango::sql::ExecError> {
127 use rustango::core::Column as _;
128 use rustango::sql::FetcherPool as _;
129
130 let user = rustango::tenancy::auth::User::objects()
132 .where_(rustango::tenancy::auth::User::id.eq(user_id))
133 .first(pool)
134 .await?;
135 let Some(user) = user else {
136 return Ok(false);
137 };
138 if !user.active {
139 return Ok(false);
140 }
141 if user.is_superuser {
142 return Ok(true);
143 }
144
145 let memberships: Vec<rustango::tenancy::permissions::UserRole> =
147 rustango::tenancy::permissions::UserRole::objects()
148 .where_(rustango::tenancy::permissions::UserRole::user_id.eq(user_id))
149 .fetch(pool)
150 .await?;
151 if memberships.is_empty() {
152 return Ok(false);
153 }
154 let role_ids: Vec<i64> = memberships.iter().map(|m| m.role_id).collect();
155
156 let target = crate::page::Page::objects()
162 .where_(crate::page::Page::id.eq(page_id))
163 .first(pool)
164 .await?;
165 let Some(mut current) = target else {
166 return Ok(false);
167 };
168 let mut chain_ids: Vec<i64> = Vec::new();
169 chain_ids.push(current.id.get().copied().unwrap_or_default());
170 while let Some(pid) = current.parent_id {
171 let parent = crate::page::Page::objects()
172 .where_(crate::page::Page::id.eq(pid))
173 .first(pool)
174 .await?;
175 match parent {
176 Some(p) => {
177 chain_ids.push(pid);
178 current = p;
179 }
180 None => break,
181 }
182 }
183
184 let grants: Vec<PagePermission> = PagePermission::objects()
186 .where_(PagePermission::page_id.is_in(chain_ids.iter().copied()))
187 .where_(PagePermission::role_id.is_in(role_ids.iter().copied()))
188 .where_(PagePermission::permission.eq(action.as_str().to_owned()))
189 .fetch(pool)
190 .await?;
191 Ok(!grants.is_empty())
192}
193
194#[derive(Model, Debug, Clone, Serialize, Deserialize)]
199#[rustango(
200 table = "cms_collection_permission",
201 app = "cms",
202 admin(
203 list_display = "collection_id, role_id, permission",
204 ordering = "collection_id, role_id, permission",
205 )
206)]
207pub struct CollectionPermission {
208 #[rustango(primary_key)]
209 pub id: Auto<i64>,
210
211 #[rustango(fk = "cms_media_collection", on = "id", index)]
212 pub collection_id: i64,
213
214 #[rustango(fk = "rustango_roles", on = "id", index)]
215 pub role_id: i64,
216
217 #[rustango(max_length = 32)]
218 pub permission: String,
219
220 #[rustango(auto_now_add)]
221 pub created_at: Auto<DateTime<Utc>>,
222}
223
224pub async fn user_can_in_collection(
232 pool: &rustango::sql::Pool,
233 user_id: i64,
234 collection_id: i64,
235 action: Action,
236) -> Result<bool, rustango::sql::ExecError> {
237 use rustango::core::Column as _;
238 use rustango::sql::FetcherPool as _;
239
240 let user = rustango::tenancy::auth::User::objects()
241 .where_(rustango::tenancy::auth::User::id.eq(user_id))
242 .first(pool)
243 .await?;
244 let Some(user) = user else {
245 return Ok(false);
246 };
247 if !user.active {
248 return Ok(false);
249 }
250 if user.is_superuser {
251 return Ok(true);
252 }
253
254 let memberships: Vec<rustango::tenancy::permissions::UserRole> =
255 rustango::tenancy::permissions::UserRole::objects()
256 .where_(rustango::tenancy::permissions::UserRole::user_id.eq(user_id))
257 .fetch(pool)
258 .await?;
259 if memberships.is_empty() {
260 return Ok(false);
261 }
262 let role_ids: Vec<i64> = memberships.iter().map(|m| m.role_id).collect();
263
264 let target = crate::media::MediaCollection::objects()
266 .where_(crate::media::MediaCollection::id.eq(collection_id))
267 .first(pool)
268 .await?;
269 let Some(mut current) = target else {
270 return Ok(false);
271 };
272 let mut chain_ids: Vec<i64> = Vec::new();
273 chain_ids.push(current.id.get().copied().unwrap_or_default());
274 while let Some(pid) = current.parent_id {
275 let parent = crate::media::MediaCollection::objects()
276 .where_(crate::media::MediaCollection::id.eq(pid))
277 .first(pool)
278 .await?;
279 match parent {
280 Some(p) => {
281 chain_ids.push(pid);
282 current = p;
283 }
284 None => break,
285 }
286 }
287
288 let grants: Vec<CollectionPermission> = CollectionPermission::objects()
289 .where_(CollectionPermission::collection_id.is_in(chain_ids.iter().copied()))
290 .where_(CollectionPermission::role_id.is_in(role_ids.iter().copied()))
291 .where_(CollectionPermission::permission.eq(action.as_str().to_owned()))
292 .fetch(pool)
293 .await?;
294 Ok(!grants.is_empty())
295}
296
297pub async fn viewable_page_ids(
308 pool: &rustango::sql::Pool,
309 user_id: i64,
310 pages: &[(i64, Option<i64>)],
311) -> Result<std::collections::HashSet<i64>, rustango::sql::ExecError> {
312 use rustango::core::Column as _;
313 use rustango::sql::FetcherPool as _;
314 use std::collections::{HashMap, HashSet};
315
316 let user = rustango::tenancy::auth::User::objects()
317 .where_(rustango::tenancy::auth::User::id.eq(user_id))
318 .first(pool)
319 .await?;
320 match user {
321 Some(u) if u.active && u.is_superuser => return Ok(pages.iter().map(|p| p.0).collect()),
322 Some(u) if u.active => {}
323 _ => return Ok(HashSet::new()),
324 }
325 let role_ids: Vec<i64> = rustango::tenancy::permissions::UserRole::objects()
326 .where_(rustango::tenancy::permissions::UserRole::user_id.eq(user_id))
327 .fetch(pool)
328 .await?
329 .into_iter()
330 .map(|m| m.role_id)
331 .collect();
332 if role_ids.is_empty() {
333 return Ok(HashSet::new());
334 }
335 let granted: HashSet<i64> = PagePermission::objects()
336 .where_(PagePermission::role_id.is_in(role_ids))
337 .where_(PagePermission::permission.eq(Action::View.as_str().to_owned()))
338 .fetch(pool)
339 .await?
340 .into_iter()
341 .map(|g| g.page_id)
342 .collect();
343 if granted.is_empty() {
344 return Ok(HashSet::new());
345 }
346
347 let mut parent_of: HashMap<i64, Option<i64>> = pages.iter().copied().collect();
349 loop {
350 let missing: HashSet<i64> = parent_of
351 .values()
352 .flatten()
353 .copied()
354 .filter(|id| !parent_of.contains_key(id))
355 .collect();
356 if missing.is_empty() {
357 break;
358 }
359 let found: Vec<crate::page::Page> = crate::page::Page::objects()
360 .where_(crate::page::Page::id.is_in(missing.iter().copied()))
361 .fetch(pool)
362 .await?;
363 for id in missing {
364 let parent = found
366 .iter()
367 .find(|p| p.id.get().copied() == Some(id))
368 .and_then(|p| p.parent_id);
369 parent_of.insert(id, parent);
370 }
371 }
372
373 let viewable = |mut id: i64| {
374 for _ in 0..=parent_of.len() {
376 if granted.contains(&id) {
377 return true;
378 }
379 match parent_of.get(&id).copied().flatten() {
380 Some(parent) => id = parent,
381 None => return false,
382 }
383 }
384 false
385 };
386 Ok(pages.iter().map(|p| p.0).filter(|&id| viewable(id)).collect())
387}
388
389pub async fn user_can_matrix(
398 pool: &rustango::sql::Pool,
399 user_id: i64,
400 page_id: i64,
401) -> Result<std::collections::HashMap<&'static str, bool>, rustango::sql::ExecError> {
402 let mut out = std::collections::HashMap::new();
403 for action in Action::all() {
404 let allowed = user_can(pool, user_id, page_id, *action).await?;
405 out.insert(action.as_str(), allowed);
406 }
407 Ok(out)
408}
409
410pub async fn user_codenames(
423 pool: &rustango::sql::Pool,
424 user_id: i64,
425) -> Result<std::collections::HashSet<String>, rustango::sql::ExecError> {
426 use rustango::core::Column as _;
427 use rustango::sql::FetcherPool as _;
428
429 let memberships: Vec<rustango::tenancy::permissions::UserRole> =
430 rustango::tenancy::permissions::UserRole::objects()
431 .where_(rustango::tenancy::permissions::UserRole::user_id.eq(user_id))
432 .fetch(pool)
433 .await?;
434 if memberships.is_empty() {
435 return Ok(std::collections::HashSet::new());
436 }
437 let role_ids: Vec<i64> = memberships.iter().map(|m| m.role_id).collect();
438 let grants: Vec<rustango::tenancy::permissions::RolePermission> =
439 rustango::tenancy::permissions::RolePermission::objects()
440 .where_(
441 rustango::tenancy::permissions::RolePermission::role_id
442 .is_in(role_ids.iter().copied()),
443 )
444 .fetch(pool)
445 .await?;
446 Ok(grants.into_iter().map(|g| g.codename).collect())
447}