flagsmith_flag_engine/environments/
mod.rs1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3
4use super::features;
5use super::identities;
6use super::projects;
7use super::utils::datetime;
8pub mod builders;
9
10#[derive(Serialize, Deserialize, Debug, Clone)]
11pub struct Environment {
12 pub id: u32,
13 pub api_key: String,
14 pub name: String,
15 pub project: projects::Project,
16 pub feature_states: Vec<features::FeatureState>,
17
18 #[serde(default)]
19 pub identity_overrides: Vec<identities::Identity>,
20}
21
22#[derive(Serialize, Deserialize, Debug)]
23pub struct EnvironmentAPIKey {
24 pub id: u32,
25 pub key: String,
26 pub active: bool,
27
28 #[serde(with = "datetime")]
29 pub created_at: DateTime<Utc>,
30 pub name: String,
31 pub client_api_key: String,
32 pub expires_at: Option<DateTime<Utc>>,
33}
34
35impl EnvironmentAPIKey {
36 pub fn is_valid(&self) -> bool {
37 if !self.active {
38 return false;
39 }
40 match self.expires_at {
41 None => return true,
42 Some(expires_at) if expires_at > Utc::now() => return true,
43 Some(_) => return false,
44 }
45 }
46}
47#[cfg(test)]
48mod tests {
49 use super::*;
50
51 #[test]
52 fn api_key_is_valid_returns_true_if_key_is_active_and_expired_is_null() {
53 let api_key_json = r#"{
54 "key": "ser.test_key",
55 "active": true,
56 "created_at": "2022-03-02T12:31:05.309861+00:00",
57 "client_api_key": "client_key",
58 "id": 1,
59 "name": "api key 1",
60 "expires_at": null
61 }"#;
62 let api_key: EnvironmentAPIKey = serde_json::from_str(api_key_json).unwrap();
63
64 assert!(api_key.is_valid())
65 }
66
67 #[test]
68 fn api_key_is_valid_returns_false_if_key_is_not_active() {
69 let api_key_json = r#"{
70 "key": "ser.test_key",
71 "active": false,
72 "created_at": "2022-03-02T12:31:05.309861+00:00",
73 "client_api_key": "client_key",
74 "id": 1,
75 "name": "api key 1",
76 "expires_at": null
77 }"#;
78 let api_key: EnvironmentAPIKey = serde_json::from_str(api_key_json).unwrap();
79
80 assert_eq!(api_key.is_valid(), false)
81 }
82
83 #[test]
84 fn api_key_is_valid_returns_false_if_key_is_active_but_expired() {
85 let api_key_json = r#"{
86 "key": "ser.test_key",
87 "active": true,
88 "created_at": "2022-03-02T12:31:05.309861+00:00",
89 "client_api_key": "client_key",
90 "id": 1,
91 "name": "api key 1",
92 "expires_at": "2022-03-02T12:32:05.309861+00:00"
93 }"#;
94 let api_key: EnvironmentAPIKey = serde_json::from_str(api_key_json).unwrap();
95
96 assert_eq!(api_key.is_valid(), false)
97 }
98}