junobuild_auth/state/
impls.rs

1use crate::openid::types::provider::OpenIdCertificate;
2use crate::state::types::config::AuthenticationConfig;
3use crate::state::types::interface::SetAuthenticationConfig;
4use crate::state::types::state::{OpenIdCachedCertificate, OpenIdLastFetchAttempt};
5use ic_cdk::api::time;
6use junobuild_shared::data::version::next_version;
7use junobuild_shared::types::state::{Timestamp, Version, Versioned};
8
9impl AuthenticationConfig {
10    pub fn prepare(
11        current_config: &Option<AuthenticationConfig>,
12        user_config: &SetAuthenticationConfig,
13    ) -> Self {
14        let now = time();
15
16        let created_at: Timestamp = match current_config {
17            None => now,
18            Some(current_doc) => current_doc.created_at.unwrap_or(now),
19        };
20
21        let version = next_version(current_config);
22
23        let updated_at: Timestamp = now;
24
25        AuthenticationConfig {
26            internet_identity: user_config.internet_identity.clone(),
27            openid: user_config.openid.clone(),
28            rules: user_config.rules.clone(),
29            created_at: Some(created_at),
30            updated_at: Some(updated_at),
31            version: Some(version),
32        }
33    }
34}
35
36impl Versioned for AuthenticationConfig {
37    fn version(&self) -> Option<Version> {
38        self.version
39    }
40}
41
42impl AuthenticationConfig {
43    pub fn openid_enabled(&self) -> bool {
44        self.openid
45            .as_ref()
46            .is_some_and(|openid| !openid.providers.is_empty())
47    }
48}
49
50impl OpenIdCachedCertificate {
51    pub fn init() -> Self {
52        Self {
53            certificate: None,
54            last_fetch_attempt: OpenIdLastFetchAttempt {
55                at: time(),
56                streak_count: 1,
57            },
58        }
59    }
60
61    pub fn record_attempt(&mut self, reset_streak: bool) {
62        self.last_fetch_attempt.at = time();
63
64        if reset_streak {
65            self.last_fetch_attempt.streak_count = 1;
66        } else {
67            self.last_fetch_attempt.streak_count =
68                self.last_fetch_attempt.streak_count.saturating_add(1);
69        }
70    }
71
72    pub fn update_certificate(&mut self, certificate: &OpenIdCertificate) {
73        self.certificate = Some(certificate.clone());
74        self.last_fetch_attempt.streak_count = 0;
75    }
76}