73 lines
1.9 KiB
Rust
73 lines
1.9 KiB
Rust
//! # API tokens management
|
|
|
|
use crate::api_tokens;
|
|
use crate::api_tokens::{NewToken, TokenID};
|
|
use crate::controllers::api_tokens_controller::rest_token::RestToken;
|
|
use crate::controllers::HttpResult;
|
|
use crate::utils::jwt_utils::TokenPrivKey;
|
|
use actix_web::{web, HttpResponse};
|
|
|
|
/// Create a special module for REST token to enforce usage of constructor function
|
|
mod rest_token {
|
|
use crate::api_tokens::Token;
|
|
use crate::utils::jwt_utils::TokenPubKey;
|
|
|
|
#[derive(serde::Serialize)]
|
|
pub struct RestToken {
|
|
token: Token,
|
|
}
|
|
|
|
impl RestToken {
|
|
pub fn new(mut token: Token) -> Self {
|
|
token.pub_key = TokenPubKey::None;
|
|
Self { token }
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(serde::Serialize)]
|
|
struct CreateTokenResult {
|
|
token: RestToken,
|
|
priv_key: TokenPrivKey,
|
|
}
|
|
|
|
/// Create a new API token
|
|
pub async fn create(new_token: web::Json<NewToken>) -> HttpResult {
|
|
if let Some(err) = new_token.check_error() {
|
|
log::error!("Failed to validate new API token information! {err}");
|
|
return Ok(HttpResponse::BadRequest().json(format!(
|
|
"Failed to validate new API token information! {err}"
|
|
)));
|
|
}
|
|
|
|
let (token, priv_key) = api_tokens::create(&new_token).await?;
|
|
|
|
Ok(HttpResponse::Ok().json(CreateTokenResult {
|
|
token: RestToken::new(token),
|
|
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))
|
|
}
|
|
|
|
#[derive(serde::Deserialize)]
|
|
pub struct TokenIDInPath {
|
|
uid: TokenID,
|
|
}
|
|
|
|
/// Get the information about a single token
|
|
pub async fn get_single(path: web::Path<TokenIDInPath>) -> HttpResult {
|
|
let token = api_tokens::get_single(path.uid).await?;
|
|
|
|
Ok(HttpResponse::Ok().json(RestToken::new(token)))
|
|
}
|