From 28743288cc640c96188d5ad227ae33c6403f9c69 Mon Sep 17 00:00:00 2001 From: Vitor Hideyoshi Nakazone Batista Date: Sat, 9 Mar 2024 23:50:23 -0300 Subject: [PATCH] Fixes Cors Implementation --- Cargo.lock | 8 ++++---- Cargo.toml | 2 +- src/config/config_auth.rs | 2 +- src/config/config_email.rs | 2 +- src/config/config_limits.rs | 2 +- src/config/config_redis.rs | 2 +- src/config/config_server.rs | 16 +++++++++------- src/handler/message.rs | 9 ++++----- src/main.rs | 1 + src/model/send_message.rs | 6 +++--- src/service/auth_service.rs | 2 +- src/utils/router_builder.rs | 17 ++++++++++++----- 12 files changed, 39 insertions(+), 30 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3d13bed..af035d8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -386,10 +386,10 @@ dependencies = [ ] [[package]] -name = "dotenv" -version = "0.15.0" +name = "dotenvy" +version = "0.15.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77c90badedccf4105eca100756a0b1289e191f6fcbdadd3cee1d2f614f97da8f" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" [[package]] name = "email-encoding" @@ -966,7 +966,7 @@ dependencies = [ "axum", "cached", "chrono", - "dotenv", + "dotenvy", "headers", "http 1.0.0", "lettre", diff --git a/Cargo.toml b/Cargo.toml index afd41d7..b30c3b8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,8 +17,8 @@ http = "1.0.0" reqwest = "0.11.24" serde_json = "1.0.114" cached = "0.49.2" -dotenv = "0.15.0" log = "0.4.20" lettre = { version = "0.11.4", default-features = false, features = ["smtp-transport", "tokio1-rustls-tls", "hostname", "builder"] } redis = { version = "0.24.0", features = ["aio", "tokio-comp"] } tower-http = { version = "0.5.2", features = ["cors"] } +dotenvy = "0.15.7" diff --git a/src/config/config_auth.rs b/src/config/config_auth.rs index cfb8666..be889bd 100644 --- a/src/config/config_auth.rs +++ b/src/config/config_auth.rs @@ -8,7 +8,7 @@ pub struct ConfigAuth { #[cached] pub fn get_config_auth() -> ConfigAuth { - dotenv::dotenv().ok(); + dotenvy::dotenv().ok(); let url = env::var("AUTH_URL").expect("AUTH_URL must be set"); diff --git a/src/config/config_email.rs b/src/config/config_email.rs index d5c87d9..6235b67 100644 --- a/src/config/config_email.rs +++ b/src/config/config_email.rs @@ -13,7 +13,7 @@ pub struct ConfigEmail { #[cached] pub fn get_config_email() -> ConfigEmail { - dotenv::dotenv().ok(); + dotenvy::dotenv().ok(); let server = env::var("SMTP_SERVER").expect("SMTP_SERVER must be set"); let port = env::var("SMTP_PORT").expect("SMTP_PORT must be set"); diff --git a/src/config/config_limits.rs b/src/config/config_limits.rs index b2f7014..5d3c8c9 100644 --- a/src/config/config_limits.rs +++ b/src/config/config_limits.rs @@ -9,7 +9,7 @@ pub struct ConfigLimits { #[cached] pub fn get_config_limits() -> ConfigLimits { - dotenv::dotenv().ok(); + dotenvy::dotenv().ok(); let max_requests = env::var("MAX_REQUESTS") .unwrap_or("10".to_string()) diff --git a/src/config/config_redis.rs b/src/config/config_redis.rs index 2c921fb..f1b7f50 100644 --- a/src/config/config_redis.rs +++ b/src/config/config_redis.rs @@ -10,7 +10,7 @@ pub struct ConfigRedis { #[cached] pub fn get_config_redis() -> ConfigRedis { - dotenv::dotenv().ok(); + dotenvy::dotenv().ok(); let url = env::var("REDIS_URL").unwrap_or("localhost".to_string()); let port = env::var("REDIS_PORT").unwrap_or("6379".to_string()); diff --git a/src/config/config_server.rs b/src/config/config_server.rs index 9adda45..2941cc7 100644 --- a/src/config/config_server.rs +++ b/src/config/config_server.rs @@ -1,3 +1,4 @@ +use std::env; use cached::proc_macro::cached; #[derive(Clone)] @@ -9,18 +10,19 @@ pub struct ConfigServer { #[cached] pub fn get_config_server() -> ConfigServer { - dotenv::dotenv().ok(); + dotenvy::dotenv().ok(); - let host = option_env!("HOST").unwrap_or("localhost").to_string(); + let host = env::var("HOST") + .unwrap_or("localhost".to_string()); - let port = option_env!("PORT") - .unwrap_or("8500") + let port = env::var("PORT") + .unwrap_or("8500".to_string()) .parse::() .unwrap(); - let allowed_origins = match option_env!("ALLOWED_ORIGINS") { - Some(origins) => Some(origins.split(",").map(|s| s.to_string()).collect()), - None => None, + let allowed_origins = match env::var("ALLOWED_ORIGINS") { + Ok(origins) => Some(origins.split(',').map(|s| s.to_string()).collect()), + Err(_) => None, }; ConfigServer { diff --git a/src/handler/message.rs b/src/handler/message.rs index 0467309..ce0944b 100644 --- a/src/handler/message.rs +++ b/src/handler/message.rs @@ -8,10 +8,9 @@ pub async fn send_message( Extension(auth_service): Extension, Extension(email_service): Extension, Extension(author): Extension, - Json(payload): Json, + Json(mut payload): Json, ) -> impl IntoResponse { - let mut package = payload.clone(); - package.author = Some(author.clone()).clone(); + payload.author = Some(author.clone()).clone(); if auth_service.has_user_reached_limit(&author).await { return ( @@ -23,7 +22,7 @@ pub async fn send_message( ); } - match email_service.send_email_smtp(package).await { + match email_service.send_email_smtp(payload).await { Ok(_) => {} Err(e) => { return ( @@ -36,7 +35,7 @@ pub async fn send_message( } }; - auth_service.increase_user_request(&author).await; + auth_service.increase_user_request_count(&author).await; return ( StatusCode::OK, diff --git a/src/main.rs b/src/main.rs index e545876..994fe1c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -20,5 +20,6 @@ async fn main() { tokio::net::TcpListener::bind(format!("{}:{}", server_config.host, server_config.port)) .await .unwrap(); + axum::serve(listener, app).await.unwrap(); } diff --git a/src/model/send_message.rs b/src/model/send_message.rs index ff2a214..2b71bea 100644 --- a/src/model/send_message.rs +++ b/src/model/send_message.rs @@ -1,5 +1,5 @@ -use chrono::naive::serde::ts_seconds::deserialize as from_ts; -use chrono::NaiveDateTime; +use chrono::serde::ts_seconds::deserialize as from_ts; +use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use serde_with::serde_as; @@ -20,5 +20,5 @@ pub struct SendMessage { pub message: String, #[serde(deserialize_with = "from_ts")] - pub timestamp: NaiveDateTime, + pub timestamp: DateTime, } diff --git a/src/service/auth_service.rs b/src/service/auth_service.rs index 5efedc1..edf7b4b 100644 --- a/src/service/auth_service.rs +++ b/src/service/auth_service.rs @@ -58,7 +58,7 @@ impl AuthService { return user_requests >= self.max_requests; } - pub async fn increase_user_request(&self, user: &MessageAuthor) -> bool { + pub async fn increase_user_request_count(&self, user: &MessageAuthor) -> bool { let mut con = self.redis.get_async_connection().await.unwrap(); let current_request_key = format!( "user-message:{}:requests:{}", diff --git a/src/utils/router_builder.rs b/src/utils/router_builder.rs index 8699171..9afccef 100644 --- a/src/utils/router_builder.rs +++ b/src/utils/router_builder.rs @@ -1,6 +1,6 @@ use axum::Router; use http::Method; -use tower_http::cors::{AllowOrigin, CorsLayer}; +use tower_http::cors::{AllowHeaders, AllowOrigin, CorsLayer}; pub struct RouterBuilder { router: Router, @@ -18,12 +18,19 @@ impl RouterBuilder { return self; } - pub fn add_cors(&mut self, allowed_origins: Option>) -> &mut Self { + pub fn add_cors(&mut self, origins: Option>) -> &mut Self { + let allowed_origins = origins.map_or(AllowOrigin::any(), |origins| { + AllowOrigin::list(origins.iter().map(|s| s.parse().unwrap())) + }); + let allowed_headers = [ + "content-type".parse().unwrap(), + "authorization".parse().unwrap(), + ]; + let cors = CorsLayer::new() .allow_methods([Method::GET, Method::POST, Method::OPTIONS]) - .allow_origin(allowed_origins.map_or(AllowOrigin::any(), |origins| { - AllowOrigin::list(origins.iter().map(|s| s.parse().unwrap())) - })); + .allow_headers(allowed_headers) + .allow_origin(allowed_origins); self.router = self.router.clone().layer(cors); return self;