Skip to main content

codex_cli/auth/
mod.rs

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