view src/guards.rs @ 27:792eb8ac3d93

cargo fmt
author Lewin Bormann <lbo@spheniscida.de>
date Thu, 14 Jul 2022 20:35:35 -0700
parents b1850e6f4d9a
children fd0237049be0
line wrap: on
line source

use anyhow::{self, Context, Error};

use rocket::http::HeaderMap;
use rocket::request::{self, FlashMessage, 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()))
    }
}