use better_auth_core::adapters::DatabaseAdapter;
use better_auth_core::entity::AuthApiKey;
use better_auth_core::{AuthContext, AuthError, AuthResult};
pub fn expires_in_to_at(expires_in_ms: Option<i64>) -> AuthResult<Option<String>> {
match expires_in_ms {
Some(ms) => {
let duration = chrono::Duration::try_milliseconds(ms)
.ok_or_else(|| AuthError::bad_request("expiresIn is out of range"))?;
let dt = chrono::Utc::now()
.checked_add_signed(duration)
.ok_or_else(|| AuthError::bad_request("expiresIn is out of range"))?;
Ok(Some(dt.to_rfc3339()))
}
None => Ok(None),
}
}
pub async fn get_owned_api_key<DB: DatabaseAdapter>(
ctx: &AuthContext<DB>,
key_id: &str,
user_id: &str,
) -> AuthResult<DB::ApiKey> {
let api_key = ctx
.database
.get_api_key_by_id(key_id)
.await?
.ok_or_else(|| AuthError::not_found("API key not found"))?;
if api_key.user_id() != user_id {
return Err(AuthError::not_found("API key not found"));
}
Ok(api_key)
}