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
use std::str;
use std::fmt;
use std::error::Error;
use std::convert::From;

use base64;
use actix_web::http::header;

/// Possible errors while parsing `Authorization` header.
///
/// Should not be used directly unless you are implementing
/// your own [authentication scheme](./trait.Scheme.html).
#[derive(Debug)]
pub enum ParseError {
    /// Header value is malformed
    Invalid,
    /// Authentication scheme is missing
    MissingScheme,
    /// Required authentication field is missing
    MissingField(&'static str),
    ToStrError(header::ToStrError),
    Base64DecodeError(base64::DecodeError),
    Utf8Error(str::Utf8Error),
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(self.description())
    }
}

impl Error for ParseError {
    fn description(&self) -> &str {
        match self {
            ParseError::Invalid => "Invalid header value",
            ParseError::MissingScheme => "Missing authorization scheme",
            ParseError::MissingField(_) => "Missing header field",
            ParseError::ToStrError(e) => e.description(),
            ParseError::Base64DecodeError(e) => e.description(),
            ParseError::Utf8Error(e) => e.description(),
        }
    }

    fn cause(&self) -> Option<&Error> {
        match self {
            ParseError::Invalid => None,
            ParseError::MissingScheme => None,
            ParseError::MissingField(_) => None,
            ParseError::ToStrError(e) => Some(e),
            ParseError::Base64DecodeError(e) => Some(e),
            ParseError::Utf8Error(e) => Some(e),
        }
    }
}

impl From<header::ToStrError> for ParseError {
    fn from(e: header::ToStrError) -> Self {
        ParseError::ToStrError(e)
    }
}
impl From<base64::DecodeError> for ParseError {
    fn from(e: base64::DecodeError) -> Self {
        ParseError::Base64DecodeError(e)
    }
}
impl From<str::Utf8Error> for ParseError {
    fn from(e: str::Utf8Error) -> Self {
        ParseError::Utf8Error(e)
    }
}