Skip to main content

codex_cli/auth/
mod.rs

1pub mod auto_refresh;
2pub mod current;
3pub mod refresh;
4pub mod sync;
5pub mod use_secret;
6
7use anyhow::Result;
8use std::path::Path;
9
10use crate::json;
11use crate::jwt;
12
13pub fn identity_from_auth_file(path: &Path) -> Result<Option<String>> {
14    let value = json::read_json(path)?;
15    let token = token_from_auth_json(&value);
16    let payload = token
17        .and_then(|tok| jwt::decode_payload_json(&tok))
18        .and_then(|payload| jwt::identity_from_payload(&payload));
19    Ok(payload)
20}
21
22pub fn email_from_auth_file(path: &Path) -> Result<Option<String>> {
23    let value = json::read_json(path)?;
24    let token = token_from_auth_json(&value);
25    let payload = token
26        .and_then(|tok| jwt::decode_payload_json(&tok))
27        .and_then(|payload| jwt::email_from_payload(&payload));
28    Ok(payload)
29}
30
31pub fn account_id_from_auth_file(path: &Path) -> Result<Option<String>> {
32    let value = json::read_json(path)?;
33    let account = json::string_at(&value, &["tokens", "account_id"])
34        .or_else(|| json::string_at(&value, &["account_id"]));
35    Ok(account)
36}
37
38pub fn last_refresh_from_auth_file(path: &Path) -> Result<Option<String>> {
39    let value = json::read_json(path)?;
40    Ok(json::string_at(&value, &["last_refresh"]))
41}
42
43pub fn identity_key_from_auth_file(path: &Path) -> Result<Option<String>> {
44    let identity = identity_from_auth_file(path)?;
45    let identity = match identity {
46        Some(value) => value,
47        None => return Ok(None),
48    };
49    let account_id = account_id_from_auth_file(path)?;
50    let key = match account_id {
51        Some(account) => format!("{}::{}", identity, account),
52        None => identity,
53    };
54    Ok(Some(key))
55}
56
57fn token_from_auth_json(value: &serde_json::Value) -> Option<String> {
58    json::string_at(value, &["tokens", "id_token"])
59        .or_else(|| json::string_at(value, &["tokens", "access_token"]))
60}