feat(api_key): implement API key management with creation, retrieval, and deletion endpoints

This commit is contained in:
2025-09-06 16:18:32 +02:00
parent b83b7acf1c
commit 508f218fc0
22 changed files with 520 additions and 11 deletions

View File

@@ -8,7 +8,7 @@ use once_cell::sync::Lazy;
use sea_orm::prelude::Uuid;
use serde::{Deserialize, Serialize};
use app::state::AppState;
use app::{persistence::api_key, state::AppState};
#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
@@ -28,14 +28,24 @@ impl FromRequestParts<AppState> for AuthUser {
async fn from_request_parts(
parts: &mut Parts,
_state: &AppState,
state: &AppState,
) -> Result<Self, Self::Rejection> {
// --- Test User ID (Keep for testing) ---
if let Some(user_id_header) = parts.headers.get("x-test-user-id") {
let user_id_str = user_id_header.to_str().unwrap_or("0");
let user_id = user_id_str.parse::<Uuid>().unwrap_or(Uuid::nil());
return Ok(AuthUser { id: user_id });
}
// --- API Key Authentication ---
if let Some(api_key) = get_api_key_from_header(&parts.headers) {
return match api_key::validate_api_key(&state.conn, &api_key).await {
Ok(user) => Ok(AuthUser { id: user.id }),
Err(_) => Err((StatusCode::UNAUTHORIZED, "Invalid API Key")),
};
}
// --- JWT Authentication (Fallback) ---
let token = get_token_from_header(&parts.headers)
.ok_or((StatusCode::UNAUTHORIZED, "Missing or invalid token"))?;
@@ -56,3 +66,11 @@ fn get_token_from_header(headers: &HeaderMap) -> Option<String> {
.and_then(|header| header.strip_prefix("Bearer "))
.map(|token| token.to_owned())
}
fn get_api_key_from_header(headers: &HeaderMap) -> Option<String> {
headers
.get("Authorization")
.and_then(|header| header.to_str().ok())
.and_then(|header| header.strip_prefix("ApiKey "))
.map(|key| key.to_owned())
}