Skip to content

Commit

Permalink
feature: add auth middleware test
Browse files Browse the repository at this point in the history
  • Loading branch information
luffy2025 committed Aug 5, 2024
1 parent b9b210f commit 3cec8b9
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions chat_server/src/middlewares/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,52 @@ pub async fn verify_token(State(state): State<AppState>, req: Request, next: Nex

next.run(req).await
}

#[cfg(test)]
mod tests {
use anyhow::{Ok, Result};
use axum::{
body::Body, extract::Request, http::StatusCode, middleware::from_fn_with_state,
response::IntoResponse, routing::get, Router,
};
use tower::ServiceExt;

use crate::{middlewares::verify_token, AppConfig, AppState, User};

async fn handler(_req: Request) -> impl IntoResponse {
(StatusCode::OK, "ok")
}

#[tokio::test]
async fn verify_token_middleware_should_work() -> Result<()> {
let (_tdb, state) = AppState::new_for_test(AppConfig::load()?).await?;

let user = User::new(1, "test_user", "[email protected]");
let token = state.ek.sign(user)?;

let app = Router::new()
.route("/", get(handler))
.layer(from_fn_with_state(state.clone(), verify_token))
.with_state(state);

let req = Request::builder()
.uri("/")
.header("Authorization", format!("Bearer {}", token))
.body(Body::empty())?;
let res = app.clone().oneshot(req).await?;
assert_eq!(res.status(), StatusCode::OK);

let req = Request::builder().uri("/").body(Body::empty())?;
let res = app.clone().oneshot(req).await?;
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);

let req = Request::builder()
.uri("/")
.header("Authorization", "Bearer bad token")
.body(Body::empty())?;
let res = app.clone().oneshot(req).await?;
assert_eq!(res.status(), StatusCode::FORBIDDEN);

Ok(())
}
}

0 comments on commit 3cec8b9

Please sign in to comment.