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
use base64::DecodeError;
use http_types::StatusCode;
use std::{fmt::Display, str::Utf8Error};

#[derive(Debug)]
pub enum Error {
    /// Header value is malformed
    Invalid,
    /// Authentication scheme is missing
    MissingScheme,
    /// Required authentication field is missing
    MissingField(&'static str),
    /// Unable to convert header into the str
    // ToStrError(header::ToStrError),
    /// Malformed base64 string
    Base64DecodeError(DecodeError),
    /// Malformed UTF-8 string
    Utf8Error(Utf8Error),
}

impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::Invalid => {
                write!(f, "Invalid")
            }
            Error::Base64DecodeError(error) => Display::fmt(error, f),
            Error::MissingField(msg) => {
                write!(f, "MissingField: {}", msg)
            }
            Error::MissingScheme => {
                write!(f, "MissingScheme")
            }
            Error::Utf8Error(error) => Display::fmt(error, f),
        }
    }
}

impl From<DecodeError> for Error {
    fn from(decode_error: DecodeError) -> Self {
        Error::Base64DecodeError(decode_error)
    }
}

impl From<Utf8Error> for Error {
    fn from(utf8_error: Utf8Error) -> Self {
        Error::Utf8Error(utf8_error)
    }
}

impl From<Error> for tide::Error {
    fn from(auth_error: Error) -> Self {
        tide::Error::from_str(StatusCode::Forbidden, auth_error)
    }
}

pub type Result<T> = std::result::Result<T, Error>;