feat(usage): add support for access token and user ID in usage scripts

Add optional accessToken and userId fields to usage query scripts,
enabling queries to authenticated endpoints like /api/user/self.

Changes:
- Add accessToken and userId fields to UsageScript type (frontend & backend)
- Extend script engine to support {{accessToken}} and {{userId}} placeholders
- Update NewAPI preset template to use /api/user/self endpoint
- Add UI inputs for access token and user ID in UsageScriptModal
- Pass new parameters through service layer to script executor

This allows users to query usage data from endpoints that require
login credentials, providing more accurate balance information for
services like NewAPI/OneAPI platforms.
This commit is contained in:
Jason
2025-11-04 11:30:14 +08:00
parent ccb011fba1
commit 49c2855b10
5 changed files with 86 additions and 27 deletions

View File

@@ -717,7 +717,7 @@ impl ProviderService {
app_type: AppType,
provider_id: &str,
) -> Result<UsageResult, AppError> {
let (provider, script_code, timeout) = {
let (provider, script_code, timeout, access_token, user_id) = {
let config = state.config.read().map_err(AppError::from)?;
let manager = config
.get_manager(&app_type)
@@ -727,7 +727,7 @@ impl ProviderService {
.get(provider_id)
.cloned()
.ok_or_else(|| AppError::ProviderNotFound(provider_id.to_string()))?;
let (script_code, timeout) = {
let (script_code, timeout, access_token, user_id) = {
let usage_script = provider
.meta
.as_ref()
@@ -749,15 +749,26 @@ impl ProviderService {
(
usage_script.code.clone(),
usage_script.timeout.unwrap_or(10),
usage_script.access_token.clone(),
usage_script.user_id.clone(),
)
};
(provider, script_code, timeout)
(provider, script_code, timeout, access_token, user_id)
};
let (api_key, base_url) = Self::extract_credentials(&provider, &app_type)?;
match usage_script::execute_usage_script(&script_code, &api_key, &base_url, timeout).await {
match usage_script::execute_usage_script(
&script_code,
&api_key,
&base_url,
timeout,
access_token.as_deref(),
user_id.as_deref(),
)
.await
{
Ok(data) => {
let usage_list: Vec<UsageData> = if data.is_array() {
serde_json::from_value(data)