Skip to content

Commit

Permalink
[datalayer] add image auth
Browse files Browse the repository at this point in the history
  • Loading branch information
kylestang committed Jul 30, 2024
1 parent 9ade3d0 commit 3c77376
Show file tree
Hide file tree
Showing 6 changed files with 236 additions and 12 deletions.
169 changes: 165 additions & 4 deletions apps/data/datalayer/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions apps/data/datalayer/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ tokio = { version = "1.38.0", features = ["full"] }
tower = "0.4.13"
tower-http = { version = "0.5.2", features = ["catch-panic"] }
uuid = { version = "1.9.1", features = ["v4"] }
jsonwebtoken = "9.3.0"
axum-extra = { version = "0.9.3", features = ["cookie"] }

[dev-dependencies]
rstest = "0.21.0"
4 changes: 4 additions & 0 deletions apps/data/datalayer/src/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use axum::{
body::Bytes,
extract::{DefaultBodyLimit, Path},
http::StatusCode,
middleware,
response::IntoResponse,
routing::{get, post},
Json, Router,
Expand All @@ -14,6 +15,8 @@ use std::{
use tower_http::catch_panic::CatchPanicLayer;
use uuid::Uuid;

use crate::jwt;

#[derive(Serialize)]
struct CreateImageResponse {
url: String,
Expand All @@ -24,6 +27,7 @@ pub fn image_router() -> Router {
.route("/api/images", post(upload_image_handler))
.layer(DefaultBodyLimit::disable())
.route("/api/images/:id", get(get_image_handler))
.layer(middleware::from_fn(jwt::jwt_middlewware))
.layer(CatchPanicLayer::new())
}

Expand Down
53 changes: 53 additions & 0 deletions apps/data/datalayer/src/jwt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
use std::env;

use axum::{body::Body, extract::Request, middleware::Next, response::Response};
use axum_extra::extract::CookieJar;
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Claims {
user_id: u32,
}

pub fn jwt_key() -> String {
env::var("JWT_PUBLIC_KEY").expect("JWT_PUBLIC_KEY env var not set")
}

pub async fn jwt_middlewware(request: Request, next: Next) -> Response {
let key = match DecodingKey::from_rsa_pem(jwt_key().as_bytes()) {
Err(e) => {
println!("{:?}", e);
return Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(Body::empty())
.unwrap();
}
Ok(k) => k,
};

let cookies = CookieJar::from_headers(request.headers());

let jwt = match cookies.get("authorization") {
None => {
return Response::builder()
.status(StatusCode::UNAUTHORIZED)
.body(Body::empty())
.unwrap()
}
Some(s) => s.value(),
};

match decode::<Claims>(jwt, &key, &Validation::new(Algorithm::RS256)) {
Err(e) => {
println!("{:?}", e);
Response::builder()
.status(StatusCode::UNAUTHORIZED)
.body(Body::empty())
.unwrap()
}
Ok(_) => next.run(request).await,
}
}
3 changes: 3 additions & 0 deletions apps/data/datalayer/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,19 @@ use std::future::IntoFuture;
use elastic::{elastic_endpoint, elastic_router};
use email::{email_endpoint, email_router};
use image::image_router;
use jwt::jwt_key;

mod elastic;
mod email;
mod image;
mod jwt;

#[tokio::main]
async fn main() {
// Check that the env vars are set
elastic_endpoint();
email_endpoint();
jwt_key();

let elastic_listener = tokio::net::TcpListener::bind("0.0.0.0:8301").await.unwrap();
let email_listener = tokio::net::TcpListener::bind("0.0.0.0:8302").await.unwrap();
Expand Down
Loading

0 comments on commit 3c77376

Please sign in to comment.