junobuild_auth/openid/
impls.rs1use crate::openid::jwt::types::cert::Jwks;
2use crate::openid::jwt::types::token::Claims;
3use crate::openid::types::interface::{OpenIdCredential, OpenIdCredentialKey};
4use crate::openid::types::provider::{OpenIdCertificate, OpenIdProvider};
5use ic_cdk::api::time;
6use jsonwebtoken::TokenData;
7use junobuild_shared::data::version::next_version;
8use junobuild_shared::types::state::{Version, Versioned};
9use std::fmt::{Display, Formatter, Result as FmtResult};
10
11impl From<TokenData<Claims>> for OpenIdCredential {
12 fn from(token: TokenData<Claims>) -> Self {
13 Self {
14 sub: token.claims.sub,
15 iss: token.claims.iss,
16 email: token.claims.email,
17 name: token.claims.name,
18 given_name: token.claims.given_name,
19 family_name: token.claims.family_name,
20 picture: token.claims.picture,
21 locale: token.claims.locale,
22 }
23 }
24}
25
26impl<'a> From<&'a OpenIdCredential> for OpenIdCredentialKey<'a> {
27 fn from(credential: &'a OpenIdCredential) -> Self {
28 Self {
29 sub: &credential.sub,
30 iss: &credential.iss,
31 }
32 }
33}
34
35impl OpenIdProvider {
36 pub fn jwks_url(&self) -> &'static str {
37 match self {
38 Self::Google => "https://www.googleapis.com/oauth2/v3/certs",
39 }
40 }
41
42 pub fn issuers(&self) -> &[&'static str] {
43 match self {
44 OpenIdProvider::Google => &["https://accounts.google.com", "accounts.google.com"],
45 }
46 }
47}
48
49impl Versioned for OpenIdCertificate {
50 fn version(&self) -> Option<Version> {
51 self.version
52 }
53}
54
55impl OpenIdCertificate {
56 fn get_next_version(current_certificate: &Option<OpenIdCertificate>) -> Version {
57 next_version(current_certificate)
58 }
59
60 pub fn init(jwks: &Jwks) -> Self {
61 let now = time();
62
63 let version = Self::get_next_version(&None);
64
65 Self {
66 jwks: jwks.clone(),
67 created_at: now,
68 updated_at: now,
69 version: Some(version),
70 }
71 }
72
73 pub fn update(current_certificate: &OpenIdCertificate, jwks: &Jwks) -> Self {
74 let now = time();
75
76 let version = Self::get_next_version(&Some(current_certificate.clone()));
77
78 Self {
79 jwks: jwks.clone(),
80 updated_at: now,
81 version: Some(version),
82 ..current_certificate.clone()
83 }
84 }
85}
86
87impl Display for OpenIdProvider {
88 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
89 match self {
90 OpenIdProvider::Google => write!(f, "Google"),
91 }
92 }
93}