Managed to query VirtWeb API
This commit is contained in:
71
remote_backend/src/virtweb_client.rs
Normal file
71
remote_backend/src/virtweb_client.rs
Normal file
@ -0,0 +1,71 @@
|
||||
use crate::app_config::AppConfig;
|
||||
use crate::utils::time;
|
||||
use std::fmt::Display;
|
||||
use thiserror::Error;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum VirtWebClientError {
|
||||
#[error("Invalid status code from VirtWeb: {0}")]
|
||||
InvalidStatusCode(u16),
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize, Debug)]
|
||||
pub struct TokenClaims {
|
||||
pub sub: String,
|
||||
pub iat: u64,
|
||||
pub exp: u64,
|
||||
pub verb: String,
|
||||
pub path: String,
|
||||
pub nonce: String,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize, Debug)]
|
||||
pub struct TokenRight {
|
||||
verb: String,
|
||||
path: String,
|
||||
}
|
||||
|
||||
pub type TokenRights = Vec<TokenRight>;
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct TokenInfo {
|
||||
rights: TokenRights,
|
||||
}
|
||||
|
||||
/// Perform a request on the API
|
||||
async fn request<D: Display, E: serde::de::DeserializeOwned>(uri: D) -> anyhow::Result<E> {
|
||||
let url = format!("{}{}", AppConfig::get().virtweb_base_url, uri);
|
||||
log::debug!("Will query {uri}...");
|
||||
|
||||
let jwt = TokenClaims {
|
||||
sub: AppConfig::get().virtweb_token_id.to_string(),
|
||||
iat: time() - 60 * 2,
|
||||
exp: time() + 60 * 3,
|
||||
verb: "GET".to_string(),
|
||||
path: uri.to_string(),
|
||||
nonce: Uuid::new_v4().to_string(),
|
||||
};
|
||||
let jwt = AppConfig::get().token_private_key().sign_jwt(&jwt)?;
|
||||
|
||||
let res = reqwest::Client::new()
|
||||
.get(url)
|
||||
.header("x-token-id", &AppConfig::get().virtweb_token_id)
|
||||
.header("x-token-content", jwt)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
if !res.status().is_success() {
|
||||
return Err(VirtWebClientError::InvalidStatusCode(res.status().as_u16()).into());
|
||||
}
|
||||
|
||||
Ok(res.json().await?)
|
||||
}
|
||||
|
||||
/// Get current token rights
|
||||
pub async fn get_token_rights() -> anyhow::Result<TokenRights> {
|
||||
let res: TokenInfo =
|
||||
request(format!("/api/token/{}", AppConfig::get().virtweb_token_id)).await?;
|
||||
|
||||
Ok(res.rights)
|
||||
}
|
Reference in New Issue
Block a user