brass/web/src/endpoints/area/post_new.rs
2025-02-06 23:01:38 +01:00

86 lines
2.2 KiB
Rust

use actix_web::{http::header::LOCATION, web, HttpResponse, Responder};
use sqlx::PgPool;
use crate::{
endpoints::area::AreaForm,
models::{Area, Role, User},
utils::ApplicationError,
};
#[actix_web::post("/area/new")]
pub async fn post(
user: web::ReqData<User>,
pool: web::Data<PgPool>,
form: web::Form<AreaForm>,
) -> Result<impl Responder, ApplicationError> {
if user.role != Role::Admin {
return Err(ApplicationError::Unauthorized);
}
Area::create(pool.get_ref(), &form.name).await?;
Ok(HttpResponse::Found()
.insert_header((LOCATION, "/locations"))
.insert_header(("HX-LOCATION", "/locations"))
.finish())
}
#[cfg(test)]
mod tests {
use actix_http::StatusCode;
use brass_macros::db_test;
use crate::{
endpoints::area::AreaForm,
models::{Area, Function, Role},
utils::test_helper::{test_post, DbTestContext, RequestConfig},
};
#[db_test]
async fn updates_area_when_user_is_admin_and_area_exists(context: &DbTestContext) {
let app = context.app().await;
let config = RequestConfig {
uri: "/area/new".to_string(),
role: Role::Admin,
function: Function::Posten,
user_area: 1,
};
let request = AreaForm {
name: "Neuer Name".to_string(),
};
let response = test_post(&context.db_pool, app, &config, request).await;
assert_eq!(StatusCode::FOUND, response.status());
let updated_area = Area::read_by_id(&context.db_pool, 2)
.await
.unwrap()
.unwrap();
assert_eq!("Neuer Name".to_string(), updated_area.name);
}
#[db_test]
async fn returns_unauthorized_when_user_is_not_admin(context: &DbTestContext) {
let app = context.app().await;
let config = RequestConfig {
uri: "/area/new".to_string(),
role: Role::AreaManager,
function: Function::Posten,
user_area: 1,
};
let request = AreaForm {
name: "Neuer Name".to_string(),
};
let response = test_post(&context.db_pool, app, &config, request).await;
assert_eq!(StatusCode::UNAUTHORIZED, response.status());
}
}