junobuild_auth/state/
impls.rs1use crate::openid::types::provider::OpenIdCertificate;
2use crate::state::types::automation::AutomationConfig;
3use crate::state::types::config::AuthenticationConfig;
4use crate::state::types::interface::{SetAuthenticationConfig, SetAutomationConfig};
5use crate::state::types::state::{OpenIdCachedCertificate, OpenIdLastFetchAttempt};
6use ic_cdk::api::time;
7use junobuild_shared::data::version::next_version;
8use junobuild_shared::types::state::{Timestamp, Version, Versioned};
9
10impl AuthenticationConfig {
11 pub fn prepare(
12 current_config: &Option<AuthenticationConfig>,
13 user_config: &SetAuthenticationConfig,
14 ) -> Self {
15 let now = time();
16
17 let created_at: Timestamp = match current_config {
18 None => now,
19 Some(current_doc) => current_doc.created_at.unwrap_or(now),
20 };
21
22 let version = next_version(current_config);
23
24 let updated_at: Timestamp = now;
25
26 AuthenticationConfig {
27 internet_identity: user_config.internet_identity.clone(),
28 openid: user_config.openid.clone(),
29 rules: user_config.rules.clone(),
30 created_at: Some(created_at),
31 updated_at: Some(updated_at),
32 version: Some(version),
33 }
34 }
35}
36
37impl Versioned for AuthenticationConfig {
38 fn version(&self) -> Option<Version> {
39 self.version
40 }
41}
42
43impl AuthenticationConfig {
44 pub fn openid_enabled(&self) -> bool {
45 self.openid
46 .as_ref()
47 .is_some_and(|openid| !openid.providers.is_empty())
48 }
49}
50
51impl AutomationConfig {
52 pub fn prepare(
53 current_config: &Option<AutomationConfig>,
54 user_config: &SetAutomationConfig,
55 ) -> Self {
56 let now = time();
57
58 let created_at: Timestamp = match current_config {
59 None => now,
60 Some(current_doc) => current_doc.created_at.unwrap_or(now),
61 };
62
63 let version = next_version(current_config);
64
65 let updated_at: Timestamp = now;
66
67 AutomationConfig {
68 openid: user_config.openid.clone(),
69 created_at: Some(created_at),
70 updated_at: Some(updated_at),
71 version: Some(version),
72 }
73 }
74}
75
76impl Versioned for AutomationConfig {
77 fn version(&self) -> Option<Version> {
78 self.version
79 }
80}
81
82impl OpenIdCachedCertificate {
83 pub fn init() -> Self {
84 Self {
85 certificate: None,
86 last_fetch_attempt: OpenIdLastFetchAttempt {
87 at: time(),
88 streak_count: 1,
89 },
90 }
91 }
92
93 pub fn record_attempt(&mut self, reset_streak: bool) {
94 self.last_fetch_attempt.at = time();
95
96 if reset_streak {
97 self.last_fetch_attempt.streak_count = 1;
98 } else {
99 self.last_fetch_attempt.streak_count =
100 self.last_fetch_attempt.streak_count.saturating_add(1);
101 }
102 }
103
104 pub fn update_certificate(&mut self, certificate: &OpenIdCertificate) {
105 self.certificate = Some(certificate.clone());
106 self.last_fetch_attempt.streak_count = 0;
107 }
108}