drawbridge_type/user/
context.rs1use super::Name;
4
5use std::fmt::Display;
6use std::str::FromStr;
7
8use anyhow::Context as _;
9
10#[derive(Clone, Debug, Eq, Hash, PartialEq)]
11pub struct Context {
12 pub name: Name,
13}
14
15impl FromStr for Context {
16 type Err = anyhow::Error;
17
18 fn from_str(s: &str) -> Result<Self, Self::Err> {
19 let name = s.parse().context("failed to parse user name")?;
20 Ok(Self { name })
21 }
22}
23
24impl Display for Context {
25 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26 write!(f, "{}", self.name)
27 }
28}
29
30#[cfg(feature = "axum")]
31#[axum::async_trait]
32impl<B: Send> axum::extract::FromRequest<B> for Context {
33 type Rejection = (axum::http::StatusCode, String);
34
35 async fn from_request(
36 req: &mut axum::extract::RequestParts<B>,
37 ) -> Result<Self, Self::Rejection> {
38 let axum::Extension(name) = req.extract().await.map_err(|e| {
39 (
40 axum::http::StatusCode::INTERNAL_SERVER_ERROR,
41 anyhow::Error::new(e)
42 .context("failed to extract user context")
43 .to_string(),
44 )
45 })?;
46 Ok(Self { name })
47 }
48}