42 lines
1.1 KiB
Rust

use actix_web::{web, HttpResponse, Responder};
use sqlx::PgPool;
use crate::{
endpoints::{location::LocationTemplate, IdPath},
utils::{ApplicationError, TemplateResponse},
};
use brass_db::models::{Area, Location, Role, User};
#[actix_web::get("/locations/edit/{id}")]
pub async fn get(
user: web::ReqData<User>,
pool: web::Data<PgPool>,
path: web::Path<IdPath>,
) -> Result<impl Responder, ApplicationError> {
if user.role == Role::AreaManager && user.role == Role::Admin {
return Err(ApplicationError::Unauthorized);
}
let Some(location) = Location::read_by_id(pool.get_ref(), path.id).await? else {
return Ok(HttpResponse::NotFound().finish());
};
if user.role == Role::AreaManager && location.area_id != user.area_id {
return Err(ApplicationError::Unauthorized);
}
let mut areas = None;
if user.role == Role::Admin {
areas = Some(Area::read_all(pool.get_ref()).await?);
}
let template = LocationTemplate {
user: user.into_inner(),
areas,
location: Some(location),
};
Ok(template.to_response()?)
}