idkthings_core 0.1.1

core stuff for idkthings
Documentation
use crate::auth::MaybeCurrentUser;
use poem::{Endpoint, Middleware, Request, Result};
use serde::{Deserialize, Serialize};
use sqlx::PgPool;
use uuid::Uuid;

pub struct MaybeCurrentUserMiddleware {
    pub pg_pool: PgPool,
}

impl<E: Endpoint> Middleware<E> for MaybeCurrentUserMiddleware {
    type Output = MaybeCurrentUserMiddlewareImpl<E>;

    fn transform(&self, ep: E) -> Self::Output {
        MaybeCurrentUserMiddlewareImpl {
            ep,
            pg_pool: self.pg_pool.clone(),
        }
    }
}

pub struct MaybeCurrentUserMiddlewareImpl<E> {
    ep: E,
    pg_pool: PgPool,
}

#[poem::async_trait]
impl<E: Endpoint> Endpoint for MaybeCurrentUserMiddlewareImpl<E> {
    type Output = E::Output;

    async fn call(&self, mut req: Request) -> Result<Self::Output> {
        let maybe_current_user = if let Some(value) = req
            .headers()
            .get("CurrentUser")
            .and_then(|value| value.to_str().ok())
        {
            let user: User = serde_json::from_str(value).unwrap();
            MaybeCurrentUser(Some(user))
        } else {
            MaybeCurrentUser(None)
        };
        req.extensions_mut()
            .insert::<MaybeCurrentUser>(maybe_current_user);

        self.ep.call(req).await
    }
}

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct User {
    pub id: Uuid,
    pub email: String,
}