Skip to content

Commit

Permalink
Add X_API_KEY environment variable and with_api_key middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
mukeshkuiry committed May 18, 2024
1 parent 17cda97 commit 9c793ad
Show file tree
Hide file tree
Showing 6 changed files with 42 additions and 3 deletions.
3 changes: 2 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ EMAIL_PASSWORD=my_email_password
EMAIL=my_email
MAIL_NAME=my_name
SMTP_DOMAIN=smtp.gmail.com
SMTP_PORT=587
SMTP_PORT=587
X_API_KEY=my_x_api_key
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ data
.env
.env.local
private_key.pem
.errorviz-version
1 change: 1 addition & 0 deletions compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ services:
MAIL_NAME: ${MAIL_NAME}
SMTP_DOMAIN: ${SMTP_DOMAIN}
SMTP_PORT: ${SMTP_PORT}
X_API_KEY: ${X_API_KEY}
volumes:
- ./src:/app/src

Expand Down
4 changes: 3 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use axum::{extract::State, middleware, routing::get, Router};
use dotenv::dotenv;
use middlewares::res_log::main_response_mapper;
use middlewares::with_api_key::with_api_key;
use mongodb::Client;
use std::error::Error;

Expand Down Expand Up @@ -35,7 +36,8 @@ async fn main() -> Result<(), Box<dyn Error>> {
.merge(routes::user_routes::routes(State(app_state.clone())))
.merge(routes::password_routes::routes(State(app_state.clone())))
.merge(routes::session_routes::routes(State(app_state.clone())))
.layer(middleware::map_response(main_response_mapper));
.layer(middleware::map_response(main_response_mapper))
.route_layer(middleware::from_fn(with_api_key));

let app = Router::new().nest("/api", routes);

Expand Down
3 changes: 2 additions & 1 deletion src/middlewares/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
pub mod res_log;
pub mod res_log;
pub mod with_api_key;
33 changes: 33 additions & 0 deletions src/middlewares/with_api_key.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use axum::{
body::Body,
http::{Request, StatusCode},
middleware::Next,
response::Response,
};
use std::env;

pub async fn with_api_key(req: Request<Body>, next: Next) -> Result<Response, StatusCode> {
println!("Checking for API key...");

let api_key = req
.headers()
.get("x-api-key")
.and_then(|key| key.to_str().ok());

let expected_api_key = env::var("X_API_KEY").expect("X_API_KEY must be set");


if let Some(key) = api_key {
if key == expected_api_key {
return Ok(next.run(req).await);
}
}
// error with message of x-api-key not match

Ok(Response::builder()
.status(StatusCode::UNAUTHORIZED)
.body(Body::from("Invalid API key"))
.unwrap())


}

0 comments on commit 9c793ad

Please sign in to comment.