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
use std::error::Error;
use std::fmt;
use actix_web::http::StatusCode;
use actix_web::{HttpResponse, ResponseError};
use crate::headers::www_authenticate::Challenge;
use crate::headers::www_authenticate::WwwAuthenticate;
#[derive(Debug)]
pub struct AuthenticationError<C: Challenge> {
challenge: C,
status_code: StatusCode,
}
impl<C: Challenge> AuthenticationError<C> {
pub fn new(challenge: C) -> AuthenticationError<C> {
AuthenticationError {
challenge,
status_code: StatusCode::UNAUTHORIZED,
}
}
pub fn challenge_mut(&mut self) -> &mut C {
&mut self.challenge
}
pub fn status_code_mut(&mut self) -> &mut StatusCode {
&mut self.status_code
}
}
impl<C: Challenge> fmt::Display for AuthenticationError<C> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.status_code, f)
}
}
impl<C: 'static + Challenge> Error for AuthenticationError<C> {}
impl<C: 'static + Challenge> ResponseError for AuthenticationError<C> {
fn error_response(&self) -> HttpResponse {
HttpResponse::build(self.status_code)
.insert_header(WwwAuthenticate(self.challenge.clone()))
.finish()
}
fn status_code(&self) -> StatusCode {
self.status_code
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::headers::www_authenticate::basic::Basic;
use actix_web::Error;
#[test]
fn test_status_code_is_preserved_across_error_conversions() {
let ae: AuthenticationError<Basic> = AuthenticationError::new(Basic::default());
let expected = ae.status_code;
let e = Error::from(ae);
let re = e.as_response_error();
assert_eq!(expected, re.status_code());
}
}