use chrono::{Duration, Local, NaiveDate}; use rocket::{catch, catchers, get, response::Redirect, routes, Build, Rocket, State}; use rocket_dyn_templates::{context, Template}; use sqlx::SqlitePool; use crate::model::{user::User, Day}; mod admin; mod auth; #[get("/")] async fn index(db: &State, user: User) -> Template { let mut days = Vec::new(); for i in 0..6 { let date = (Local::now() + Duration::days(i)).date_naive(); days.push(Day::new(db, date).await); } Template::render("index", context! {loggedin_user: user, days}) } #[catch(401)] //unauthorized fn unauthorized_error() -> Redirect { Redirect::to("/auth") } pub fn start(db: SqlitePool) -> Rocket { rocket::build() .manage(db) .mount("/", routes![index]) .mount("/auth", auth::routes()) .mount("/admin", admin::routes()) .register("/", catchers![unauthorized_error]) .attach(Template::fairing()) } #[cfg(test)] mod test { use crate::testdb; use super::start; use rocket::http::Status; use rocket::local::asynchronous::Client; use rocket::uri; use sqlx::SqlitePool; #[sqlx::test] fn test_not_logged_in() { let pool = testdb!(); let client = Client::tracked(start(pool)) .await .expect("valid rocket instance"); let response = client.get(uri!(super::index)).dispatch().await; assert_eq!(response.status(), Status::SeeOther); let location = response.headers().get("Location").next().unwrap(); assert_eq!(location, "/auth"); } }