cdb/src/routes/mod.rs
2025-04-16 04:05:29 +02:00

39 lines
984 B
Rust

use rocket::{
Request, http::Status, outcome::Outcome, request::FromRequest, response::status::BadRequest,
};
use serde_json::json;
pub mod flow;
pub mod item;
pub type ApiError = BadRequest<serde_json::Value>;
type FallibleApiResponse = Result<serde_json::Value, ApiError>;
pub fn api_error(msg: &str) -> ApiError {
BadRequest(json!({
"error": msg
}))
}
pub struct Token(pub String);
#[macro_export]
macro_rules! check_auth {
($t:ident, $c:ident) => {
if !$c.allowed_tokens.contains(&$t.0) {
return Err(api_error("Unauthorized"));
}
};
}
#[rocket::async_trait]
impl<'r> FromRequest<'r> for Token {
type Error = ();
async fn from_request(request: &'r Request<'_>) -> rocket::request::Outcome<Self, Self::Error> {
match request.headers().get_one("Token") {
Some(key) => Outcome::Success(Token(key.to_string())),
None => Outcome::Error((Status::Unauthorized, ())),
}
}
}