#[cfg(feature = "http-basic")]
use actix_web::dev::ServiceRequest;
#[cfg(feature = "http-basic")]
use actix_web::http;
#[cfg(feature = "http-basic")]
use base64::prelude::*;
#[cfg(feature = "http-basic")]
use crate::http::security::user::User;
#[cfg(feature = "http-basic")]
pub fn extract_basic_auth<F>(req: &ServiceRequest, verify: F) -> Option<User>
where
F: FnOnce(&str, &str) -> Option<User>,
{
let auth_header = req.headers().get(http::header::AUTHORIZATION)?;
let auth_str = auth_header.to_str().ok()?;
let credentials = auth_str.strip_prefix("Basic ")?;
let decoded = BASE64_STANDARD.decode(credentials).ok()?;
let decoded_str = String::from_utf8(decoded).ok()?;
let (username, password) = decoded_str.split_once(':')?;
verify(username, password)
}
#[cfg(feature = "http-basic")]
#[derive(Clone)]
pub struct HttpBasicConfig {
realm: String,
}
#[cfg(feature = "http-basic")]
impl HttpBasicConfig {
pub fn new() -> Self {
HttpBasicConfig {
realm: "Restricted".to_string(),
}
}
pub fn realm(mut self, realm: &str) -> Self {
self.realm = realm.to_string();
self
}
pub fn www_authenticate_header(&self) -> String {
format!("Basic realm=\"{}\"", self.realm)
}
}
#[cfg(feature = "http-basic")]
impl Default for HttpBasicConfig {
fn default() -> Self {
Self::new()
}
}