Add API tokens support #9

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

View File

@ -1,5 +1,6 @@
//! # API tokens management
use crate::app_config::AppConfig;
use crate::constants;
use crate::utils::jwt_utils;
use crate::utils::jwt_utils::{TokenPrivKey, TokenPubKey};
@ -10,9 +11,9 @@ pub struct TokenID(pub uuid::Uuid);
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct Token {
pub id: TokenID,
pub name: String,
pub description: String,
pub id: TokenID,
created: u64,
updated: u64,
pub pub_key: TokenPubKey,
@ -22,6 +23,13 @@ pub struct Token {
pub delete_after_inactivity: Option<u64>,
}
impl Token {
/// Turn the token into a JSON string
pub fn to_json(&self) -> String {
serde_json::to_string(self).expect("Failed to serialize an API token!")
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, Eq, PartialEq)]
pub enum TokenVerb {
GET,
@ -83,23 +91,26 @@ impl NewToken {
}
/// Create a new Token
pub async fn create(token: &NewToken) -> anyhow::Result<(Token, TokenPrivKey)> {
pub async fn create(t: &NewToken) -> anyhow::Result<(Token, TokenPrivKey)> {
let (pub_key, priv_key) = jwt_utils::generate_key_pair()?;
let full_token = Token {
name: token.name.to_string(),
description: token.description.to_string(),
let token = Token {
name: t.name.to_string(),
description: t.description.to_string(),
id: TokenID(uuid::Uuid::new_v4()),
created: time(),
updated: time(),
pub_key,
rights: token.rights.clone(),
rights: t.rights.clone(),
last_used: Some(time()),
ip_restriction: token.ip_restriction,
delete_after_inactivity: token.delete_after_inactivity,
ip_restriction: t.ip_restriction,
delete_after_inactivity: t.delete_after_inactivity,
};
// TODO : save
std::fs::write(
AppConfig::get().api_token_definition_path(token.id),
token.to_json(),
)?;
Ok((full_token, priv_key))
Ok((token, priv_key))
}

View File

@ -1,3 +1,4 @@
use crate::api_tokens::TokenID;
use crate::constants;
use crate::libvirt_lib_structures::XMLUuid;
use crate::libvirt_rest_structures::net::NetworkName;
@ -272,6 +273,10 @@ impl AppConfig {
pub fn api_tokens_path(&self) -> PathBuf {
self.storage_path().join(constants::STORAGE_TOKENS_DIR)
}
pub fn api_token_definition_path(&self, id: TokenID) -> PathBuf {
self.api_tokens_path().join(format!("{}.json", id.0))
}
}
#[derive(Debug, Clone, serde::Serialize)]