cot 0.6.0

The Rust web framework for lazy developers.
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
//! Administration panel.
//!
//! This module provides an administration panel for managing models
//! registered in the application, straight from the web interface.

use std::any::Any;
use std::marker::PhantomData;

use async_trait::async_trait;
use bytes::Bytes;
/// Implements the [`AdminModel`] trait for a struct.
///
/// This is a simple method for adding a database model to the admin panel.
/// Note that in order for this derive macro to work, the structure
/// **must** implement [`Model`](crate::db::Model) and
/// [`Form`] traits. These can also be derived using the `#[model]` and
/// `#[derive(Form)]` attributes.
pub use cot_macros::AdminModel;
use derive_more::Debug;
use serde::Deserialize;

use crate::auth::Auth;
use crate::common_types::Password;
use crate::error::NotFound;
use crate::form::{
    Form, FormContext, FormErrorTarget, FormField, FormFieldValidationError, FormResult,
};
use crate::html::Html;
use crate::request::extractors::{FromRequestHead, Path, StaticFiles, UrlQuery};
use crate::request::{Request, RequestExt, RequestHead};
use crate::response::{IntoResponse, Response};
use crate::router::{Router, Urls};
use crate::static_files::StaticFile;
use crate::{App, Error, Method, RequestHandler, Template, reverse_redirect};

struct AdminAuthenticated<T, H: Send + Sync>(H, PhantomData<fn() -> T>);

impl<T, H: RequestHandler<T> + Send + Sync> AdminAuthenticated<T, H> {
    #[must_use]
    fn new(handler: H) -> Self {
        Self(handler, PhantomData)
    }
}

impl<T, H: RequestHandler<T> + Send + Sync> RequestHandler<T> for AdminAuthenticated<T, H> {
    async fn handle(&self, mut request: Request) -> crate::Result<Response> {
        let auth: Auth = request.extract_from_head().await?;
        if !auth.user().is_authenticated() {
            return Ok(reverse_redirect!(request, "login")?);
        }

        self.0.handle(request).await
    }
}

#[derive(Debug, FromRequestHead)]
struct BaseContext {
    urls: Urls,
    static_files: StaticFiles,
}

async fn index(
    base_context: BaseContext,
    AdminModelManagers(managers): AdminModelManagers,
) -> crate::Result<Html> {
    #[derive(Debug, Template)]
    #[template(path = "admin/model_list.html")]
    struct ModelListTemplate<'a> {
        ctx: &'a BaseContext,
        #[debug("..")]
        model_managers: Vec<Box<dyn AdminModelManager>>,
    }

    let template = ModelListTemplate {
        ctx: &base_context,
        model_managers: managers,
    };
    Ok(Html::new(template.render()?))
}

#[derive(Debug, Form)]
struct LoginForm {
    username: String,
    password: Password,
}

async fn login(
    base_context: BaseContext,
    auth: Auth,
    mut request: Request,
) -> crate::Result<Response> {
    #[derive(Debug, Template)]
    #[template(path = "admin/login.html")]
    struct LoginTemplate<'a> {
        ctx: &'a BaseContext,
        form: <LoginForm as Form>::Context,
    }

    let login_form_context = if request.method() == Method::GET {
        LoginForm::build_context(&mut request).await?
    } else if request.method() == Method::POST {
        let login_form = LoginForm::from_request(&mut request).await?;
        match login_form {
            FormResult::Ok(login_form) => {
                if authenticate(&auth, login_form).await? {
                    return Ok(reverse_redirect!(base_context.urls, "index")?);
                }

                let mut context = LoginForm::build_context(&mut request).await?;
                context.add_error(
                    FormErrorTarget::Form,
                    FormFieldValidationError::from_static("Invalid username or password"),
                );
                context
            }
            FormResult::ValidationError(context) => context,
        }
    } else {
        panic!("Unexpected request method");
    };

    let template = LoginTemplate {
        ctx: &base_context,
        form: login_form_context,
    };
    Html::new(template.render()?).into_response()
}

async fn authenticate(auth: &Auth, login_form: LoginForm) -> crate::Result<bool> {
    #[cfg(feature = "db")]
    let user = auth
        .authenticate(&crate::auth::db::DatabaseUserCredentials::new(
            login_form.username,
            Password::new(login_form.password.into_string()),
        ))
        .await?;

    #[cfg(not(feature = "db"))]
    let user: Option<Box<dyn crate::auth::User + Send + Sync>> = None;

    if let Some(user) = user {
        auth.login(user).await?;
        Ok(true)
    } else {
        Ok(false)
    }
}

/// Struct representing the pagination of objects.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Pagination {
    limit: u64,
    offset: u64,
}

impl Pagination {
    fn new(limit: u64, page: u64) -> Self {
        assert!(page > 0, "Page number must be greater than 0");

        Self {
            limit,
            offset: (page - 1) * limit,
        }
    }

    /// Returns the limit of objects per page.
    #[must_use]
    pub fn limit(&self) -> u64 {
        self.limit
    }

    /// Returns the offset of objects.
    #[must_use]
    pub fn offset(&self) -> u64 {
        self.offset
    }
}

#[derive(Debug, Deserialize)]
struct PaginationParams {
    page: Option<u64>,
    page_size: Option<u64>,
}

async fn view_model(
    base_context: BaseContext,
    managers: AdminModelManagers,
    Path(model_name): Path<String>,
    UrlQuery(pagination_params): UrlQuery<PaginationParams>,
    request: Request,
) -> crate::Result<Response> {
    #[derive(Debug, Template)]
    #[template(path = "admin/model.html")]
    struct ModelTemplate<'a> {
        ctx: &'a BaseContext,
        #[debug("..")]
        model: &'a dyn AdminModelManager,
        #[debug("..")]
        objects: Vec<Box<dyn AdminModel>>,
        page: u64,
        page_size: &'a u64,
        total_object_counts: u64,
        total_pages: u64,
    }

    const DEFAULT_PAGE_SIZE: u64 = 10;

    let manager = get_manager(managers, &model_name)?;

    let page = pagination_params.page.unwrap_or(1);
    let page_size = pagination_params.page_size.unwrap_or(DEFAULT_PAGE_SIZE);

    let total_object_counts = manager.get_total_object_counts(&request).await?;
    let total_pages = total_object_counts.div_ceil(page_size);

    if (page == 0 || page > total_pages) && total_pages > 0 {
        return Err(Error::from(NotFound::with_message(format!(
            "page {page} not found"
        ))));
    }

    let pagination = Pagination::new(page_size, page);

    let objects = manager.get_objects(&request, pagination).await?;

    let template = ModelTemplate {
        ctx: &base_context,
        model: &*manager,
        objects,
        page,
        page_size: &page_size,
        total_object_counts,
        total_pages,
    };

    Html::new(template.render()?).into_response()
}

async fn create_model_instance(
    base_context: BaseContext,
    managers: AdminModelManagers,
    Path(model_name): Path<String>,
    request: Request,
) -> cot::Result<Response> {
    edit_model_instance_impl(base_context, managers, request, &model_name, None).await
}

async fn edit_model_instance(
    base_context: BaseContext,
    managers: AdminModelManagers,
    Path((model_name, object_id)): Path<(String, String)>,
    request: Request,
) -> cot::Result<Response> {
    edit_model_instance_impl(
        base_context,
        managers,
        request,
        &model_name,
        Some(&object_id),
    )
    .await
}

async fn edit_model_instance_impl(
    base_context: BaseContext,
    managers: AdminModelManagers,
    mut request: Request,
    model_name: &str,
    object_id: Option<&str>,
) -> cot::Result<Response> {
    #[derive(Debug, Template)]
    #[template(path = "admin/model_edit.html")]
    struct ModelEditTemplate<'a> {
        ctx: &'a BaseContext,
        #[debug("..")]
        model: &'a dyn AdminModelManager,
        form_context: Box<dyn FormContext>,
        is_edit: bool,
    }

    let manager = get_manager(managers, model_name)?;

    let form_context = if request.method() == Method::POST {
        let form_context = manager.save_from_request(&mut request, object_id).await?;

        if let Some(form_context) = form_context {
            form_context
        } else {
            return Ok(reverse_redirect!(
                base_context.urls,
                "view_model",
                model_name = manager.url_name()
            )?);
        }
    } else if let Some(object_id) = object_id {
        let object = get_object(&mut request, &*manager, object_id).await?;

        manager.form_context_from_object(object).await
    } else {
        manager.form_context()
    };

    let template = ModelEditTemplate {
        ctx: &base_context,
        model: &*manager,
        form_context,
        is_edit: object_id.is_some(),
    };

    Html::new(template.render()?).into_response()
}

async fn remove_model_instance(
    base_context: BaseContext,
    managers: AdminModelManagers,
    Path((model_name, object_id)): Path<(String, String)>,
    mut request: Request,
) -> cot::Result<Response> {
    #[derive(Debug, Template)]
    #[template(path = "admin/model_remove.html")]
    struct ModelRemoveTemplate<'a> {
        ctx: &'a BaseContext,
        #[debug("..")]
        model: &'a dyn AdminModelManager,
        #[debug("..")]
        object: &'a dyn AdminModel,
    }

    let manager = get_manager(managers, &model_name)?;
    let object = get_object(&mut request, &*manager, &object_id).await?;

    if request.method() == Method::POST {
        manager.remove_by_id(&mut request, &object_id).await?;

        Ok(reverse_redirect!(
            base_context.urls,
            "view_model",
            model_name = manager.url_name()
        )?)
    } else {
        let template = ModelRemoveTemplate {
            ctx: &base_context,
            model: &*manager,
            object: &*object,
        };

        Html::new(template.render()?).into_response()
    }
}

async fn get_object(
    request: &mut Request,
    manager: &dyn AdminModelManager,
    object_id: &str,
) -> Result<Box<dyn AdminModel>, Error> {
    manager
        .get_object_by_id(request, object_id)
        .await?
        .ok_or_else(|| {
            Error::from(NotFound::with_message(format!(
                "Object with ID `{}` not found in model `{}`",
                object_id,
                manager.name()
            )))
        })
}

fn get_manager(
    AdminModelManagers(model_managers): AdminModelManagers,
    model_name: &str,
) -> cot::Result<Box<dyn AdminModelManager>> {
    model_managers
        .into_iter()
        .find(|manager| manager.url_name() == model_name)
        .ok_or_else(|| {
            Error::from(NotFound::with_message(format!(
                "Model `{model_name}` not found"
            )))
        })
}

#[repr(transparent)]
struct AdminModelManagers(Vec<Box<dyn AdminModelManager>>);

impl FromRequestHead for AdminModelManagers {
    async fn from_request_head(head: &RequestHead) -> cot::Result<Self> {
        let managers = head
            .context()
            .apps()
            .iter()
            .flat_map(|app| app.admin_model_managers())
            .collect();
        Ok(Self(managers))
    }
}

/// A trait for adding admin models to the app.
///
/// This exposes an API over [`AdminModel`] that is dyn-compatible and
/// hence can be dynamically added to the project.
///
/// See [`DefaultAdminModelManager`] for an automatic implementation of this
/// trait.
#[async_trait]
pub trait AdminModelManager: Send + Sync {
    /// Returns the display name of the model.
    fn name(&self) -> &str;

    /// Returns the URL slug for the model.
    fn url_name(&self) -> &str;

    /// Returns the list of objects of this model.
    async fn get_objects(
        &self,
        request: &Request,
        pagination: Pagination,
    ) -> cot::Result<Vec<Box<dyn AdminModel>>>;

    /// Returns the total count of objects of this model.
    async fn get_total_object_counts(&self, request: &Request) -> cot::Result<u64>;

    /// Returns the object with the given ID.
    async fn get_object_by_id(
        &self,
        request: &Request,
        id: &str,
    ) -> cot::Result<Option<Box<dyn AdminModel>>>;

    /// Returns an empty form context for this model.
    fn form_context(&self) -> Box<dyn FormContext>;

    /// Returns a form context pre-filled with the data from given object.
    ///
    /// It is guaranteed that `object` parameter is an object returned by either
    /// [`Self::get_objects`] or [`Self::get_object_by_id`] methods. This means
    /// that if you always return the same object type from these methods,
    /// you can safely downcast the object to the same type in this method
    /// as well.
    async fn form_context_from_object(&self, object: Box<dyn AdminModel>) -> Box<dyn FormContext>;

    /// Saves the object by using the form data from given request.
    ///
    /// # Errors
    ///
    /// Returns an error if the object could not be saved, for instance
    /// due to a database error.
    async fn save_from_request(
        &self,
        request: &mut Request,
        object_id: Option<&str>,
    ) -> cot::Result<Option<Box<dyn FormContext>>>;

    /// Removes the object with the given ID.
    ///
    /// # Errors
    ///
    /// Returns an error if the object with the given ID does not exist.
    ///
    /// Returns an error if the object could not be removed, for example,
    /// a database error.
    async fn remove_by_id(&self, request: &mut Request, object_id: &str) -> cot::Result<()>;
}

/// A default implementation of [`AdminModelManager`] for an [`AdminModel`].
#[derive(Debug)]
pub struct DefaultAdminModelManager<T> {
    phantom_data: PhantomData<T>,
}

impl<T> Default for DefaultAdminModelManager<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T> DefaultAdminModelManager<T> {
    /// Creates a new instance of the default admin model manager.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            phantom_data: PhantomData,
        }
    }
}

#[async_trait]
impl<T: AdminModel + Send + Sync + 'static> AdminModelManager for DefaultAdminModelManager<T> {
    fn name(&self) -> &str {
        T::name()
    }

    fn url_name(&self) -> &str {
        T::url_name()
    }

    async fn get_total_object_counts(&self, request: &Request) -> cot::Result<u64> {
        T::get_total_object_counts(request).await
    }

    async fn get_objects(
        &self,
        request: &Request,
        pagination: Pagination,
    ) -> cot::Result<Vec<Box<dyn AdminModel>>> {
        #[expect(trivial_casts)] // Upcast to the correct Box type
        T::get_objects(request, pagination).await.map(|objects| {
            objects
                .into_iter()
                .map(|object| Box::new(object) as Box<dyn AdminModel>)
                .collect()
        })
    }

    async fn get_object_by_id(
        &self,
        request: &Request,
        id: &str,
    ) -> cot::Result<Option<Box<dyn AdminModel>>> {
        #[expect(trivial_casts)] // Upcast to the correct Box type
        T::get_object_by_id(request, id)
            .await
            .map(|object| object.map(|object| Box::new(object) as Box<dyn AdminModel>))
    }

    fn form_context(&self) -> Box<dyn FormContext> {
        T::form_context()
    }

    async fn form_context_from_object(&self, object: Box<dyn AdminModel>) -> Box<dyn FormContext> {
        let object_any: &dyn Any = &*object;
        let object_casted = object_any.downcast_ref::<T>().expect("Invalid object type");

        T::form_context_from_self(object_casted).await
    }

    async fn save_from_request(
        &self,
        request: &mut Request,
        object_id: Option<&str>,
    ) -> cot::Result<Option<Box<dyn FormContext>>> {
        T::save_from_request(request, object_id).await
    }

    async fn remove_by_id(&self, request: &mut Request, object_id: &str) -> cot::Result<()> {
        T::remove_by_id(request, object_id).await
    }
}

/// A model that can be managed by the admin panel.
#[async_trait]
#[diagnostic::on_unimplemented(
    message = "`{Self}` does not implement the `AdminModel` trait",
    label = "`{Self}` is not an admin model",
    note = "add #[derive(cot::admin::AdminModel)] to the struct to automatically derive the trait"
)]
pub trait AdminModel: Any + Send + 'static {
    /// Get the objects of this model.
    async fn get_objects(request: &Request, pagination: Pagination) -> cot::Result<Vec<Self>>
    where
        Self: Sized;

    /// Get the total count of objects of this model.
    async fn get_total_object_counts(request: &Request) -> cot::Result<u64>
    where
        Self: Sized;

    /// Returns the object with the given ID.
    async fn get_object_by_id(request: &Request, id: &str) -> cot::Result<Option<Self>>
    where
        Self: Sized;

    /// Get the display name of this model.
    fn name() -> &'static str
    where
        Self: Sized;

    /// Get the URL slug for this model.
    fn url_name() -> &'static str
    where
        Self: Sized;

    /// Get the ID of this model instance as a [`String`].
    fn id(&self) -> String;

    /// Get the display text of this model instance.
    fn display(&self) -> String;

    /// Get the form context for this model.
    fn form_context() -> Box<dyn FormContext>
    where
        Self: Sized;

    /// Get the form context with the data pre-filled from this model instance.
    async fn form_context_from_self(&self) -> Box<dyn FormContext>;

    /// Save the model instance from the form data in the request.
    ///
    /// # Errors
    ///
    /// Returns an error if the object could not be saved, for example,
    /// a database error.
    async fn save_from_request(
        request: &mut Request,
        object_id: Option<&str>,
    ) -> cot::Result<Option<Box<dyn FormContext>>>
    where
        Self: Sized;

    /// Remove the model instance with the given ID.
    ///
    /// # Errors
    ///
    /// Returns an error if the object with the given ID does not exist.
    ///
    /// Returns an error if the object could not be removed, for example,
    /// a database error.
    async fn remove_by_id(request: &mut Request, object_id: &str) -> cot::Result<()>
    where
        Self: Sized;
}

/// The admin app.
///
/// # Examples
///
/// ```
/// use cot::admin::AdminApp;
/// use cot::project::RegisterAppsContext;
/// use cot::{AppBuilder, Project};
///
/// struct MyProject;
/// impl Project for MyProject {
///     fn register_apps(&self, apps: &mut AppBuilder, _context: &RegisterAppsContext) {
///         apps.register_with_views(AdminApp::new(), "/admin");
///     }
/// }
/// ```
#[derive(Debug, Copy, Clone)]
pub struct AdminApp;

impl Default for AdminApp {
    fn default() -> Self {
        Self::new()
    }
}

impl AdminApp {
    /// Creates an admin app instance.
    ///
    /// # Examples
    ///
    /// ```
    /// use cot::admin::AdminApp;
    /// use cot::project::RegisterAppsContext;
    /// use cot::{AppBuilder, Project};
    ///
    /// struct MyProject;
    /// impl Project for MyProject {
    ///     fn register_apps(&self, apps: &mut AppBuilder, _context: &RegisterAppsContext) {
    ///         apps.register_with_views(AdminApp::new(), "/admin");
    ///     }
    /// }
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {}
    }
}

impl App for AdminApp {
    fn name(&self) -> &'static str {
        "cot_admin"
    }

    fn router(&self) -> Router {
        Router::with_urls([
            crate::router::Route::with_handler_and_name(
                "/",
                AdminAuthenticated::new(index),
                "index",
            ),
            crate::router::Route::with_handler_and_name("/login/", login, "login"),
            crate::router::Route::with_handler_and_name(
                "/{model_name}/",
                AdminAuthenticated::new(view_model),
                "view_model",
            ),
            crate::router::Route::with_handler_and_name(
                "/{model_name}/create/",
                AdminAuthenticated::new(create_model_instance),
                "create_model_instance",
            ),
            crate::router::Route::with_handler_and_name(
                "/{model_name}/{pk}/edit/",
                AdminAuthenticated::new(edit_model_instance),
                "edit_model_instance",
            ),
            crate::router::Route::with_handler_and_name(
                "/{model_name}/{pk}/remove/",
                AdminAuthenticated::new(remove_model_instance),
                "remove_model_instance",
            ),
        ])
    }

    fn static_files(&self) -> Vec<StaticFile> {
        vec![StaticFile::new(
            "admin/admin.css",
            Bytes::from_static(include_bytes!(concat!(
                env!("OUT_DIR"),
                "/static/admin/admin.css"
            ))),
        )]
    }
}