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
use std::fmt;
use std::error::Error;
use std::string;
use base64;
use actix_web::HttpResponse;
use actix_web::error::ResponseError;
use actix_web::http::{StatusCode, header};
#[derive(Debug, PartialEq)]
pub enum AuthError {
HeaderMissing,
InvalidMechanism,
HeaderMalformed,
}
impl fmt::Display for AuthError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.description())
}
}
impl Error for AuthError {
fn description(&self) -> &str {
match *self {
AuthError::HeaderMissing => "HTTP 'Authorization' header is missing",
AuthError::InvalidMechanism => "Wrong mechanism for a HTTP 'Authorization' header, expected 'Basic'",
AuthError::HeaderMalformed => "Malformed HTTP 'Authorization' header",
}
}
}
impl From<header::ToStrError> for AuthError {
fn from(_: header::ToStrError) -> Self {
AuthError::HeaderMalformed
}
}
impl From<base64::DecodeError> for AuthError {
fn from(_: base64::DecodeError) -> Self {
AuthError::HeaderMalformed
}
}
impl From<string::FromUtf8Error> for AuthError {
fn from(_: string::FromUtf8Error) -> Self {
AuthError::HeaderMalformed
}
}
impl ResponseError for AuthError {
fn error_response(&self) -> HttpResponse {
let status = match *self {
AuthError::HeaderMissing => StatusCode::UNAUTHORIZED,
AuthError::InvalidMechanism => StatusCode::UNAUTHORIZED,
AuthError::HeaderMalformed => StatusCode::BAD_REQUEST,
};
HttpResponse::build(status)
.header("WWW-Authenticate", "Basic, charset=\"UTF-8\"")
.finish()
}
}