cx_sdk/
auth.rs

1// Copyright 2024 Coralogix Ltd.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use 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)]
25/// The authentication context.
26pub struct AuthContext {
27    /// The team level API key.
28    pub(crate) team_level_api_key: ApiKey,
29    /// The user level API key.
30    pub(crate) user_level_api_key: ApiKey,
31}
32
33impl AuthContext {
34    /// Creates a new AuthContext instance.
35    ///
36    /// # Arguments
37    /// * `team_level_api_key` - The team level API key.
38    /// * `user_level_api_key` - The user level API key.
39    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    /// Creates a new AuthContext instance from environment variables.
53    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)]
62/// The API key used for authentication.
63pub struct ApiKey(String);
64
65impl ApiKey {
66    /// Returns the API key as a string.
67    pub fn token(&self) -> &str {
68        &self.0
69    }
70
71    /// Creates a new teams-level API key from the ENV_API_KEY environment variable.
72    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    /// Creates a new user-level API key from the ENV_API_KEY environment variable.
79    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}