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