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
//! The service provider interface (SPI) for auth

use super::UserDetail;
use crate::BoxError;

use async_trait::async_trait;
use std::fmt::Debug;
use thiserror::Error;

/// Defines the requirements for Authentication implementations
#[async_trait]
pub trait Authenticator<User>: Sync + Send + Debug
where
    User: UserDetail,
{
    /// Authenticate the given user with the given password.
    async fn authenticate(&self, username: &str, password: &str) -> Result<User, AuthenticationError>;

    /// Implement to set the name of the authenticator. By default it returns the type signature.
    fn name(&self) -> &str {
        std::any::type_name::<Self>()
    }
}

/// The error type returned by `Authenticator.authenticate`
#[derive(Error, Debug)]
pub enum AuthenticationError {
    /// A bad password was provided
    #[error("bad password")]
    BadPassword,

    /// A bad username was provided
    #[error("bad username")]
    BadUser,

    /// Another issue occurred during the authentication process.
    #[error("authentication error: {0}: {1:?}")]
    ImplPropagated(String, #[source] Option<BoxError>),
}

impl AuthenticationError {
    /// Creates a new domain specific error
    pub fn new(s: impl Into<String>) -> AuthenticationError {
        AuthenticationError::ImplPropagated(s.into(), None)
    }

    /// Creates a new domain specific error with the given source error.
    pub fn with_source<E>(s: impl Into<String>, source: E) -> AuthenticationError
    where
        E: std::error::Error + Send + Sync + 'static,
    {
        AuthenticationError::ImplPropagated(s.into(), Some(Box::new(source)))
    }
}