Initial Implementation of AuthService

This commit is contained in:
2024-02-25 02:10:43 -03:00
parent 05dc487099
commit 11f01a6156
8 changed files with 75 additions and 37 deletions

1
Cargo.lock generated
View File

@@ -851,6 +851,7 @@ dependencies = [
"dotenv", "dotenv",
"headers", "headers",
"http 1.0.0", "http 1.0.0",
"log",
"reqwest", "reqwest",
"serde", "serde",
"serde_json", "serde_json",

View File

@@ -18,3 +18,4 @@ reqwest = "0.11.24"
serde_json = "1.0.114" serde_json = "1.0.114"
cached = "0.49.2" cached = "0.49.2"
dotenv = "0.15.0" dotenv = "0.15.0"
log = "0.4.20"

View File

@@ -3,6 +3,7 @@ mod middleware;
mod model; mod model;
mod route; mod route;
mod config; mod config;
mod service;
use crate::config::config_server; use crate::config::config_server;

View File

@@ -1,19 +1,12 @@
use axum::{ use axum::{response::Response, middleware::Next, extract::Request, http::StatusCode, Extension};
response::Response, use crate::service::auth_service::AuthService;
middleware::Next,
extract::Request,
http::StatusCode,
};
use reqwest::header::AUTHORIZATION;
use crate::model::send_message::MessageAuthor;
use crate::config::config_auth;
pub async fn auth_middleware(mut request: Request, next: Next) -> Result<Response, StatusCode> {
pub async fn auth_middleware(Extension(auth_service): Extension<AuthService>, mut request: Request, next: Next) -> Result<Response, StatusCode> {
let token = get_token(&request).ok_or(StatusCode::UNAUTHORIZED)?; let token = get_token(&request).ok_or(StatusCode::UNAUTHORIZED)?;
return match validate_token(&token).await { return match auth_service.validate_token(&token).await {
Some(author) => { Some(author) => {
println!("Author: {:?}", author);
request.extensions_mut().insert(author); request.extensions_mut().insert(author);
Ok(next.run(request).await) Ok(next.run(request).await)
}, },
@@ -26,24 +19,4 @@ fn get_token(req: &Request) -> Option<String> {
.get(http::header::AUTHORIZATION) .get(http::header::AUTHORIZATION)
.and_then(|header| header.to_str().ok()) .and_then(|header| header.to_str().ok())
.map(|header| header.replace("Bearer ", "")) .map(|header| header.replace("Bearer ", ""))
}
async fn validate_token(token: &str) -> Option<MessageAuthor> {
println!("Received token: {}", token);
let auth_config = config_auth::get_config_auth();
let validation_url = format!("{}/user/login/validate", auth_config.auth_url);
let client = reqwest::Client::new();
let response = client.post(validation_url.as_str())
.header(AUTHORIZATION, format!("Bearer {}", token))
.send().await.unwrap();
if response.status().is_success() {
let text = response.text().await.unwrap();
return serde_json::from_str(&text).unwrap();
}
None
} }

View File

@@ -1,12 +1,29 @@
use crate::handler::health::health_check; use crate::handler::health::health_check;
use crate::handler::message::send_message; use crate::handler::message::send_message;
use axum::{routing::{get, post}, Router, middleware}; use axum::{routing::{get, post}, Router, middleware, Extension};
use crate::config::config_auth;
use crate::middleware::auth_middleware::auth_middleware; use crate::middleware::auth_middleware::auth_middleware;
use crate::service::auth_service::AuthService;
use crate::service::email_service::EmailService;
fn configure_message_endpoint(router: Router) -> Router {
router.route("/message", post(send_message))
.layer(middleware::from_fn(auth_middleware))
.layer(Extension(AuthService::new(config_auth::get_config_auth())))
.layer(Extension(EmailService::new()))
}
fn configure_health_endpoint(router: Router) -> Router {
router.route("/health", get(health_check))
}
pub fn create_route() -> Router { pub fn create_route() -> Router {
Router::new() let mut router = Router::new();
.route("/message", post(send_message))
.layer(middleware::from_fn(auth_middleware)) router = configure_message_endpoint(router);
.route("/health", get(health_check)) router = configure_health_endpoint(router);
router
} }

View File

@@ -0,0 +1,35 @@
use reqwest::header::AUTHORIZATION;
use crate::config::config_auth::ConfigAuth;
use crate::model::send_message::MessageAuthor;
#[derive(Clone)]
pub struct AuthService {
auth_url: String,
}
impl AuthService {
pub fn new(config_auth: ConfigAuth) -> Self {
AuthService {
auth_url: config_auth.auth_url,
}
}
pub async fn validate_token(&self, token: &str) -> Option<MessageAuthor> {
println!("Received token: {}", token);
let validation_url = format!("{}/user/login/validate", self.auth_url);
let client = reqwest::Client::new();
let response = client.post(validation_url.as_str())
.header(AUTHORIZATION, format!("Bearer {}", token))
.send().await.unwrap();
if response.status().is_success() {
let text = response.text().await.unwrap();
return serde_json::from_str(&text).unwrap();
}
None
}
}

View File

@@ -0,0 +1,8 @@
#[derive(Clone)]
pub struct EmailService {}
impl EmailService {
pub fn new() -> Self {
EmailService {}
}
}

2
src/service/mod.rs Normal file
View File

@@ -0,0 +1,2 @@
pub mod auth_service;
pub mod email_service;