90 lines
2.5 KiB
Rust
90 lines
2.5 KiB
Rust
use actix_web::{web, HttpResponse, Responder};
|
|
use sqlx::PgPool;
|
|
|
|
use crate::{
|
|
endpoints::{area::NewOrEditAreaTemplate, IdPath},
|
|
models::{Area, Role, User},
|
|
utils::{ApplicationError, TemplateResponse},
|
|
};
|
|
|
|
#[actix_web::get("/area/edit/{id}")]
|
|
async fn get(
|
|
user: web::ReqData<User>,
|
|
pool: web::Data<PgPool>,
|
|
path: web::Path<IdPath>,
|
|
) -> Result<impl Responder, ApplicationError> {
|
|
if user.role != Role::Admin {
|
|
return Err(ApplicationError::Unauthorized);
|
|
}
|
|
|
|
if let Some(area_in_db) = Area::read_by_id(pool.get_ref(), path.id).await? {
|
|
let template = NewOrEditAreaTemplate {
|
|
user: user.into_inner(),
|
|
area: Some(area_in_db),
|
|
};
|
|
|
|
Ok(template.to_response()?)
|
|
} else {
|
|
Ok(HttpResponse::NotFound().finish())
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use actix_http::StatusCode;
|
|
use brass_macros::db_test;
|
|
|
|
use crate::{
|
|
models::{Function, Role},
|
|
utils::test_helper::{assert_snapshot, read_body, test_get, DbTestContext, RequestConfig},
|
|
};
|
|
|
|
#[db_test]
|
|
async fn produces_template_when_area_exists_and_user_is_admin(context: &DbTestContext) {
|
|
let app = context.app().await;
|
|
|
|
let config = RequestConfig {
|
|
uri: "/area/edit/1".to_string(),
|
|
role: Role::Admin,
|
|
function: Function::Posten,
|
|
user_area: 1,
|
|
};
|
|
let response = test_get(&context.db_pool, app, &config).await;
|
|
|
|
assert_eq!(StatusCode::OK, response.status());
|
|
|
|
let body = read_body(response).await;
|
|
assert_snapshot!(body);
|
|
}
|
|
|
|
#[db_test]
|
|
async fn returns_unauthorized_when_user_is_not_admin(context: &DbTestContext) {
|
|
let app = context.app().await;
|
|
|
|
let config = RequestConfig {
|
|
uri: "/area/edit/1".to_string(),
|
|
role: Role::AreaManager,
|
|
function: Function::Posten,
|
|
user_area: 1,
|
|
};
|
|
let response = test_get(&context.db_pool, app, &config).await;
|
|
|
|
assert_eq!(StatusCode::UNAUTHORIZED, response.status());
|
|
}
|
|
|
|
#[db_test]
|
|
async fn returns_not_found_when_area_does_not_exist(context: &DbTestContext) {
|
|
let app = context.app().await;
|
|
|
|
let config = RequestConfig {
|
|
uri: "/area/edit/2".to_string(),
|
|
role: Role::Admin,
|
|
function: Function::Posten,
|
|
user_area: 1,
|
|
};
|
|
let response = test_get(&context.db_pool, app, &config).await;
|
|
|
|
assert_eq!(StatusCode::NOT_FOUND, response.status());
|
|
}
|
|
}
|