view src/guards.rs @ 77:fd0237049be0

Show paths instead of tags & apply rust fixes
author Lewin Bormann <lbo@spheniscida.de>
date Mon, 31 Jul 2023 09:31:37 +0200
parents 792eb8ac3d93
children d3368a7142ef
line wrap: on
line source

use anyhow::{self, Error};

use rocket::http::HeaderMap;
use rocket::request::{FromRequest, Outcome, Request};

pub const USER_ID_COOKIE_KEY: &str = "user_id";

pub struct LoggedInGuard(pub String);

#[rocket::async_trait]
impl<'r> FromRequest<'r> for LoggedInGuard {
    type Error = Error;

    async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
        let cookies = req.cookies();
        if let Some(uc) = cookies.get_private(USER_ID_COOKIE_KEY) {
            Outcome::Success(LoggedInGuard(uc.value().to_string()))
        } else {
            Outcome::Forward(())
        }
    }
}

pub struct HeadersGuard<'h>(pub HeaderMap<'h>);

#[rocket::async_trait]
impl<'r> FromRequest<'r> for HeadersGuard<'r> {
    type Error = Error;

    async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
        Outcome::Success(HeadersGuard(req.headers().clone()))
    }
}