use std::borrow::Cow;
use std::default::Default;
use kayrx::web::dev::{Payload, ServiceRequest};
use kayrx::http::header::Header;
use kayrx::web::{FromRequest, HttpRequest};
use futures::future;
use super::config::AuthExtractorConfig;
use super::errors::AuthenticationError;
use super::AuthExtractor;
use crate::headers::authorization;
use crate::headers::www_authenticate::bearer;
pub use crate::headers::www_authenticate::bearer::Error;
#[derive(Debug, Clone, Default)]
pub struct Config(bearer::Bearer);
impl Config {
pub fn scope<T: Into<Cow<'static, str>>>(mut self, value: T) -> Config {
self.0.scope = Some(value.into());
self
}
pub fn realm<T: Into<Cow<'static, str>>>(mut self, value: T) -> Config {
self.0.realm = Some(value.into());
self
}
}
impl AsRef<bearer::Bearer> for Config {
fn as_ref(&self) -> &bearer::Bearer {
&self.0
}
}
impl AuthExtractorConfig for Config {
type Inner = bearer::Bearer;
fn into_inner(self) -> Self::Inner {
self.0
}
}
#[allow(clippy::needless_doctest_main)]
#[derive(Debug, Clone)]
pub struct BearerAuth(authorization::Bearer);
impl BearerAuth {
pub fn token(&self) -> &str {
self.0.token()
}
}
impl FromRequest for BearerAuth {
type Config = Config;
type Future = future::Ready<Result<Self, Self::Error>>;
type Error = AuthenticationError<bearer::Bearer>;
fn from_request(
req: &HttpRequest,
_payload: &mut Payload,
) -> <Self as FromRequest>::Future {
future::ready(
authorization::Authorization::<authorization::Bearer>::parse(req)
.map(|auth| BearerAuth(auth.into_scheme()))
.map_err(|_| {
let bearer = req
.app_data::<Self::Config>()
.map(|config| config.0.clone())
.unwrap_or_else(Default::default);
AuthenticationError::new(bearer)
}),
)
}
}
impl AuthExtractor for BearerAuth {
type Future = future::Ready<Result<Self, Self::Error>>;
type Error = AuthenticationError<bearer::Bearer>;
fn from_service_request(req: &ServiceRequest) -> Self::Future {
future::ready(
authorization::Authorization::<authorization::Bearer>::parse(req)
.map(|auth| BearerAuth(auth.into_scheme()))
.map_err(|_| {
let bearer = req
.app_data::<Config>()
.map(|config| config.0.clone())
.unwrap_or_else(Default::default);
AuthenticationError::new(bearer)
}),
)
}
}
impl AuthenticationError<bearer::Bearer> {
pub fn with_error(mut self, kind: Error) -> Self {
*self.status_code_mut() = kind.status_code();
self.challenge_mut().error = Some(kind);
self
}
pub fn with_error_description<T>(mut self, desc: T) -> Self
where
T: Into<Cow<'static, str>>,
{
self.challenge_mut().error_description = Some(desc.into());
self
}
pub fn with_error_uri<T>(mut self, uri: T) -> Self
where
T: Into<Cow<'static, str>>,
{
self.challenge_mut().error_uri = Some(uri.into());
self
}
}