use actix_web::{web, Responder}; use askama::Template; use sqlx::PgPool; use crate::utils::{ApplicationError, TemplateResponse}; use brass_db::models::{Clothing, Role, User}; #[derive(Template)] #[cfg_attr(not(test), template(path = "clothing/overview.html"))] #[cfg_attr( test, template(path = "clothing/overview.html", block = "content"), allow(dead_code) )] pub struct ClothingOverviewTemplate { user: User, clothings: Vec, } #[actix_web::get("/clothing")] pub async fn get( user: web::ReqData, pool: web::Data, ) -> Result { if user.role != Role::Admin { return Err(ApplicationError::Unauthorized); } let clothings = Clothing::read_all(pool.get_ref()).await?; let template = ClothingOverviewTemplate { user: user.into_inner(), clothings, }; Ok(template.to_response()?) } #[cfg(test)] mod tests { use crate::utils::test_helper::{ assert_snapshot, create_test_login_user, read_body, test_get, DbTestContext, RequestConfig, StatusCode }; use brass_db::models::{Clothing, Role}; use brass_macros::db_test; #[db_test] async fn user_cant_view_overview(context: &DbTestContext) { let app = context.app().await; let config = RequestConfig::new("/clothing"); create_test_login_user(&context.db_pool, &config).await; let response = test_get(&app, &config).await; assert_eq!(StatusCode::UNAUTHORIZED, response.status()); } #[db_test] async fn area_manager_cant_view_overview(context: &DbTestContext) { let app = context.app().await; let config = RequestConfig::new("/clothing").with_role(Role::AreaManager); create_test_login_user(&context.db_pool, &config).await; let response = test_get(&app, &config).await; assert_eq!(StatusCode::UNAUTHORIZED, response.status()); } #[db_test] async fn produces_template_fine_when_user_is_admin(context: &DbTestContext) { let app = context.app().await; Clothing::create(&context.db_pool, "Schutzkleidung Form 1") .await .unwrap(); let config = RequestConfig::new("/clothing").with_role(Role::Admin); create_test_login_user(&context.db_pool, &config).await; let response = test_get(&app, &config).await; assert_eq!(StatusCode::OK, response.status()); let body = read_body(response).await; assert_snapshot!(body); } }