trifid/trifid-api/src/auth.rs

97 lines
3.1 KiB
Rust
Raw Normal View History

2023-11-21 01:07:02 +00:00
use crate::models::SessionToken;
pub struct AuthInfo {
pub session_token: Option<SessionToken>,
pub auth_token: Option<()>,
}
#[macro_export]
macro_rules! auth {
($i:expr,$c:expr) => {{
let authorization_hdr_value = match $i.headers().get("Authorization") {
Some(hdr) => hdr,
None => $crate::err!(
actix_web::http::StatusCode::UNAUTHORIZED,
$crate::make_err!("ERR_UNAUTHORIZED", "unauthorized")
),
};
let hdr_value_split = $crate::handle_error!(authorization_hdr_value.to_str())
.split(' ')
.collect::<Vec<_>>();
if hdr_value_split.len() < 2 {
$crate::err!(
actix_web::http::StatusCode::UNAUTHORIZED,
$crate::make_err!("ERR_UNAUTHORIZED", "unauthorized")
)
}
let tokens = hdr_value_split[1..].to_vec();
let mut auth_info = $crate::auth::AuthInfo {
session_token: None,
auth_token: None,
};
for token in tokens {
if token.starts_with("sess-") {
// handle session token
use $crate::schema::session_tokens::dsl::*;
let tokens = $crate::handle_error!(
session_tokens
.filter(id.eq(token))
.select($crate::models::SessionToken::as_select())
.load(&mut $c)
.await
);
let real_token = match tokens.get(0) {
Some(tok) => tok,
None => $crate::err!(
actix_web::http::StatusCode::UNAUTHORIZED,
$crate::make_err!("ERR_UNAUTHORIZED", "unauthorized")
),
};
auth_info.session_token = Some(real_token.clone());
} else if token.starts_with("auth-") {
// parse auth token
todo!()
}
}
auth_info
}};
}
#[macro_export]
macro_rules! enforce {
(sess $i:expr) => {
if $i.session_token.is_none() {
$crate::err!(
actix_web::http::StatusCode::UNAUTHORIZED,
$crate::make_err!("ERR_UNAUTHORIZED", "unauthorized")
)
}
};
(auth $i:expr) => {
if $i.auth_token.is_none() {
$crate::err!(
actix_web::http::StatusCode::UNAUTHORIZED,
$crate::make_err!("ERR_UNAUTHORIZED", "unauthorized")
)
}
};
(sess auth $i:expr) => {
if $i.session_token.is_none() || $i.auth_token.is_none() {
$crate::err!(
actix_web::http::StatusCode::UNAUTHORIZED,
$crate::make_err!("ERR_UNAUTHORIZED", "unauthorized")
)
}
};
(auth sess $i:expr) => {
if $i.session_token.is_none() || $i.auth_token.is_none() {
$crate::err!(
actix_web::http::StatusCode::UNAUTHORIZED,
$crate::make_err!("ERR_UNAUTHORIZED", "unauthorized")
)
}
};
}