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
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
//! basic auth middleware

use async_trait::async_trait;

use salvo_core::http::header::AUTHORIZATION;
use salvo_core::http::{Request, Response, StatusCode};
use salvo_core::routing::FlowCtrl;
use salvo_core::{Depot, Handler};

use thiserror::Error;

/// key used when insert into depot.
pub const USERNAME_KEY: &str = "::salvo::extra::basic_auth::username";

/// Error
#[derive(Debug, Error)]
pub enum Error {
    /// Base64 decode error
    #[error("Base64 decode error")]
    Base64Decode(#[from] base64::DecodeError),
    /// ParseHttpHeader
    #[error("Parse http header error")]
    ParseHttpHeader,
}

/// BasicAuthValidator
pub trait BasicAuthValidator: Send + Sync {
    /// Validate is that username and password is right.
    fn validate(&self, username: String, password: String) -> bool;
}
impl<F> BasicAuthValidator for F
where
    F: Send + Sync,
    F: Fn(String, String) -> bool,
{
    fn validate(&self, username: String, password: String) -> bool {
        self(username, password)
    }
}

/// BasicAuthDepotExt
pub trait BasicAuthDepotExt {
    /// Get basic auth username reference.
    fn basic_auth_username(&self) -> Option<&String>;
}

impl BasicAuthDepotExt for Depot {
    fn basic_auth_username(&self) -> Option<&String> {
        self.get(USERNAME_KEY)
    }
}

/// BasicAuthHandler
pub struct BasicAuthHandler<V: BasicAuthValidator> {
    realm: String,
    validator: V,
}
impl<V> BasicAuthHandler<V>
where
    V: BasicAuthValidator,
{
    /// Create new `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())?;
        let auth = auth.iter().map(|&c| c as char).collect::<String>();
        let parts: Vec<&str> = auth.splitn(2, ':').collect();
        if parts.len() == 2 {
            Ok((parts[0].to_owned(), parts[1].to_owned()))
        } else {
            Err(Error::ParseHttpHeader)
        }
    }
}
#[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.splitn(2, ' ').collect::<Vec<&str>>().pop() {
                        if let Ok((username, password)) = self.parse_authorization(auth) {
                            if self.validator.validate(username.clone(), password) {
                                depot.insert(USERNAME_KEY, username);
                                ctrl.call_next(req, depot, res).await;
                                return;
                            }
                        }
                    }
                }
            }
        }
        self.ask_credentials(res);
        ctrl.skip_reset();
    }
}

#[cfg(test)]
mod tests {
    use salvo_core::http::headers::{Authorization, HeaderMapExt};
    use salvo_core::hyper;
    use salvo_core::prelude::*;

    use super::*;

    #[tokio::test]
    async fn test_basic_auth() {
        let auth_handler =
            BasicAuthHandler::new(|username, password| -> bool { username == "root" && password == "pwd" });

        #[fn_handler]
        async fn hello() -> &'static str {
            "hello"
        }

        let router = Router::new()
            .hoop(auth_handler)
            .push(Router::with_path("hello").get(hello));
        let service = Service::new(router);

        let mut req = hyper::Request::builder()
            .method("GET")
            .uri("http://127.0.0.1:7979/hello");
        let headers = req.headers_mut().unwrap();
        headers.typed_insert(Authorization::basic("root", "pwd"));
        let req: Request = req.body(hyper::Body::empty()).unwrap().into();
        let content = service.handle(req).await.take_text().await.unwrap();
        assert!(content.contains("hello"));

        let mut req = hyper::Request::builder()
            .method("GET")
            .uri("http://127.0.0.1:7979/hello");
        let headers = req.headers_mut().unwrap();
        headers.typed_insert(Authorization::basic("root", "pwd2"));
        let req: Request = req.body(hyper::Body::empty()).unwrap().into();
        let content = service.handle(req).await.take_text().await.unwrap();
        assert!(content.contains("Unauthorized"));
    }
}