use crate::api::BearerToken;
use crate::core::network_analyzer::{ConnectionType, NetworkInfoProvider};
use crate::security::jwt::JwtManager;
use crate::AppState;
use actix_web::{post, web, HttpResponse, Responder};
use serde::Deserialize;
use std::net::IpAddr;
struct SimpleProvider {
ip: IpAddr,
conn_type: ConnectionType,
}
#[async_trait::async_trait]
impl NetworkInfoProvider for SimpleProvider {
async fn get_connection_type(&self) -> ConnectionType {
self.conn_type.clone()
}
async fn get_public_ip(&self) -> Option<IpAddr> {
Some(self.ip)
}
}
#[derive(Deserialize)]
pub struct NetworkAnalyzeRequest {
pub ip: IpAddr, pub conn_type: ConnectionType, }
#[post("/network/analyze")]
pub async fn analyze_network(
app_data: web::Data<AppState>,
payload: web::Json<NetworkAnalyzeRequest>, bearer: BearerToken,
) -> impl Responder {
let token = bearer.0;
if token.is_empty() {
return HttpResponse::Unauthorized().body("Missing Authorization token");
}
let jwt_manager = JwtManager::new(
&crate::security::secret::SecureString::new(
"a_very_secure_and_long_secret_key_that_is_at_least_32_bytes_long".to_string(),
),
60,
"my_app".to_string(),
"user_service".to_string(),
);
if jwt_manager.decode_token(&token).is_err() {
return HttpResponse::Unauthorized().body("Invalid or expired token");
}
let provider = SimpleProvider {
ip: payload.ip,
conn_type: payload.conn_type.clone(),
};
let engine = &app_data.x_engine.network_engine;
match engine.analyze(&provider).await {
Ok(result) => HttpResponse::Ok().json(result),
Err(e) => HttpResponse::InternalServerError().json(e.to_string()),
}
}