Skip to content

Commit

Permalink
Ensure result order when searching for sso_user
Browse files Browse the repository at this point in the history
  • Loading branch information
Timshel committed Nov 11, 2024
1 parent a87e12f commit a8f3aa4
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions src/db/models/user.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::util::{format_date, get_uuid, retry};
use chrono::{NaiveDateTime, TimeDelta, Utc};
use serde_json::Value;
use std::cmp::Ordering;

use crate::crypto;
use crate::CONFIG;
Expand Down Expand Up @@ -487,7 +488,8 @@ impl SsoUser {
}

// Written as an union to make the query more lisible than using an `or_filter`.
// But `first()` does not appear to work with `union()` so we use `load()`.
// If there is a match on identifier and email we want the identifier match.
// We sort results in code since UNION does not garanty order and DBs order NULL differently.
pub async fn find_by_identifier_or_email(
identifier: &str,
mail: &str,
Expand All @@ -496,7 +498,7 @@ impl SsoUser {
let lower_mail = mail.to_lowercase();

db_run! {conn: {
users::table
let mut res = users::table
.inner_join(sso_users::table)
.select(<(UserDb, Option<SsoUserDb>)>::as_select())
.filter(sso_users::identifier.eq(identifier))
Expand All @@ -509,8 +511,17 @@ impl SsoUser {
.load(conn)
.expect("Error searching user by SSO identifier and email")
.into_iter()
.next()
.map(|(user, sso_user)| { (user.from_db(), sso_user.from_db()) })
.collect::<Vec<(User, Option<SsoUser>)>>();

res.sort_by(|(_, sso_user), _| {
match sso_user {
Some(db_sso_user) if db_sso_user.identifier == identifier => Ordering::Less,
_ => Ordering::Greater,
}
});

res.into_iter().next()
}}
}
}

0 comments on commit a8f3aa4

Please sign in to comment.