Skip to content

Commit

Permalink
auth middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
Micha 'mies' Hernandez van Leuffen authored and hatchan committed Jan 8, 2025
1 parent 2d428a4 commit 4bcb201
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 2 deletions.
15 changes: 13 additions & 2 deletions fpx-workers/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,20 @@ use worker::send::SendFuture;
use worker::*;
use ws::client::WebSocketWorkerClient;
use ws::handlers::{ws_connect, WorkerApiState};
use middleware::auth::auth_middleware;

mod ws;

mod ws;
mod data;
mod middleware;

#[event(start)]
fn start() {
// This code runs in the start event handler for the Worker
// However, .env files are not supported in Cloudflare Workers
// and environment variables should be configured through wrangler.toml
// or the Cloudflare dashboard instead

let fmt_layer = tracing_subscriber::fmt::layer()
.json()
.with_ansi(false) // Only partially supported across JavaScript runtimes
Expand Down Expand Up @@ -53,7 +60,11 @@ async fn fetch(
let boxed_store = Arc::new(store);

let service = service::Service::new(boxed_store.clone(), boxed_events.clone());
let api_router = api::Builder::new().build(service, boxed_store);
let api_router = api::Builder::new()
.build(service, boxed_store)
.route_layer(axum::middleware::from_fn(move |req, next| {
auth_middleware(req, env.as_ref().clone(), next)
}));

let mut router: axum::Router = axum::Router::new()
.route("/api/ws", get(ws_connect))
Expand Down
49 changes: 49 additions & 0 deletions fpx-workers/src/middleware/auth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
use axum::{
body::Body,
http::{Request, StatusCode},
middleware::Next,
response::Response,
};

use tracing::debug;



pub async fn auth_middleware(
request: Request<Body>,
env: worker::Env,
next: Next,
) -> Result<Response, StatusCode> {

let expected_token = env.var("API_TOKEN").map_err(|_| {
debug!("Failed to get API_TOKEN");
StatusCode::INTERNAL_SERVER_ERROR
})?.to_string();

if expected_token.is_empty() {
debug!("API_TOKEN is empty");
return Err(StatusCode::INTERNAL_SERVER_ERROR);
}
debug!("Expected token: {}", expected_token);

let auth_header = request
.headers()
.get("Authorization")
.and_then(|header| header.to_str().ok());



match auth_header {
Some(auth) if auth.starts_with("Bearer ") => {
let token = &auth[7..];
debug!("Received token: {}", token);

if token == expected_token {
Ok(next.run(request).await)
} else {
Err(StatusCode::UNAUTHORIZED)
}
}
_ => Err(StatusCode::UNAUTHORIZED),
}
}
1 change: 1 addition & 0 deletions fpx-workers/src/middleware/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod auth;

0 comments on commit 4bcb201

Please sign in to comment.