use std::{convert::Infallible, fmt, ops::Deref, sync::Arc};
use axum::{extract::FromRequestParts, http::request::Parts};
use crate::web::response::ApiError;
use super::RequestSubject;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RequestId(Arc<str>);
impl RequestId {
pub fn new(value: impl Into<Arc<str>>) -> Self {
Self(value.into())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_inner(self) -> String {
self.0.to_string()
}
}
impl AsRef<str> for RequestId {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl From<String> for RequestId {
fn from(value: String) -> Self {
Self::new(value)
}
}
impl Deref for RequestId {
type Target = str;
fn deref(&self) -> &Self::Target {
self.as_str()
}
}
impl fmt::Display for RequestId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl<S> FromRequestParts<S> for RequestId
where
S: Send + Sync,
{
type Rejection = Infallible;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
Ok(parts
.extensions
.get::<Self>()
.cloned()
.unwrap_or_else(|| Self::new(uuid::Uuid::now_v7().to_string())))
}
}
#[derive(Clone, Debug)]
pub struct TrustedSubject(Arc<RequestSubject>);
impl TrustedSubject {
pub(crate) fn new(subject: RequestSubject) -> Self {
Self(Arc::new(subject))
}
#[must_use]
pub fn id(&self) -> &str {
&self.0.id
}
pub fn subject(&self) -> &RequestSubject {
&self.0
}
pub fn into_subject(self) -> RequestSubject {
Arc::unwrap_or_clone(self.0)
}
}
impl Deref for TrustedSubject {
type Target = RequestSubject;
fn deref(&self) -> &Self::Target {
self.subject()
}
}
impl<S> FromRequestParts<S> for TrustedSubject
where
S: Send + Sync,
{
type Rejection = ApiError;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
parts
.extensions
.get::<Self>()
.cloned()
.ok_or_else(|| ApiError::err_unauthorized("无法确认当前请求身份,请重新登录"))
}
}