Browse Source

Response with statuscode

master
Julio Biason 2 years ago
parent
commit
53fc5a7438
  1. 11
      axumtest/src/auth/mod.rs
  2. 48
      axumtest/src/entities/mod.rs
  3. 25
      axumtest/src/main.rs

11
axumtest/src/auth/mod.rs

@ -4,7 +4,11 @@ use axum::headers::HeaderName;
use axum::http::Request;
use axum::http::StatusCode;
use axum::middleware::Next;
use axum::response::IntoResponse;
use axum::response::Response;
use axum::Json;
use crate::entities::ErrorResponse;
static CIUSR: HeaderName = HeaderName::from_static("x-ciusr");
static CIPWD: HeaderName = HeaderName::from_static("x-cipwd");
@ -16,7 +20,7 @@ pub async fn ci_auth<B>(
expected_usr: String,
expected_pwd: String,
expected_role: String,
) -> Result<Response, StatusCode> {
) -> Result<Response, (StatusCode, impl IntoResponse)> {
let usr = req
.headers()
.get(&CIUSR)
@ -38,6 +42,9 @@ pub async fn ci_auth<B>(
{
Ok(next.run(req).await)
}
(_, _, _) => Err(StatusCode::UNAUTHORIZED),
(_, _, _) => Err((
StatusCode::UNAUTHORIZED,
Json(ErrorResponse::new("Invalid credentials")),
)),
}
}

48
axumtest/src/entities/mod.rs

@ -0,0 +1,48 @@
//! Entities used in the system.
use clap::Parser;
use mongodb::Database;
/// State shared between routes.
pub struct State {
pub db: Database,
}
/// Command line options.
#[derive(Parser)]
pub struct Params {
/// Address to listen for requests.
#[clap(env = "SRV_ADDR", default_value = "0.0.0.0:3000")]
pub addr: String,
/// URI to connect to MongoDB.
#[clap(short, long, env = "MONGO_URI")]
pub mongo_addr: String,
/// Validation for the X-CIUSR header.
#[clap(long, env = "CIUSR")]
pub ci_usr: String,
/// Validation for the X-CIPWD header.
#[clap(long, env = "CIPWD")]
pub ci_pwd: String,
/// Validation for the X-CIROLE header.
#[clap(long, env = "CIROLE")]
pub ci_role: String,
}
#[derive(serde::Serialize)]
pub struct ErrorResponse {
status: String,
reason: String,
}
impl ErrorResponse {
pub fn new(reason: &str) -> Self {
Self {
status: "ERR".into(),
reason: reason.into(),
}
}
}

25
axumtest/src/main.rs

@ -1,6 +1,7 @@
mod auth;
mod cases;
mod collections;
mod entities;
use std::sync::Arc;
@ -10,29 +11,9 @@ use clap::Parser;
use dotenv::dotenv;
use mongodb::options::ClientOptions;
use mongodb::Client;
use mongodb::Database;
#[derive(Parser)]
struct Params {
#[clap(env = "SRV_ADDR", default_value = "0.0.0.0:3000")]
addr: String,
#[clap(short, long, env = "MONGO_URI")]
mongo_addr: String,
#[clap(long, env = "CIUSR")]
ci_usr: String,
#[clap(long, env = "CIPWD")]
ci_pwd: String,
#[clap(long, env = "CIROLE")]
ci_role: String,
}
pub struct State {
db: Database,
}
use crate::entities::Params;
use crate::entities::State;
#[tokio::main]
async fn main() {

Loading…
Cancel
Save