1use crate::error::Result;
16use std::fmt::{
17 Debug,
18 Formatter,
19};
20
21const ENV_TEAM_API_KEY: &str = "CORALOGIX_TEAM_API_KEY";
22const ENV_USER_API_KEY: &str = "CORALOGIX_USER_API_KEY";
23
24#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Default)]
25pub struct AuthContext {
27 pub(crate) team_level_api_key: ApiKey,
29 pub(crate) user_level_api_key: ApiKey,
31}
32
33impl AuthContext {
34 pub fn new(team_level_api_key: Option<ApiKey>, user_level_api_key: Option<ApiKey>) -> Self {
40 if team_level_api_key.is_none() {
41 log::warn!("Team level API key is not set. some functionality may not be available.");
42 }
43 if user_level_api_key.is_none() {
44 log::warn!("User level API key is not set. some functionality may not be available.");
45 }
46 AuthContext {
47 team_level_api_key: team_level_api_key.unwrap_or_default(),
48 user_level_api_key: user_level_api_key.unwrap_or_default(),
49 }
50 }
51
52 pub fn from_env() -> Self {
54 AuthContext::new(
55 ApiKey::teams_level_from_env().ok(),
56 ApiKey::user_level_from_env().ok(),
57 )
58 }
59}
60
61#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Default)]
62pub struct ApiKey(String);
64
65impl ApiKey {
66 pub fn token(&self) -> &str {
68 &self.0
69 }
70
71 pub fn teams_level_from_env() -> Result<Self> {
73 std::env::var(ENV_TEAM_API_KEY)
74 .map(ApiKey)
75 .map_err(From::from)
76 }
77
78 pub fn user_level_from_env() -> Result<Self> {
80 std::env::var(ENV_USER_API_KEY)
81 .map(ApiKey)
82 .map_err(From::from)
83 }
84}
85
86impl From<&str> for ApiKey {
87 fn from(s: &str) -> Self {
88 ApiKey(String::from(s))
89 }
90}
91
92impl From<String> for ApiKey {
93 fn from(s: String) -> Self {
94 ApiKey(s)
95 }
96}
97
98impl Debug for ApiKey {
99 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
100 f.write_str("ApiKey(***)")
101 }
102}