Skip to main content

alibi_sqlx/store/
jwks.rs

1use super::SqlxStore;
2use super::entities::jwk::Model;
3use crate::model::{self, ActiveRow};
4use crate::pool::Exec;
5use crate::schema::AuthSchema;
6use alibi_core::error::AuthResult;
7use alibi_core::store::JwkStore;
8use alibi_core::types::{CreateJwk, Jwk};
9use async_trait::async_trait;
10
11impl<S: AuthSchema> SqlxStore<S> {
12    pub(super) async fn list_jwks_with(&self, exec: Exec<'_>) -> AuthResult<Vec<Jwk>> {
13        let mut sql = model::select_model::<Model>(exec);
14        sql.push(" LIMIT ");
15        sql.bind(self.find_many_limit());
16        Ok(exec
17            .fetch_all::<Model>(sql)
18            .await?
19            .into_iter()
20            .map(Into::into)
21            .collect())
22    }
23
24    pub(super) async fn get_jwk_with(&self, exec: Exec<'_>, id: &str) -> AuthResult<Option<Jwk>> {
25        let mut sql = model::by_id::<Model>(exec, id);
26        model::limit_one(&mut sql);
27        Ok(exec.fetch_optional::<Model>(sql).await?.map(Into::into))
28    }
29
30    pub(super) async fn create_jwk_with(&self, exec: Exec<'_>, data: CreateJwk) -> AuthResult<Jwk> {
31        let mut active = ActiveRow::new();
32        active.set(
33            "id",
34            data.id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
35        );
36        active.set("public_key", data.public_key);
37        active.set("private_key", data.private_key);
38        active.set("created_at", data.created_at);
39        active.set("expires_at", data.expires_at);
40        active.set("alg", data.alg);
41        active.set("crv", data.crv);
42        model::insert::<Model>(exec, &active).await.map(Into::into)
43    }
44}
45
46#[async_trait]
47impl<S: AuthSchema> JwkStore for SqlxStore<S> {
48    async fn list_jwks(&self) -> AuthResult<Vec<Jwk>> {
49        self.list_jwks_with(self.exec()).await
50    }
51    async fn get_jwk_by_id(&self, id: &str) -> AuthResult<Option<Jwk>> {
52        self.get_jwk_with(self.exec(), id).await
53    }
54    async fn create_jwk(&self, data: CreateJwk) -> AuthResult<Jwk> {
55        self.create_jwk_with(self.exec(), data).await
56    }
57}