#![forbid(unsafe_code)]
#![deny(
clippy::dbg_macro,
missing_copy_implementations,
rustdoc::missing_crate_level_docs,
missing_debug_implementations,
missing_docs,
nonstandard_style,
unused_qualifications
)]
#[cfg(test)]
#[doc = include_str!("../README.md")]
mod readme {}
use base64::{Engine, engine::general_purpose::STANDARD as BASE64};
use trillium::{
Conn, Handler,
KnownHeaderName::{Authorization, WwwAuthenticate},
Status,
};
#[derive(Clone, Debug)]
pub struct BasicAuth {
credentials: Credentials,
realm: Option<String>,
expected_header: String,
www_authenticate: String,
}
#[derive(Clone, Debug, PartialEq, Eq, fieldwork::Fieldwork)]
#[fieldwork(get)]
pub struct Credentials {
username: String,
password: String,
}
impl Credentials {
fn new(username: &str, password: &str) -> Self {
Self {
username: String::from(username),
password: String::from(password),
}
}
fn expected_header(&self) -> String {
format!(
"Basic {}",
BASE64.encode(format!("{}:{}", self.username, self.password))
)
}
}
impl BasicAuth {
pub fn new(username: &str, password: &str) -> Self {
let credentials = Credentials::new(username, password);
let expected_header = credentials.expected_header();
let realm = None;
Self {
expected_header,
credentials,
realm,
www_authenticate: String::from("Basic"),
}
}
pub fn with_realm(mut self, realm: &str) -> Self {
self.www_authenticate = format!("Basic realm=\"{}\"", realm.replace('\"', "\\\""));
self.realm = Some(String::from(realm));
self
}
fn is_allowed(&self, conn: &Conn) -> bool {
conn.request_headers().get_str(Authorization) == Some(&*self.expected_header)
}
fn deny(&self, conn: Conn) -> Conn {
conn.with_status(Status::Unauthorized)
.with_response_header(WwwAuthenticate, self.www_authenticate.clone())
.halt()
}
}
impl Handler for BasicAuth {
async fn run(&self, conn: Conn) -> Conn {
if self.is_allowed(&conn) {
conn.with_state(self.credentials.clone())
} else {
self.deny(conn)
}
}
}