headless_lms_models/
study_registry_registrars.rs1use crate::prelude::*;
2
3#[derive(Clone, PartialEq, Deserialize, Serialize)]
4pub struct StudyRegistryRegistrar {
5 pub id: Uuid,
6 pub created_at: DateTime<Utc>,
7 pub updated_at: DateTime<Utc>,
8 pub deleted_at: Option<DateTime<Utc>>,
9 pub name: String,
10 pub secret_key: String,
11}
12
13pub async fn insert(
14 conn: &mut PgConnection,
15 pkey_policy: PKeyPolicy<Uuid>,
16 name: &str,
17 secret_key: &str,
18) -> ModelResult<Uuid> {
19 let res = sqlx::query!(
20 "
21INSERT INTO study_registry_registrars (id, name, secret_key)
22VALUES ($1, $2, $3)
23RETURNING id
24 ",
25 pkey_policy.into_uuid(),
26 name,
27 secret_key
28 )
29 .fetch_one(conn)
30 .await?;
31 Ok(res.id)
32}
33
34pub async fn get_by_id(conn: &mut PgConnection, id: Uuid) -> ModelResult<StudyRegistryRegistrar> {
35 let res = sqlx::query_as!(
36 StudyRegistryRegistrar,
37 "
38SELECT *
39FROM study_registry_registrars
40WHERE id = $1
41 AND deleted_at IS NULL
42 ",
43 id,
44 )
45 .fetch_one(conn)
46 .await?;
47 Ok(res)
48}
49
50pub async fn get_by_secret_key(
51 conn: &mut PgConnection,
52 secret_key: &str,
53) -> ModelResult<StudyRegistryRegistrar> {
54 let res = sqlx::query_as!(
55 StudyRegistryRegistrar,
56 "
57SELECT *
58FROM study_registry_registrars
59WHERE secret_key = $1
60 AND deleted_at IS NULL
61 ",
62 secret_key
63 )
64 .fetch_one(conn)
65 .await?;
66 Ok(res)
67}
68
69pub async fn delete(conn: &mut PgConnection, id: Uuid) -> ModelResult<()> {
70 sqlx::query!(
71 "
72UPDATE study_registry_registrars
73SET deleted_at = now()
74WHERE id = $1
75AND deleted_at IS NULL
76 ",
77 id,
78 )
79 .execute(conn)
80 .await?;
81 Ok(())
82}
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87 use crate::test_helper::*;
88
89 #[tokio::test]
90 async fn secret_key_needs_to_be_long_enough() {
91 insert_data!(:tx);
92 let id_1 = Uuid::parse_str("88eff75b-4c8f-46f7-a857-9d804b5ec054").unwrap();
93 let res = insert(
94 tx.as_mut(),
95 PKeyPolicy::Fixed(id_1),
96 "test registrar",
97 "12345",
98 )
99 .await;
100 assert!(res.is_err(), "Expected too short key to produce error.");
101 }
102
103 #[tokio::test]
104 async fn secret_key_needs_to_be_unique() {
105 insert_data!(:tx);
106 let id_1 = Uuid::parse_str("88eff75b-4c8f-46f7-a857-9d804b5ec054").unwrap();
107 let res = insert(
108 tx.as_mut(),
109 PKeyPolicy::Fixed(id_1),
110 "test registrar",
111 "123456789-123456",
112 )
113 .await;
114 assert!(res.is_ok(), "Expected insertion to succeed.");
115
116 let id_2 = Uuid::parse_str("d06abb84-0cad-4372-ad2a-7f87d3c1e420").unwrap();
117 let res = insert(
118 tx.as_mut(),
119 PKeyPolicy::Fixed(id_2),
120 "test registrar 2",
121 "123456789-123456",
122 )
123 .await;
124 assert!(
125 res.is_err(),
126 "Expected insertion to fail with duplicate secret key."
127 );
128 }
129}