backbone_integrations/presentation/http/
integration_event_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::{IntegrationEventService, ServiceError};
26
27use crate::presentation::dto::{CreateIntegrationEventDto, UpdateIntegrationEventDto, PatchIntegrationEventDto, IntegrationEventResponseDto};
29
30
31#[derive(Debug, thiserror::Error)]
33pub enum IntegrationEventError {
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 IntegrationEventError {
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 IntegrationEventError {
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, "INTEGRATIONEVENT_NOT_FOUND"),
64 Self::Validation(_) => (StatusCode::BAD_REQUEST, "INTEGRATIONEVENT_VALIDATION_ERROR"),
65 Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "INTEGRATIONEVENT_DATABASE_ERROR"),
66 Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "INTEGRATIONEVENT_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 create_integration_event_routes(service: Arc<IntegrationEventService>) -> Router {
112 BackboneCrudHandler::<IntegrationEventService, IntegrationEvent, CreateIntegrationEventDto, UpdateIntegrationEventDto, IntegrationEventResponseDto>::routes(
113 service,
114 "/integration_events",
115 )
116}
117
118pub fn create_integration_event_read_routes(service: Arc<IntegrationEventService>) -> Router {
124 BackboneCrudHandler::<IntegrationEventService, IntegrationEvent, CreateIntegrationEventDto, UpdateIntegrationEventDto, IntegrationEventResponseDto>::read_routes(
125 service,
126 "/integration_events",
127 )
128}
129
130pub fn create_integration_event_write_routes(service: Arc<IntegrationEventService>) -> Router {
142 BackboneCrudHandler::<IntegrationEventService, IntegrationEvent, CreateIntegrationEventDto, UpdateIntegrationEventDto, IntegrationEventResponseDto>::write_routes(
143 service,
144 "/integration_events",
145 )
146}
147
148#[cfg(feature = "auth")]
154pub fn create_protected_integration_event_routes<A: AuthMiddleware + Send + Sync + 'static>(
155 service: Arc<IntegrationEventService>,
156 auth: Arc<A>,
157) -> Router {
158 use axum::middleware;
159 use axum::response::IntoResponse;
160
161 let auth_layer = auth.clone();
162 create_integration_event_routes(service)
163 .layer(middleware::from_fn(move |mut req: axum::extract::Request, next: axum::middleware::Next| {
164 let auth = auth_layer.clone();
165 async move {
166 let token = req.headers()
167 .get(axum::http::header::AUTHORIZATION)
168 .and_then(|h| h.to_str().ok())
169 .and_then(|raw| raw.strip_prefix("Bearer ").or_else(|| raw.strip_prefix("bearer ")))
170 .unwrap_or("");
171 match auth.authenticate(token).await {
172 Ok(ctx) => {
173 req.extensions_mut().insert(ctx);
174 next.run(req).await
175 }
176 Err(_) => {
177 (axum::http::StatusCode::UNAUTHORIZED,
178 axum::Json(serde_json::json!({
179 "success": false,
180 "error": "unauthorized",
181 "message": "Authentication required"
182 }))
183 ).into_response()
184 }
185 }
186 }
187 }))
188}