Skip to main content

bctx_cloud_core/client/
mod.rs

1pub mod auth;
2pub mod sync;
3pub mod upgrade;
4
5use anyhow::Result;
6use auth::{load_token, TokenStore};
7use upgrade::Tier;
8
9pub struct CloudClient {
10    pub endpoint: String,
11    pub token: Option<TokenStore>,
12}
13
14impl CloudClient {
15    pub fn new(endpoint: impl Into<String>) -> Self {
16        Self {
17            endpoint: endpoint.into(),
18            token: None,
19        }
20    }
21
22    /// Load from persisted token file (returns unauthenticated client if not logged in).
23    pub fn from_env() -> Self {
24        let endpoint = std::env::var("BCTX_CLOUD_ENDPOINT")
25            .unwrap_or_else(|_| "https://api.betterctx.com".to_string());
26        let token = load_token();
27        Self { endpoint, token }
28    }
29
30    pub fn is_authenticated(&self) -> bool {
31        self.token.is_some()
32    }
33
34    pub fn tier(&self) -> Tier {
35        self.token
36            .as_ref()
37            .map(|t| Tier::parse_tier(&t.tier))
38            .unwrap_or(Tier::Free)
39    }
40
41    pub fn bearer_token(&self) -> Option<&str> {
42        self.token.as_ref().map(|t| t.access_token.as_str())
43    }
44
45    pub fn gate(&self, required: &Tier, feature: &str) -> Result<()> {
46        upgrade::gate(&self.tier(), required, feature).map_err(|e| anyhow::anyhow!(e))
47    }
48}