brass/web/src/endpoints/clothing/get_overview.rs

86 lines
2.5 KiB
Rust

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<Clothing>,
}
#[actix_web::get("/clothing")]
pub async fn get(
user: web::ReqData<User>,
pool: web::Data<PgPool>,
) -> Result<impl Responder, ApplicationError> {
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);
}
}