rustango_cms/
collection_view_restriction.rs1use chrono::{DateTime, Utc};
15use rustango::sql::Auto;
16use rustango::Model;
17use serde::{Deserialize, Serialize};
18
19pub use crate::view_restriction::RestrictionKind;
20
21#[derive(Model, Debug, Clone, Serialize, Deserialize)]
22#[rustango(
23 table = "cms_collection_view_restriction",
24 app = "cms",
25 display = "collection_id",
26 admin(
27 list_display = "collection_id, kind, created_at",
28 ordering = "-created_at",
29 list_filter = "kind",
30 )
31)]
32pub struct CollectionViewRestriction {
33 #[rustango(primary_key)]
34 pub id: Auto<i64>,
35
36 #[rustango(fk = "cms_media_collection", on = "id", index)]
38 pub collection_id: i64,
39
40 #[rustango(max_length = 16, index)]
42 pub kind: String,
43
44 #[rustango(max_length = 255, default = "''")]
46 pub password_hash: String,
47
48 pub group_ids: serde_json::Value,
51
52 #[rustango(default = "'[]'")]
56 pub codenames: serde_json::Value,
57
58 #[rustango(auto_now_add)]
59 pub created_at: Auto<DateTime<Utc>>,
60
61 #[rustango(auto_now)]
62 pub updated_at: Auto<DateTime<Utc>>,
63}
64
65impl CollectionViewRestriction {
66 #[must_use]
67 pub fn parsed_kind(&self) -> Option<RestrictionKind> {
68 RestrictionKind::parse(&self.kind)
69 }
70
71 #[must_use]
72 pub fn parsed_groups(&self) -> Vec<i64> {
73 self.group_ids
74 .as_array()
75 .map(|arr| arr.iter().filter_map(|v| v.as_i64()).collect::<Vec<_>>())
76 .unwrap_or_default()
77 }
78
79 #[must_use]
82 pub fn parsed_codenames(&self) -> Vec<String> {
83 self.codenames
84 .as_array()
85 .map(|arr| {
86 arr.iter()
87 .filter_map(|v| v.as_str().map(str::to_owned))
88 .collect::<Vec<_>>()
89 })
90 .unwrap_or_default()
91 }
92}
93
94pub async fn direct_for_collection(
99 pool: &rustango::sql::Pool,
100 collection_id: i64,
101) -> Result<Option<CollectionViewRestriction>, rustango::sql::ExecError> {
102 use rustango::core::Column as _;
103 use rustango::sql::FetcherPool as _;
104 let rows: Vec<CollectionViewRestriction> = CollectionViewRestriction::objects()
105 .where_(CollectionViewRestriction::collection_id.eq(collection_id))
106 .fetch(pool)
107 .await?;
108 Ok(rows.into_iter().next())
109}
110
111pub async fn effective_for_collection(
119 pool: &rustango::sql::Pool,
120 collection_id: i64,
121) -> Result<Option<CollectionViewRestriction>, rustango::sql::ExecError> {
122 use rustango::core::Column as _;
123 use rustango::sql::FetcherPool as _;
124
125 let mut chain: Vec<i64> = vec![collection_id];
129 let mut seen: std::collections::HashSet<i64> = std::collections::HashSet::new();
130 seen.insert(collection_id);
131 let mut current_id = collection_id;
132 for _ in 0..16 {
133 let rows: Vec<crate::media::MediaCollection> = crate::media::MediaCollection::objects()
134 .where_(crate::media::MediaCollection::id.eq(current_id))
135 .fetch(pool)
136 .await?;
137 let Some(c) = rows.into_iter().next() else {
138 break;
139 };
140 let Some(pid) = c.parent_id else {
141 break;
142 };
143 if !seen.insert(pid) {
144 break;
145 }
146 chain.push(pid);
147 current_id = pid;
148 }
149
150 let restrictions: Vec<CollectionViewRestriction> = CollectionViewRestriction::objects()
151 .where_(CollectionViewRestriction::collection_id.is_in(chain.clone()))
152 .fetch(pool)
153 .await?;
154 if restrictions.is_empty() {
155 return Ok(None);
156 }
157 let by_collection: std::collections::HashMap<i64, CollectionViewRestriction> = restrictions
158 .into_iter()
159 .map(|r| (r.collection_id, r))
160 .collect();
161 for cid in chain {
162 if let Some(r) = by_collection.get(&cid) {
163 return Ok(Some(r.clone()));
164 }
165 }
166 Ok(None)
167}
168
169pub async fn denied_collection_ids(
182 pool: &rustango::sql::Pool,
183 viewer: Option<&rustango::tenancy::auth::User>,
184 collection_ids: &[i64],
185) -> std::collections::HashSet<i64> {
186 use rustango::sql::FetcherPool as _;
187 use std::collections::{HashMap, HashSet};
188
189 let mut denied: HashSet<i64> = HashSet::new();
190 if collection_ids.is_empty() {
191 return denied;
192 }
193
194 let restrictions: Vec<CollectionViewRestriction> =
195 match CollectionViewRestriction::objects().fetch(pool).await {
196 Ok(r) => r,
197 Err(e) => {
198 tracing::warn!(
202 target: "rustango_cms::collection_view_restriction",
203 error = %e,
204 "collection restriction lookup failed; treating collections as public",
205 );
206 return denied;
207 }
208 };
209 if restrictions.is_empty() {
210 return denied;
211 }
212 let by_collection: HashMap<i64, &CollectionViewRestriction> = restrictions
213 .iter()
214 .map(|r| (r.collection_id, r))
215 .collect();
216
217 let parents: HashMap<i64, Option<i64>> = crate::media::MediaCollection::objects()
218 .fetch(pool)
219 .await
220 .unwrap_or_default()
221 .into_iter()
222 .filter_map(|c| c.id.get().copied().map(|id| (id, c.parent_id)))
223 .collect();
224
225 let facts = crate::view_restriction::viewer_facts(pool, viewer, true).await;
226
227 for &id in collection_ids {
228 let mut current = Some(id);
231 let mut seen: HashSet<i64> = HashSet::new();
232 for _ in 0..16 {
233 let Some(cid) = current else { break };
234 if !seen.insert(cid) {
235 break;
236 }
237 if let Some(r) = by_collection.get(&cid) {
238 if !facts.satisfies(r.parsed_kind(), &r.parsed_groups(), &r.parsed_codenames()) {
239 denied.insert(id);
240 }
241 break;
242 }
243 current = parents.get(&cid).copied().flatten();
244 }
245 }
246 denied
247}