users.rs

  1use chrono::NaiveDateTime;
  2
  3use super::*;
  4
  5impl Database {
  6    /// Creates a new user.
  7    pub async fn create_user(
  8        &self,
  9        email_address: &str,
 10        admin: bool,
 11        params: NewUserParams,
 12    ) -> Result<NewUserResult> {
 13        self.transaction(|tx| async {
 14            let tx = tx;
 15            let user = user::Entity::insert(user::ActiveModel {
 16                email_address: ActiveValue::set(Some(email_address.into())),
 17                github_login: ActiveValue::set(params.github_login.clone()),
 18                github_user_id: ActiveValue::set(params.github_user_id),
 19                admin: ActiveValue::set(admin),
 20                metrics_id: ActiveValue::set(Uuid::new_v4()),
 21                ..Default::default()
 22            })
 23            .on_conflict(
 24                OnConflict::column(user::Column::GithubUserId)
 25                    .update_columns([
 26                        user::Column::Admin,
 27                        user::Column::EmailAddress,
 28                        user::Column::GithubLogin,
 29                    ])
 30                    .to_owned(),
 31            )
 32            .exec_with_returning(&*tx)
 33            .await?;
 34
 35            Ok(NewUserResult {
 36                user_id: user.id,
 37                metrics_id: user.metrics_id.to_string(),
 38                signup_device_id: None,
 39                inviting_user_id: None,
 40            })
 41        })
 42        .await
 43    }
 44
 45    /// Returns a user by ID. There are no access checks here, so this should only be used internally.
 46    pub async fn get_user_by_id(&self, id: UserId) -> Result<Option<user::Model>> {
 47        self.transaction(|tx| async move { Ok(user::Entity::find_by_id(id).one(&*tx).await?) })
 48            .await
 49    }
 50
 51    /// Returns all users by ID. There are no access checks here, so this should only be used internally.
 52    pub async fn get_users_by_ids(&self, ids: Vec<UserId>) -> Result<Vec<user::Model>> {
 53        if ids.len() >= 10000_usize {
 54            return Err(anyhow!("too many users"))?;
 55        }
 56        self.transaction(|tx| async {
 57            let tx = tx;
 58            Ok(user::Entity::find()
 59                .filter(user::Column::Id.is_in(ids.iter().copied()))
 60                .all(&*tx)
 61                .await?)
 62        })
 63        .await
 64    }
 65
 66    /// Returns a user by email address. There are no access checks here, so this should only be used internally.
 67    pub async fn get_user_by_email(&self, email: &str) -> Result<Option<User>> {
 68        self.transaction(|tx| async move {
 69            Ok(user::Entity::find()
 70                .filter(user::Column::EmailAddress.eq(email))
 71                .one(&*tx)
 72                .await?)
 73        })
 74        .await
 75    }
 76
 77    /// Returns a user by GitHub user ID. There are no access checks here, so this should only be used internally.
 78    pub async fn get_user_by_github_user_id(&self, github_user_id: i32) -> Result<Option<User>> {
 79        self.transaction(|tx| async move {
 80            Ok(user::Entity::find()
 81                .filter(user::Column::GithubUserId.eq(github_user_id))
 82                .one(&*tx)
 83                .await?)
 84        })
 85        .await
 86    }
 87
 88    /// Returns a user by GitHub login. There are no access checks here, so this should only be used internally.
 89    pub async fn get_user_by_github_login(&self, github_login: &str) -> Result<Option<User>> {
 90        self.transaction(|tx| async move {
 91            Ok(user::Entity::find()
 92                .filter(user::Column::GithubLogin.eq(github_login))
 93                .one(&*tx)
 94                .await?)
 95        })
 96        .await
 97    }
 98
 99    pub async fn get_or_create_user_by_github_account(
100        &self,
101        github_login: &str,
102        github_user_id: i32,
103        github_email: Option<&str>,
104        github_user_created_at: Option<DateTimeUtc>,
105        initial_channel_id: Option<ChannelId>,
106    ) -> Result<User> {
107        self.transaction(|tx| async move {
108            self.get_or_create_user_by_github_account_tx(
109                github_login,
110                github_user_id,
111                github_email,
112                github_user_created_at.map(|created_at| created_at.naive_utc()),
113                initial_channel_id,
114                &tx,
115            )
116            .await
117        })
118        .await
119    }
120
121    pub async fn get_or_create_user_by_github_account_tx(
122        &self,
123        github_login: &str,
124        github_user_id: i32,
125        github_email: Option<&str>,
126        github_user_created_at: Option<NaiveDateTime>,
127        initial_channel_id: Option<ChannelId>,
128        tx: &DatabaseTransaction,
129    ) -> Result<User> {
130        if let Some(user_by_github_user_id) = user::Entity::find()
131            .filter(user::Column::GithubUserId.eq(github_user_id))
132            .one(tx)
133            .await?
134        {
135            let mut user_by_github_user_id = user_by_github_user_id.into_active_model();
136            user_by_github_user_id.github_login = ActiveValue::set(github_login.into());
137            if github_user_created_at.is_some() {
138                user_by_github_user_id.github_user_created_at =
139                    ActiveValue::set(github_user_created_at);
140            }
141            Ok(user_by_github_user_id.update(tx).await?)
142        } else if let Some(user_by_github_login) = user::Entity::find()
143            .filter(user::Column::GithubLogin.eq(github_login))
144            .one(tx)
145            .await?
146        {
147            let mut user_by_github_login = user_by_github_login.into_active_model();
148            user_by_github_login.github_user_id = ActiveValue::set(github_user_id);
149            if github_user_created_at.is_some() {
150                user_by_github_login.github_user_created_at =
151                    ActiveValue::set(github_user_created_at);
152            }
153            Ok(user_by_github_login.update(tx).await?)
154        } else {
155            let user = user::Entity::insert(user::ActiveModel {
156                email_address: ActiveValue::set(github_email.map(|email| email.into())),
157                github_login: ActiveValue::set(github_login.into()),
158                github_user_id: ActiveValue::set(github_user_id),
159                github_user_created_at: ActiveValue::set(github_user_created_at),
160                admin: ActiveValue::set(false),
161                invite_count: ActiveValue::set(0),
162                invite_code: ActiveValue::set(None),
163                metrics_id: ActiveValue::set(Uuid::new_v4()),
164                ..Default::default()
165            })
166            .exec_with_returning(tx)
167            .await?;
168            if let Some(channel_id) = initial_channel_id {
169                channel_member::Entity::insert(channel_member::ActiveModel {
170                    id: ActiveValue::NotSet,
171                    channel_id: ActiveValue::Set(channel_id),
172                    user_id: ActiveValue::Set(user.id),
173                    accepted: ActiveValue::Set(true),
174                    role: ActiveValue::Set(ChannelRole::Guest),
175                })
176                .exec(tx)
177                .await?;
178            }
179            Ok(user)
180        }
181    }
182
183    /// get_all_users returns the next page of users. To get more call again with
184    /// the same limit and the page incremented by 1.
185    pub async fn get_all_users(&self, page: u32, limit: u32) -> Result<Vec<User>> {
186        self.transaction(|tx| async move {
187            Ok(user::Entity::find()
188                .order_by_asc(user::Column::GithubLogin)
189                .limit(limit as u64)
190                .offset(page as u64 * limit as u64)
191                .all(&*tx)
192                .await?)
193        })
194        .await
195    }
196
197    /// Returns the metrics id for the user.
198    pub async fn get_user_metrics_id(&self, id: UserId) -> Result<String> {
199        #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
200        enum QueryAs {
201            MetricsId,
202        }
203
204        self.transaction(|tx| async move {
205            let metrics_id: Uuid = user::Entity::find_by_id(id)
206                .select_only()
207                .column(user::Column::MetricsId)
208                .into_values::<_, QueryAs>()
209                .one(&*tx)
210                .await?
211                .ok_or_else(|| anyhow!("could not find user"))?;
212            Ok(metrics_id.to_string())
213        })
214        .await
215    }
216
217    /// Sets "connected_once" on the user for analytics.
218    pub async fn set_user_connected_once(&self, id: UserId, connected_once: bool) -> Result<()> {
219        self.transaction(|tx| async move {
220            user::Entity::update_many()
221                .filter(user::Column::Id.eq(id))
222                .set(user::ActiveModel {
223                    connected_once: ActiveValue::set(connected_once),
224                    ..Default::default()
225                })
226                .exec(&*tx)
227                .await?;
228            Ok(())
229        })
230        .await
231    }
232
233    /// Sets "accepted_tos_at" on the user to the given timestamp.
234    pub async fn set_user_accepted_tos_at(
235        &self,
236        id: UserId,
237        accepted_tos_at: Option<DateTime>,
238    ) -> Result<()> {
239        self.transaction(|tx| async move {
240            user::Entity::update_many()
241                .filter(user::Column::Id.eq(id))
242                .set(user::ActiveModel {
243                    accepted_tos_at: ActiveValue::set(accepted_tos_at),
244                    ..Default::default()
245                })
246                .exec(&*tx)
247                .await?;
248            Ok(())
249        })
250        .await
251    }
252
253    /// hard delete the user.
254    pub async fn destroy_user(&self, id: UserId) -> Result<()> {
255        self.transaction(|tx| async move {
256            access_token::Entity::delete_many()
257                .filter(access_token::Column::UserId.eq(id))
258                .exec(&*tx)
259                .await?;
260            user::Entity::delete_by_id(id).exec(&*tx).await?;
261            Ok(())
262        })
263        .await
264    }
265
266    /// Find users where github_login ILIKE name_query.
267    pub async fn fuzzy_search_users(&self, name_query: &str, limit: u32) -> Result<Vec<User>> {
268        self.transaction(|tx| async {
269            let tx = tx;
270            let like_string = Self::fuzzy_like_string(name_query);
271            let query = "
272                SELECT users.*
273                FROM users
274                WHERE github_login ILIKE $1
275                ORDER BY github_login <-> $2
276                LIMIT $3
277            ";
278
279            Ok(user::Entity::find()
280                .from_raw_sql(Statement::from_sql_and_values(
281                    self.pool.get_database_backend(),
282                    query,
283                    vec![like_string.into(), name_query.into(), limit.into()],
284                ))
285                .all(&*tx)
286                .await?)
287        })
288        .await
289    }
290
291    /// fuzzy_like_string creates a string for matching in-order using fuzzy_search_users.
292    /// e.g. "cir" would become "%c%i%r%"
293    pub fn fuzzy_like_string(string: &str) -> String {
294        let mut result = String::with_capacity(string.len() * 2 + 1);
295        for c in string.chars() {
296            if c.is_alphanumeric() {
297                result.push('%');
298                result.push(c);
299            }
300        }
301        result.push('%');
302        result
303    }
304
305    /// Creates a new feature flag.
306    pub async fn create_user_flag(&self, flag: &str, enabled_for_all: bool) -> Result<FlagId> {
307        self.transaction(|tx| async move {
308            let flag = feature_flag::Entity::insert(feature_flag::ActiveModel {
309                flag: ActiveValue::set(flag.to_string()),
310                enabled_for_all: ActiveValue::set(enabled_for_all),
311                ..Default::default()
312            })
313            .exec(&*tx)
314            .await?
315            .last_insert_id;
316
317            Ok(flag)
318        })
319        .await
320    }
321
322    /// Add the given user to the feature flag
323    pub async fn add_user_flag(&self, user: UserId, flag: FlagId) -> Result<()> {
324        self.transaction(|tx| async move {
325            user_feature::Entity::insert(user_feature::ActiveModel {
326                user_id: ActiveValue::set(user),
327                feature_id: ActiveValue::set(flag),
328            })
329            .exec(&*tx)
330            .await?;
331
332            Ok(())
333        })
334        .await
335    }
336
337    /// Returns the active flags for the user.
338    pub async fn get_user_flags(&self, user: UserId) -> Result<Vec<String>> {
339        self.transaction(|tx| async move {
340            #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
341            enum QueryAs {
342                Flag,
343            }
344
345            let flags_enabled_for_all = feature_flag::Entity::find()
346                .filter(feature_flag::Column::EnabledForAll.eq(true))
347                .select_only()
348                .column(feature_flag::Column::Flag)
349                .into_values::<_, QueryAs>()
350                .all(&*tx)
351                .await?;
352
353            let flags_enabled_for_user = user::Model {
354                id: user,
355                ..Default::default()
356            }
357            .find_linked(user::UserFlags)
358            .select_only()
359            .column(feature_flag::Column::Flag)
360            .into_values::<_, QueryAs>()
361            .all(&*tx)
362            .await?;
363
364            let mut all_flags = HashSet::from_iter(flags_enabled_for_all);
365            all_flags.extend(flags_enabled_for_user);
366
367            Ok(all_flags.into_iter().collect())
368        })
369        .await
370    }
371
372    pub async fn get_users_missing_github_user_created_at(&self) -> Result<Vec<user::Model>> {
373        self.transaction(|tx| async move {
374            Ok(user::Entity::find()
375                .filter(user::Column::GithubUserCreatedAt.is_null())
376                .all(&*tx)
377                .await?)
378        })
379        .await
380    }
381}