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            match data.id {
35                Some(id) => id,
36                None => self
37                    .generated_id(exec, "jwks", "jwks", "id")
38                    .await?
39                    .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()),
40            },
41        );
42        active.set("public_key", data.public_key);
43        active.set("private_key", data.private_key);
44        active.set("created_at", data.created_at);
45        active.set("expires_at", data.expires_at);
46        active.set("alg", data.alg);
47        active.set("crv", data.crv);
48        model::insert::<Model>(exec, &active).await.map(Into::into)
49    }
50}
51
52#[async_trait]
53impl<S: AuthSchema> JwkStore for SqlxStore<S> {
54    async fn list_jwks(&self) -> AuthResult<Vec<Jwk>> {
55        self.list_jwks_with(self.exec()).await
56    }
57    async fn get_jwk_by_id(&self, id: &str) -> AuthResult<Option<Jwk>> {
58        self.get_jwk_with(self.exec(), id).await
59    }
60    async fn create_jwk(&self, data: CreateJwk) -> AuthResult<Jwk> {
61        self.create_jwk_with(self.exec(), data).await
62    }
63}