1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
use salvo_core::async_trait;
use salvo_core::http::header::AUTHORIZATION;
use salvo_core::http::{Request, Response, StatusCode};
use salvo_core::routing::FlowCtrl;
use salvo_core::{Depot, Error, Handler};
pub const USERNAME_KEY: &str = "::salvo::extra::basic_auth::username";
#[async_trait]
pub trait BasicAuthValidator: Send + Sync {
#[must_use = "validate future must be used"]
async fn validate(&self, username: &str, password: &str) -> bool;
}
pub trait BasicAuthDepotExt {
fn basic_auth_username(&self) -> Option<&String>;
}
impl BasicAuthDepotExt for Depot {
fn basic_auth_username(&self) -> Option<&String> {
self.get(USERNAME_KEY)
}
}
pub struct BasicAuthHandler<V: BasicAuthValidator> {
realm: String,
validator: V,
}
impl<V> BasicAuthHandler<V>
where
V: BasicAuthValidator,
{
pub fn new(validator: V) -> Self {
BasicAuthHandler {
realm: "realm".to_owned(),
validator,
}
}
#[inline]
fn ask_credentials(&self, res: &mut Response) {
res.headers_mut().insert(
"WWW-Authenticate",
format!("Basic realm={:?}", self.realm).parse().unwrap(),
);
res.set_status_code(StatusCode::UNAUTHORIZED);
}
fn parse_authorization<S: AsRef<str>>(&self, authorization: S) -> Result<(String, String), Error> {
let auth = base64::decode(authorization.as_ref()).map_err(Error::other)?;
let auth = auth.iter().map(|&c| c as char).collect::<String>();
if let Some((username, password)) = auth.split_once(':') {
Ok((username.to_owned(), password.to_owned()))
} else {
Err(Error::other("parse http header failed"))
}
}
}
#[async_trait]
impl<V> Handler for BasicAuthHandler<V>
where
V: BasicAuthValidator + 'static,
{
async fn handle(&self, req: &mut Request, depot: &mut Depot, res: &mut Response, ctrl: &mut FlowCtrl) {
if let Some(auth) = req.headers().get(AUTHORIZATION) {
if let Ok(auth) = auth.to_str() {
if auth.starts_with("Basic") {
if let Some((_, auth)) = auth.split_once(' ') {
if let Ok((username, password)) = self.parse_authorization(auth) {
if self.validator.validate(&username, &password).await {
depot.insert(USERNAME_KEY, username);
ctrl.call_next(req, depot, res).await;
return;
}
}
}
}
}
}
self.ask_credentials(res);
ctrl.skip_rest();
}
}