feat(cli): implement api-key create and list
**實作內容**: - Create: 完整實作,生成 API key 並寫入 DB - List: 完整實作,列表顯示所有 API keys - Validate/Revoke/Rotate/Stats: 預留介面,回傳 exit code 1 **關鍵調整**: - 權限寫死為 ["read","write"](預設值) - key_type 使用 serde 序列化(JSON 字串格式) - DB 寫入失敗回傳 Err(不再靜默成功) - 錯誤處理完整,失敗時 exit code ≠ 0 **參考**: - playground.rs:2862-2956 - postgres_db.rs:2928, 2992 - api_key/service.rs:66 **驗收標準**: - api_keys 表新增記錄 - key_prefix 正確 (muser_ / msvc_ 等) - exit code 為 0
This commit is contained in:
+115
-20
@@ -397,38 +397,133 @@ pub async fn handle_api_key(
|
||||
key: Option<String>,
|
||||
key_id: Option<String>,
|
||||
) -> Result<()> {
|
||||
println!("API Key Management:");
|
||||
println!(" Action: {:?}", action);
|
||||
|
||||
// TODO: Implement proper API key management
|
||||
use momentry_core::core::db::PostgresDb;
|
||||
use momentry_core::core::api_key::ApiKeyService;
|
||||
use momentry_core::core::api_key::CreateApiKeyRequest;
|
||||
|
||||
// Connect to database
|
||||
let database_url = std::env::var("DATABASE_URL")
|
||||
.unwrap_or_else(|_| "postgres://accusys@localhost:5432/momentry".to_string());
|
||||
let db = PostgresDb::new(&database_url).await?;
|
||||
let service = ApiKeyService::new(&database_url);
|
||||
|
||||
match action {
|
||||
crate::cli::args::ApiKeyAction::Create => {
|
||||
let name = name.unwrap_or_else(|| "default".to_string());
|
||||
println!("Would create API key with name: {}", name);
|
||||
println!("(API key creation would be implemented here)");
|
||||
let name = name.unwrap_or_else(|| "unnamed-key".to_string());
|
||||
|
||||
// Parse key type
|
||||
let key_type_enum = match key_type.as_deref() {
|
||||
Some("service") => momentry_core::core::api_key::ApiKeyType::Service,
|
||||
Some("integration") => momentry_core::core::api_key::ApiKeyType::Integration,
|
||||
Some("emergency") => momentry_core::core::api_key::ApiKeyType::Emergency,
|
||||
_ => momentry_core::core::api_key::ApiKeyType::User,
|
||||
};
|
||||
|
||||
// Create request with default permissions
|
||||
let request = CreateApiKeyRequest {
|
||||
name: name.clone(),
|
||||
key_type: key_type_enum,
|
||||
user_id: None,
|
||||
service_name: None,
|
||||
permissions: vec!["read".to_string(), "write".to_string()], // Default permissions
|
||||
ttl_days: ttl,
|
||||
};
|
||||
|
||||
// Generate key
|
||||
let response = service.create_key(request)?;
|
||||
|
||||
// Hash key
|
||||
let key_hash = service.hash_key(&response.key);
|
||||
let key_type_str = serde_json::to_string(&key_type_enum)
|
||||
.unwrap_or_else(|_| "\"user\"".to_string());
|
||||
let permissions = serde_json::json!(["read", "write"]); // Default permissions
|
||||
|
||||
// Create config
|
||||
let config = momentry_core::core::db::CreateApiKeyConfig::new(
|
||||
&response.key_id,
|
||||
&key_hash,
|
||||
key_type_enum.prefix(),
|
||||
&name,
|
||||
&key_type_str,
|
||||
)
|
||||
.with_permissions(&permissions)
|
||||
.with_expires_at(response.expires_at);
|
||||
|
||||
// Insert into database - fail on error
|
||||
db.create_api_key(config).await?;
|
||||
|
||||
println!("\n✅ API Key created successfully!");
|
||||
println!("\n┌─────────────────────────────────────────────────────────────────────────────┐");
|
||||
println!("│ ⚠️ IMPORTANT: Save this key now - it will not be shown again! │");
|
||||
println!("└─────────────────────────────────────────────────────────────────────────────┘");
|
||||
println!("\nKey ID: {}", response.key_id);
|
||||
println!("API Key: {}", response.key);
|
||||
println!("Expires: {}", response.expires_at);
|
||||
if !response.warning.is_empty() {
|
||||
println!("\n⚠️ {}", response.warning);
|
||||
}
|
||||
}
|
||||
crate::cli::args::ApiKeyAction::List => {
|
||||
println!("Would list API keys");
|
||||
println!("(API key listing would be implemented here)");
|
||||
match db.list_api_keys().await {
|
||||
Ok(keys) => {
|
||||
println!("\n📋 API Key List");
|
||||
if keys.is_empty() {
|
||||
println!(" (no API keys found)");
|
||||
} else {
|
||||
println!("\n┌────────────────────────────────────────────────────────────────────────────┐");
|
||||
println!(
|
||||
"│ {:8} │ {:20} │ {:12} │ {:8} │ {:15} │",
|
||||
"Status", "Name", "Type", "Usage", "Last Used"
|
||||
);
|
||||
println!("├────────────────────────────────────────────────────────────────────────────┤");
|
||||
for k in &keys {
|
||||
let status = if k.status == "active" {
|
||||
"✓ active"
|
||||
} else {
|
||||
&k.status
|
||||
};
|
||||
let last_used = k
|
||||
.last_used_at
|
||||
.map(|dt| dt.format("%Y-%m-%d %H:%M").to_string())
|
||||
.unwrap_or_else(|| "never".to_string());
|
||||
println!(
|
||||
"│ {:8} │ {:20} │ {:12} │ {:8} │ {:15} │",
|
||||
status,
|
||||
if k.name.len() > 20 {
|
||||
&k.name[..17]
|
||||
} else {
|
||||
&k.name
|
||||
},
|
||||
k.key_type,
|
||||
k.usage_count,
|
||||
last_used
|
||||
);
|
||||
}
|
||||
println!("└────────────────────────────────────────────────────────────────────────────┘");
|
||||
println!("\nTotal: {} key(s)", keys.len());
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("\n❌ Failed to list API keys: {}", e);
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::cli::args::ApiKeyAction::Validate => {
|
||||
let key = key.expect("API key required for validation");
|
||||
println!("Would validate API key: {}...", &key[..8]);
|
||||
println!("(API key validation would be implemented here)");
|
||||
eprintln!("⚠️ Validate action not implemented");
|
||||
std::process::exit(1);
|
||||
}
|
||||
crate::cli::args::ApiKeyAction::Revoke => {
|
||||
let key_id = key_id.expect("Key ID required for revocation");
|
||||
println!("Would revoke API key with ID: {}", key_id);
|
||||
println!("(API key revocation would be implemented here)");
|
||||
eprintln!("⚠️ Revoke action not implemented");
|
||||
std::process::exit(1);
|
||||
}
|
||||
crate::cli::args::ApiKeyAction::Rotate => {
|
||||
let key_id = key_id.expect("Key ID required for rotation");
|
||||
println!("Would rotate API key with ID: {}", key_id);
|
||||
println!("(API key rotation would be implemented here)");
|
||||
eprintln!("⚠️ Rotate action not implemented");
|
||||
std::process::exit(1);
|
||||
}
|
||||
crate::cli::args::ApiKeyAction::Stats => {
|
||||
println!("Would show API key statistics");
|
||||
println!("(API key statistics would be implemented here)");
|
||||
eprintln!("⚠️ Stats action not implemented");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user