feat: add api key verification
This commit is contained in:
+8
-17
@@ -6,12 +6,11 @@ use axum::{
|
||||
use base64::{Engine as _, engine::general_purpose};
|
||||
use rand::RngCore;
|
||||
use rand::rngs::OsRng;
|
||||
use sha2::{Digest, Sha256};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::dto::api::{CreateApiKeyRequest, CreateApiKeyResponse};
|
||||
use crate::middlewares::auth::keycloak::Claims;
|
||||
use crate::middlewares::auth::middleware::Auth;
|
||||
use crate::state::app_state::AppState;
|
||||
use crate::utils::crypto::hash_key;
|
||||
|
||||
fn generate_api_key() -> String {
|
||||
let mut bytes = [0u8; 32];
|
||||
@@ -19,28 +18,20 @@ fn generate_api_key() -> String {
|
||||
general_purpose::URL_SAFE_NO_PAD.encode(bytes)
|
||||
}
|
||||
|
||||
fn hash_key(key: &str) -> String {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(key.as_bytes());
|
||||
hasher
|
||||
.finalize()
|
||||
.iter()
|
||||
.map(|b| format!("{:02x}", b))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub async fn create_api_key(
|
||||
State(state): State<AppState>,
|
||||
Extension(claims): Extension<Claims>,
|
||||
Extension(claims): Extension<Auth>,
|
||||
Json(body): Json<CreateApiKeyRequest>,
|
||||
) -> Result<Json<CreateApiKeyResponse>, StatusCode> {
|
||||
if matches!(claims, Auth::ApiKey(_)) {
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
|
||||
let raw_key = generate_api_key();
|
||||
let key_hash = hash_key(&raw_key);
|
||||
|
||||
dbg!(&claims);
|
||||
|
||||
let user_id = Uuid::parse_str(&claims.sub).map_err(|_| StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
sqlx::query!(
|
||||
r#"
|
||||
INSERT INTO auth.api_key (key_hash, name, created_by, scopes)
|
||||
@@ -48,7 +39,7 @@ pub async fn create_api_key(
|
||||
"#,
|
||||
key_hash,
|
||||
body.name,
|
||||
user_id,
|
||||
claims.user_id(),
|
||||
&body.scopes
|
||||
)
|
||||
.execute(&state.postgres)
|
||||
|
||||
Reference in New Issue
Block a user