runique 3.0.2

A Django-inspired web framework for Rust with ORM, templates, and comprehensive security middleware
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
use std::sync::Arc;

use axum::http::Method;
use sea_orm::{ActiveModelTrait, ActiveValue::Set, EntityTrait, PaginatorTrait, QuerySelect};

use crate::admin::{
    forms::{UserAdminCreateForm, UserAdminEditForm},
    helper::{
        dyn_form::DynForm,
        resource_entry::{
            CountFn, CreateFn, DeleteFn, FormBuilder, GetFn, ListFn, ListParams, ResourceEntry,
            SortDir, UpdateFn,
        },
        sql_dialect::ilike,
    },
    resource::AdminResource,
};
use crate::forms::field::RuniqueForm;
use crate::utils::{
    aliases::{ADb, ATera, StrMap},
    constante::admin_context::{
        permission::GROUPES,
        user::{IS_ACTIVE, IS_STAFF},
    },
    forms::parse_bool,
    trad::{t, tf},
};

/// Replaces a user's group memberships with the comma-separated group ids in
/// `groupes`, all or nothing.
async fn replace_user_groupes(
    db: &ADb,
    user_id: crate::utils::pk::Pk,
    groupes: &str,
) -> Result<(), sea_orm::DbErr> {
    use sea_orm::TransactionTrait;

    let txn = db.begin().await?;
    write_user_groupes(&txn, user_id, groupes).await?;
    txn.commit().await
}

async fn write_user_groupes(
    txn: &sea_orm::DatabaseTransaction,
    user_id: crate::utils::pk::Pk,
    groupes: &str,
) -> Result<(), sea_orm::DbErr> {
    use crate::auth::permissions::users_groupes;
    use sea_orm::{ColumnTrait, QueryFilter};

    users_groupes::Entity::delete_many()
        .filter(users_groupes::Column::UserId.eq(user_id))
        .exec(txn)
        .await?;
    for groupe_id in groupes
        .split(',')
        .filter_map(|g| g.trim().parse::<i32>().ok())
    {
        users_groupes::ActiveModel {
            user_id: Set(user_id),
            groupe_id: Set(groupe_id),
        }
        .insert(txn)
        .await?;
    }
    Ok(())
}

/// Refuses to make active an account its owner never activated: the first
/// activation is the owner's, through the emailed link. Checked here for a
/// clear message — the database refuses it anyway.
async fn ensure_activatable(
    db: &ADb,
    id: crate::utils::pk::Pk,
    wants_active: bool,
) -> Result<(), sea_orm::DbErr> {
    if !wants_active {
        return Ok(());
    }
    let never_activated = crate::auth::user::Entity::find_by_id(id)
        .one(db)
        .await?
        .is_some_and(|u| u.activated_at.is_none());
    if never_activated {
        return Err(sea_orm::DbErr::Custom(
            t("admin.user.not_activated").into_owned(),
        ));
    }
    Ok(())
}

pub(super) fn user_entry() -> ResourceEntry {
    use crate::auth::user;
    use crate::utils::pk::Pk;

    let meta = AdminResource::new(
        "users",
        "runique::auth::user::Model",
        "UserAdminCreateForm",
        "Users",
    )
    .inject_password(true);

    let form_builder: FormBuilder = Arc::new(
        |db: ADb,
         _vec: Vec<std::string::String>,
         data: StrMap,
         tera: ATera,
         csrf: String,
         method: Method| {
            Box::pin(async move {
                let mut form =
                    UserAdminCreateForm::build_with_data(&data, tera, &csrf, method).await;

                let groupes = crate::auth::permissions::groupe::Entity::find()
                    .all(&*db)
                    .await
                    .unwrap_or_default();
                let choices = groupes
                    .into_iter()
                    .map(|g| crate::forms::fields::ChoiceOption::new(&g.id.to_string(), &g.nom))
                    .collect::<Vec<_>>();
                form.get_form_mut().fields.insert(
                    GROUPES.to_string(),
                    Box::new(
                        crate::forms::fields::CheckboxField::new(GROUPES)
                            .choices(choices)
                            .label(t("admin.groups").as_ref()),
                    ),
                );

                Box::new(UserCreateDynWrapper(form)) as Box<dyn DynForm>
            })
        },
    );

    let edit_form_builder: FormBuilder = Arc::new(
        |db: ADb,
         _vec: Vec<std::string::String>,
         data: StrMap,
         tera: ATera,
         csrf: String,
         method: Method| {
            Box::pin(async move {
                let mut form = UserAdminEditForm::build_with_data(&data, tera, &csrf, method).await;

                let groupes = crate::auth::permissions::groupe::Entity::find()
                    .all(&*db)
                    .await
                    .unwrap_or_default();
                let selected = data.get(GROUPES).cloned().unwrap_or_default();
                let choices = groupes
                    .into_iter()
                    .map(|g| {
                        let id_str = g.id.to_string();
                        let mut opt = crate::forms::fields::ChoiceOption::new(&id_str, &g.nom);
                        if selected.split(',').any(|s| s.trim() == id_str) {
                            opt = opt.selected();
                        }
                        opt
                    })
                    .collect::<Vec<_>>();

                let mut field = crate::forms::fields::CheckboxField::new(GROUPES)
                    .choices(choices)
                    .label(t("admin.groups").as_ref());
                {
                    use crate::forms::base::FormField;
                    field.set_value(&selected);
                }

                form.get_form_mut()
                    .fields
                    .insert(GROUPES.to_string(), Box::new(field));

                Box::new(UserEditDynWrapper(form)) as Box<dyn DynForm>
            })
        },
    );

    let list_fn: ListFn = Arc::new(|db: ADb, params: ListParams| {
        Box::pin(async move {
            use sea_orm::{
                QueryFilter, QueryOrder,
                sea_query::{Alias, Expr, Order},
            };
            let mut query = user::Entity::find();
            // The columns shown in the list: any other `sort_by` is ignored.
            const SORT_COLS: &[&str] = &[
                "id",
                "username",
                "email",
                "is_active",
                "is_staff",
                "is_superuser",
                "created_at",
                "updated_at",
                "activated_at",
            ];
            if let Some(ref col) = params.sort_by
                && SORT_COLS.contains(&col.as_str())
            {
                let order = if params.sort_dir == SortDir::Desc {
                    Order::Desc
                } else {
                    Order::Asc
                };
                query = query.order_by(Expr::col(Alias::new(col.as_str())), order);
            }
            // No sidebar filter is declared: a `filter_*` from the query string
            // is ignored rather than turned into a condition on any column.
            if let Some(ref search_str) = params.search {
                let pattern = format!("%{}%", search_str.to_lowercase());
                let mut search_cond = sea_orm::Condition::any();
                let cols = vec!["id", "username", "email"];
                for col in cols {
                    search_cond = search_cond.add(ilike(&db, col, &pattern));
                }
                query = query.filter(search_cond);
            }
            let rows = query
                .offset(params.offset)
                .limit(params.limit)
                .all(&*db)
                .await?;
            Ok(rows
                .into_iter()
                .map(|r| serde_json::to_value(r).unwrap_or(serde_json::Value::Null))
                .collect())
        })
    });

    let count_fn: CountFn = Arc::new(|db: ADb, _search, _column_filters, _scope| {
        Box::pin(async move {
            use sea_orm::QueryFilter;
            let mut query = user::Entity::find();
            if let Some(ref search_str) = _search {
                let pattern = format!("%{}%", search_str.to_lowercase());
                let mut search_cond = sea_orm::Condition::any();
                let cols = vec!["id", "username", "email"];
                for col in cols {
                    search_cond = search_cond.add(ilike(&db, col, &pattern));
                }
                query = query.filter(search_cond);
            }
            query.count(&*db).await
        })
    });

    let get_fn: GetFn = Arc::new(|db: ADb, id: String| {
        Box::pin(async move {
            use crate::auth::permissions::users_groupes;
            use sea_orm::{ColumnTrait, QueryFilter};

            // A malformed id (e.g. not a valid Uuid under `pk-uuid`) is
            // indistinguishable from "no such record" to every caller — treat
            // it as not-found, not a database error (never a 5xx on garbage input).
            let Ok(id) = id.parse::<Pk>() else {
                return Ok(None);
            };
            let row = user::Entity::find_by_id(id).one(&*db).await?;
            let Some(row) = row else { return Ok(None) };

            let mut value = serde_json::to_value(&row).unwrap_or(serde_json::Value::Null);

            let liens: Vec<users_groupes::Model> = users_groupes::Entity::find()
                .filter(users_groupes::Column::UserId.eq(id))
                .all(&*db)
                .await
                .unwrap_or_default();
            let groupes_str = liens
                .iter()
                .map(|l| l.groupe_id.to_string())
                .collect::<Vec<_>>()
                .join(",");
            if let serde_json::Value::Object(ref mut map) = value {
                map.insert(GROUPES.to_string(), serde_json::Value::String(groupes_str));
            }

            Ok(Some(value))
        })
    });

    let delete_fn: DeleteFn = Arc::new(|db: ADb, id: String| {
        Box::pin(async move {
            let id = id
                .parse::<Pk>()
                .map_err(|_| sea_orm::DbErr::Custom(t("admin.builtin.invalid_id").into_owned()))?;
            user::Entity::delete_by_id(id).exec(&*db).await.map(|_| ())
        })
    });

    let create_fn: CreateFn = Arc::new(|db: ADb, data: StrMap| {
        Box::pin(async move {
            use crate::auth::permissions::users_groupes;

            let now = Some(chrono::Utc::now().naive_utc());
            let username = data.get("username").cloned().unwrap_or_default();
            let email = data.get("email").cloned().unwrap_or_default();
            let new_user = user::ActiveModel {
                username: Set(username.clone()),
                email: Set(email.clone()),
                password: Set(data.get("password").cloned().unwrap_or_default()),
                is_active: Set(parse_bool(&data, IS_ACTIVE)),
                is_staff: Set(parse_bool(&data, IS_STAFF)),
                // `is_superuser` is intentionally never read from submitted data here:
                // an admin account must never be grantable from within the admin panel,
                // regardless of who is submitting the form (see UserAdminCreateForm).
                is_superuser: Set(false),
                created_at: Set(now),
                updated_at: Set(now),
                ..Default::default()
            };
            let inserted = new_user.insert(&*db).await.map_err(|e| {
                if super::is_unique_violation(&e) {
                    let msg = e.to_string().to_lowercase();
                    if msg.contains("username") {
                        sea_orm::DbErr::Custom(tf(
                            "admin.builtin.user_username_exists",
                            &[&username],
                        ))
                    } else if msg.contains("email") {
                        sea_orm::DbErr::Custom(tf("admin.builtin.user_email_exists", &[&email]))
                    } else {
                        e
                    }
                } else {
                    e
                }
            })?;

            if let Some(groupes_str) = data.get(GROUPES) {
                for id_str in groupes_str.split(',') {
                    let id_str = id_str.trim();
                    if id_str.is_empty() {
                        continue;
                    }
                    if let Ok(groupe_id) = id_str.parse::<i32>()
                        && let Err(e) = (users_groupes::ActiveModel {
                            user_id: Set(inserted.id),
                            groupe_id: Set(groupe_id),
                        }
                        .insert(&*db)
                        .await)
                    {
                        tracing::warn!(user_id = %inserted.id, groupe_id = %groupe_id, error = %e, "user→group assignment failed (create)");
                    }
                }
            }

            Ok(())
        })
    });

    let update_fn: UpdateFn = Arc::new(|db: ADb, id: String, data: StrMap| {
        Box::pin(async move {
            let id = id
                .parse::<Pk>()
                .map_err(|_| sea_orm::DbErr::Custom(t("admin.builtin.invalid_id").into_owned()))?;
            ensure_activatable(&db, id, parse_bool(&data, IS_ACTIVE)).await?;
            user::ActiveModel {
                id: Set(id),
                username: Set(data.get("username").cloned().unwrap_or_default()),
                email: Set(data.get("email").cloned().unwrap_or_default()),
                is_active: Set(parse_bool(&data, IS_ACTIVE)),
                is_staff: Set(parse_bool(&data, IS_STAFF)),
                // `is_superuser` intentionally left untouched here — see create_fn.
                updated_at: Set(Some(chrono::Utc::now().naive_utc())),
                ..Default::default()
            }
            .update(&*db)
            .await?;

            replace_user_groupes(&db, id, data.get(GROUPES).map_or("", String::as_str)).await
        })
    });

    let partial_update_fn: UpdateFn = Arc::new(|db: ADb, id: String, data: StrMap| {
        Box::pin(async move {
            let id = id
                .parse::<Pk>()
                .map_err(|_| sea_orm::DbErr::Custom(t("admin.builtin.invalid_id").into_owned()))?;
            let mut model = user::ActiveModel {
                id: ::sea_orm::ActiveValue::Unchanged(id),
                updated_at: Set(Some(chrono::Utc::now().naive_utc())),
                ..Default::default()
            };
            if data.contains_key(IS_ACTIVE) {
                ensure_activatable(&db, id, parse_bool(&data, IS_ACTIVE)).await?;
                model.is_active = Set(parse_bool(&data, IS_ACTIVE));
            }
            if data.contains_key(IS_STAFF) {
                model.is_staff = Set(parse_bool(&data, IS_STAFF));
            }
            // `is_superuser` intentionally never applied from bulk/partial updates
            // — see create_fn for the rationale.
            if let Some(v) = data.get("username").filter(|v| !v.is_empty()) {
                model.username = Set(v.clone());
            }
            if let Some(v) = data.get("email").filter(|v| !v.is_empty()) {
                model.email = Set(v.clone());
            }
            model.update(&*db).await?;
            // The edit form always sends `groupes` (empty when every box is
            // unchecked); a bulk update sends it only when the admin picked
            // groups, and leaves memberships alone otherwise.
            if let Some(groupes) = data.get(GROUPES) {
                replace_user_groupes(&db, id, groupes).await?;
            }
            Ok(())
        })
    });

    ResourceEntry::new(meta, form_builder)
        .with_table(sea_orm::EntityName::table_name(&crate::auth::user::Entity))
        .with_edit_form_builder(edit_form_builder)
        .with_list_fn(list_fn)
        .with_count_fn(count_fn)
        .with_get_fn(get_fn)
        .with_delete_fn(delete_fn)
        .with_create_fn(create_fn)
        .with_update_fn(update_fn)
        .with_partial_update_fn(partial_update_fn)
}

struct UserCreateDynWrapper(pub UserAdminCreateForm);
#[async_trait::async_trait]
impl DynForm for UserCreateDynWrapper {
    async fn is_valid(&mut self) -> bool {
        self.0.is_valid().await
    }
    async fn save(&mut self, _db: &crate::utils::aliases::ADb) -> Result<(), sea_orm::DbErr> {
        Ok(())
    }
    fn get_form(&self) -> &crate::forms::form::Forms {
        self.0.get_form()
    }
    fn get_form_mut(&mut self) -> &mut crate::forms::form::Forms {
        self.0.get_form_mut()
    }
}

struct UserEditDynWrapper(pub UserAdminEditForm);
#[async_trait::async_trait]
impl DynForm for UserEditDynWrapper {
    async fn is_valid(&mut self) -> bool {
        self.0.is_valid().await
    }
    async fn save(&mut self, _db: &crate::utils::aliases::ADb) -> Result<(), sea_orm::DbErr> {
        Ok(())
    }
    fn get_form(&self) -> &crate::forms::form::Forms {
        self.0.get_form()
    }
    fn get_form_mut(&mut self) -> &mut crate::forms::form::Forms {
        self.0.get_form_mut()
    }
}