backbone_inventory/presentation/http/
route_rule_handler.rs1use std::collections::HashMap;
8use std::sync::Arc;
9
10use axum::Router;
11use serde::{Deserialize, Serialize};
12use uuid::Uuid;
13
14use backbone_core::http::BackboneCrudHandler;
16
17#[cfg(feature = "auth")]
19use backbone_auth::middleware::AuthContext;
20#[cfg(feature = "auth")]
21use backbone_auth::AuthMiddleware;
22
23use crate::domain::entity::*;
25use crate::application::service::{RouteRuleService, ServiceError};
26
27use crate::presentation::dto::{CreateRouteRuleDto, UpdateRouteRuleDto, PatchRouteRuleDto, RouteRuleResponseDto};
29
30
31#[derive(Debug, thiserror::Error)]
33pub enum RouteRuleError {
34 #[error("Not found: {0}")]
35 NotFound(String),
36 #[error("Validation error: {0}")]
37 Validation(String),
38 #[error("Database error: {0}")]
39 Database(String),
40 #[error("Internal error: {0}")]
41 Internal(String),
42}
43
44impl From<ServiceError> for RouteRuleError {
45 fn from(err: ServiceError) -> Self {
46 match err {
47 ServiceError::NotFound => Self::NotFound(err.to_string()),
48 ServiceError::Validation(ref msg) => Self::Validation(msg.clone()),
49 ServiceError::AlreadyExists(ref msg) => Self::Validation(msg.clone()),
50 ServiceError::Repository(ref e) => Self::Database(e.to_string()),
51 ServiceError::Internal(ref msg) => Self::Internal(msg.clone()),
52 ServiceError::Violations(_) => Self::Validation(err.to_string()),
53 }
54 }
55}
56
57impl axum::response::IntoResponse for RouteRuleError {
58 fn into_response(self) -> axum::response::Response {
59 use axum::http::StatusCode;
60 use axum::Json;
61
62 let (status, code) = match &self {
63 Self::NotFound(_) => (StatusCode::NOT_FOUND, "ROUTERULE_NOT_FOUND"),
64 Self::Validation(_) => (StatusCode::BAD_REQUEST, "ROUTERULE_VALIDATION_ERROR"),
65 Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "ROUTERULE_DATABASE_ERROR"),
66 Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "ROUTERULE_INTERNAL_ERROR"),
67 };
68
69 let body = serde_json::json!({
70 "success": false,
71 "error": code,
72 "message": self.to_string(),
73 });
74
75 (status, Json(body)).into_response()
76 }
77}
78
79pub fn route_rule_permissions() -> backbone_core::http::CrudPermissions {
86 backbone_core::http::CrudPermissions::new("route_rule")
87 .in_module("inventory")
88}
89
90pub fn create_route_rule_routes(service: Arc<RouteRuleService>) -> Router {
119 BackboneCrudHandler::<RouteRuleService, RouteRule, CreateRouteRuleDto, UpdateRouteRuleDto, RouteRuleResponseDto>::routes_guarded(
120 service,
121 "/route_rules",
122 route_rule_permissions(),
123 )
124}
125
126pub fn create_route_rule_read_routes(service: Arc<RouteRuleService>) -> Router {
132 BackboneCrudHandler::<RouteRuleService, RouteRule, CreateRouteRuleDto, UpdateRouteRuleDto, RouteRuleResponseDto>::read_routes_guarded(
133 service,
134 "/route_rules",
135 route_rule_permissions(),
136 )
137}
138
139pub fn create_route_rule_write_routes(service: Arc<RouteRuleService>) -> Router {
151 BackboneCrudHandler::<RouteRuleService, RouteRule, CreateRouteRuleDto, UpdateRouteRuleDto, RouteRuleResponseDto>::write_routes_guarded(
152 service,
153 "/route_rules",
154 route_rule_permissions(),
155 )
156}
157
158#[cfg(feature = "auth")]
164pub fn create_protected_route_rule_routes<A: AuthMiddleware + Send + Sync + 'static>(
165 service: Arc<RouteRuleService>,
166 auth: Arc<A>,
167) -> Router {
168 use axum::middleware;
169 use axum::response::IntoResponse;
170
171 let auth_layer = auth.clone();
172 create_route_rule_routes(service)
173 .layer(middleware::from_fn(move |mut req: axum::extract::Request, next: axum::middleware::Next| {
174 let auth = auth_layer.clone();
175 async move {
176 let token = req.headers()
177 .get(axum::http::header::AUTHORIZATION)
178 .and_then(|h| h.to_str().ok())
179 .and_then(|raw| raw.strip_prefix("Bearer ").or_else(|| raw.strip_prefix("bearer ")))
180 .unwrap_or("");
181 match auth.authenticate(token).await {
182 Ok(ctx) => {
183 req.extensions_mut().insert(ctx);
184 next.run(req).await
185 }
186 Err(_) => {
187 (axum::http::StatusCode::UNAUTHORIZED,
188 axum::Json(serde_json::json!({
189 "success": false,
190 "error": "unauthorized",
191 "message": "Authentication required"
192 }))
193 ).into_response()
194 }
195 }
196 }
197 }))
198}
199