Fixes Cors Implementation

This commit is contained in:
2024-03-09 23:50:23 -03:00
parent 2876d83274
commit 28743288cc
12 changed files with 39 additions and 30 deletions

8
Cargo.lock generated
View File

@@ -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",

View File

@@ -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"

View File

@@ -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");

View File

@@ -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");

View File

@@ -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())

View File

@@ -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());

View File

@@ -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::<u16>()
.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 {

View File

@@ -8,10 +8,9 @@ pub async fn send_message(
Extension(auth_service): Extension<AuthService>,
Extension(email_service): Extension<EmailService>,
Extension(author): Extension<MessageAuthor>,
Json(payload): Json<SendMessage>,
Json(mut payload): Json<SendMessage>,
) -> 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,

View File

@@ -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();
}

View File

@@ -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<Utc>,
}

View File

@@ -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:{}",

View File

@@ -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<Vec<String>>) -> &mut Self {
pub fn add_cors(&mut self, origins: Option<Vec<String>>) -> &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;