From 76743aee48263f459ad4c8f3fc6a77bd2e482f35 Mon Sep 17 00:00:00 2001 From: Michael Powers Date: Mon, 13 Jan 2020 21:53:57 -0500 Subject: [PATCH 1/2] Fixes #635 - Unique constraint violation when using U2F tokens on PostgreSQL Because of differences in how .on_conflict() works compared to .replace_into() the PostgreSQL backend wasn't correctly ensuring the unique constraint on user_uuid and atype wasn't getting violated. This change simply issues a DELETE on the unique constraint prior to the insert to ensure uniqueness. PostgreSQL does not support multiple constraints in ON CONFLICT clauses. --- src/db/models/two_factor.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/db/models/two_factor.rs b/src/db/models/two_factor.rs index ecc3c69..b730b18 100644 --- a/src/db/models/two_factor.rs +++ b/src/db/models/two_factor.rs @@ -73,6 +73,16 @@ impl TwoFactor { impl TwoFactor { #[cfg(feature = "postgresql")] pub fn save(&self, conn: &DbConn) -> EmptyResult { + // We need to make sure we're not going to violate the unique constraint on user_uuid and atype. + // This happens automatically on other DBMS backends due to replace_into(). PostgreSQL does + // not support multiple constraints on ON CONFLICT clauses. + let result: EmptyResult = diesel::delete(twofactor::table.filter(twofactor::user_uuid.eq(&self.user_uuid)).filter(twofactor::atype.eq(&self.atype))) + .execute(&**conn) + .map_res("Error deleting twofactor for insert"); + if result.is_err() { + return result; + } + diesel::insert_into(twofactor::table) .values(self) .on_conflict(twofactor::uuid) From e196ba6e869793a37f0f5fa79f0f46c12ec3b40a Mon Sep 17 00:00:00 2001 From: Michael Powers Date: Thu, 16 Jan 2020 08:14:25 -0500 Subject: [PATCH 2/2] Switch error handling to ? operator instead of explicit handling. --- src/db/models/two_factor.rs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/db/models/two_factor.rs b/src/db/models/two_factor.rs index b730b18..b8b3a68 100644 --- a/src/db/models/two_factor.rs +++ b/src/db/models/two_factor.rs @@ -76,12 +76,9 @@ impl TwoFactor { // We need to make sure we're not going to violate the unique constraint on user_uuid and atype. // This happens automatically on other DBMS backends due to replace_into(). PostgreSQL does // not support multiple constraints on ON CONFLICT clauses. - let result: EmptyResult = diesel::delete(twofactor::table.filter(twofactor::user_uuid.eq(&self.user_uuid)).filter(twofactor::atype.eq(&self.atype))) + diesel::delete(twofactor::table.filter(twofactor::user_uuid.eq(&self.user_uuid)).filter(twofactor::atype.eq(&self.atype))) .execute(&**conn) - .map_res("Error deleting twofactor for insert"); - if result.is_err() { - return result; - } + .map_res("Error deleting twofactor for insert")?; diesel::insert_into(twofactor::table) .values(self)