rowt/src/rest/mod.rs

52 lines
1.3 KiB
Rust
Raw Normal View History

2023-04-03 22:03:45 +02:00
use rocket::{catch, catchers, get, response::Redirect, routes, Build, Rocket};
2023-04-03 16:11:26 +02:00
use rocket_dyn_templates::{context, Template};
use sqlx::SqlitePool;
2023-04-03 22:03:45 +02:00
use crate::model::user::User;
2023-04-03 16:11:26 +02:00
mod auth;
2023-03-26 14:40:56 +02:00
#[get("/")]
fn index(user: User) -> Template {
Template::render("index", context! {loggedin_user: user})
2023-03-26 14:40:56 +02:00
}
2023-04-03 22:03:45 +02:00
#[catch(401)] //unauthorized
fn unauthorized_error() -> Redirect {
Redirect::to("/auth")
}
2023-04-03 16:11:26 +02:00
pub fn start(db: SqlitePool) -> Rocket<Build> {
2023-03-26 16:58:45 +02:00
rocket::build()
2023-04-03 16:11:26 +02:00
.manage(db)
2023-03-26 16:58:45 +02:00
.mount("/", routes![index])
2023-04-03 16:11:26 +02:00
.mount("/auth", auth::routes())
2023-04-03 22:03:45 +02:00
.register("/", catchers![unauthorized_error])
2023-03-26 16:58:45 +02:00
.attach(Template::fairing())
2023-03-26 14:40:56 +02:00
}
2023-04-03 22:03:45 +02:00
#[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");
}
}