Add API tokens support #9

Merged
pierre merged 40 commits from api into master 2024-04-23 17:04:45 +00:00
3 changed files with 28 additions and 2 deletions
Showing only changes of commit f56e9c14b2 - Show all commits

View File

@ -5,6 +5,7 @@ use crate::constants;
use crate::utils::jwt_utils;
use crate::utils::jwt_utils::{TokenPrivKey, TokenPubKey};
use crate::utils::time_utils::time;
use std::path::Path;
#[derive(serde::Serialize, serde::Deserialize, Clone, Copy, Debug)]
pub struct TokenID(pub uuid::Uuid);
@ -28,6 +29,11 @@ impl Token {
pub fn to_json(&self) -> String {
serde_json::to_string(self).expect("Failed to serialize an API token!")
}
/// Load token information from a file
pub fn load_from_file(path: &Path) -> anyhow::Result<Self> {
Ok(serde_json::from_str(&std::fs::read_to_string(path)?)?)
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, Eq, PartialEq)]
@ -114,3 +120,12 @@ pub async fn create(t: &NewToken) -> anyhow::Result<(Token, TokenPrivKey)> {
Ok((token, priv_key))
}
/// Get the entire list of api toksn
pub async fn full_list() -> anyhow::Result<Vec<Token>> {
let mut list = Vec::new();
for f in std::fs::read_dir(AppConfig::get().api_tokens_path())? {
list.push(Token::load_from_file(&f?.path())?);
}
Ok(list)
}

View File

@ -47,3 +47,14 @@ pub async fn create(new_token: web::Json<NewToken>) -> HttpResult {
priv_key,
}))
}
/// Get the list of API tokens
pub async fn list() -> HttpResult {
let list = api_tokens::full_list()
.await?
.into_iter()
.map(RestToken::new)
.collect::<Vec<_>>();
Ok(HttpResponse::Ok().json(list))
}

View File

@ -282,11 +282,11 @@ async fn main() -> std::io::Result<()> {
"/api/tokens/create",
web::post().to(api_tokens_controller::create),
)
/* TODO .route(
.route(
"/api/tokens/list",
web::get().to(api_tokens_controller::list),
)
.route(
/* TODO .route(
"/api/tokens/{uid}",
web::get().to(api_tokens_controller::get_single),
)