Skip to content

Commit bb0d87b

Browse files
committed
dev/core#6931 - Fix orphan contact on login for a second account with the same email
1 parent 9103487 commit bb0d87b

2 files changed

Lines changed: 213 additions & 0 deletions

File tree

‎CRM/Core/BAO/UFMatch.php‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,25 @@ public static function &synchronizeUFMatch(&$user, $userKey, $uniqId, $uf, $stat
225225
}
226226

227227
if (!$found) {
228+
// uf_name is unique per domain, so a contact created for this user
229+
// could never be linked to it. When another account with the same
230+
// email holds it, give the session that account's contact instead of
231+
// leaving an orphan behind.
232+
$duplicate = self::getMatchOfAccountWithSameEmail($uniqId);
233+
if ($duplicate) {
234+
$ufmatch->contact_id = $duplicate['contact_id'];
235+
Civi::log()->warning(ts('%1 user %2 was not linked to a contact: its email is already linked to %1 user %3, so contact %4 is used for this session', [
236+
1 => $uf,
237+
2 => $userKey,
238+
3 => $duplicate['uf_id'],
239+
4 => $duplicate['contact_id'],
240+
]));
241+
if ($status) {
242+
return $newContact;
243+
}
244+
return $ufmatch;
245+
}
246+
228247
$contactParameters = $config->userSystem->getContactDetailsFromUser([
229248
'user' => $user,
230249
'uniqId' => $uniqId,
@@ -288,6 +307,7 @@ public static function &synchronizeUFMatch(&$user, $userKey, $uniqId, $uf, $stat
288307
4 => $conflict,
289308
]
290309
);
310+
Civi::log()->warning($msg);
291311
unset($conflict);
292312
}
293313
}
@@ -300,6 +320,42 @@ public static function &synchronizeUFMatch(&$user, $userKey, $uniqId, $uf, $stat
300320
}
301321
}
302322

323+
/**
324+
* Finds the match of another CMS account that has this email.
325+
*
326+
* A uf_name alone is not proof: it can keep an email that its account no
327+
* longer has. So the other account's current email in the CMS must match.
328+
*
329+
* @param string|null $email
330+
* Email of the user being synchronized (its uniqId).
331+
*
332+
* @return array|null
333+
* ['uf_id' => int, 'contact_id' => int], or NULL.
334+
*/
335+
private static function getMatchOfAccountWithSameEmail($email): ?array {
336+
$email = trim((string) $email);
337+
$userSystem = CRM_Core_Config::singleton()->userSystem;
338+
if ($email === '' || !method_exists($userSystem, 'getUserObject')) {
339+
return NULL;
340+
}
341+
$match = CRM_Core_DAO::executeQuery(
342+
'SELECT uf_id, contact_id FROM civicrm_uf_match WHERE uf_name = %1 AND domain_id = %2',
343+
[
344+
1 => [$email, 'String'],
345+
2 => [CRM_Core_Config::domainID(), 'Integer'],
346+
]
347+
);
348+
if (!$match->fetch()) {
349+
return NULL;
350+
}
351+
$account = $userSystem->getUserObject($match->uf_id);
352+
$accountEmail = $account ? trim((string) $userSystem->getUniqueIdentifierFromUserObject($account)) : '';
353+
if (strcasecmp($accountEmail, $email) !== 0) {
354+
return NULL;
355+
}
356+
return ['uf_id' => (int) $match->uf_id, 'contact_id' => (int) $match->contact_id];
357+
}
358+
303359
/**
304360
* Update the uf_name in the user object.
305361
*

‎tests/phpunit/CRM/Core/BAO/UFMatchTest.php‎

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,28 @@
11
<?php
22

3+
use Civi\Api4\Email;
4+
35
/**
46
* Class CRM_Core_BAO_UFMatchTest
57
* @group headless
68
*/
79
class CRM_Core_BAO_UFMatchTest extends CiviUnitTestCase {
810

11+
/**
12+
* The user system a test replaced, restored in tearDown().
13+
*
14+
* @var CRM_Utils_System_Base|null
15+
*/
16+
private $originalUserSystem;
17+
18+
protected function tearDown(): void {
19+
if ($this->originalUserSystem) {
20+
CRM_Core_Config::singleton()->userSystem = $this->originalUserSystem;
21+
$this->originalUserSystem = NULL;
22+
}
23+
parent::tearDown();
24+
}
25+
926
/**
1027
* Don't crash if the uf_id doesn't exist
1128
*/
@@ -15,4 +32,144 @@ public function testGetUFValuesWithNonexistentUFId(): void {
1532
$this->assertNull($dontcrash);
1633
}
1734

35+
/**
36+
* A second account with the same email gets no new contact.
37+
*
38+
* uf_name is unique per domain, so a new contact could never be linked to
39+
* this user. Before dev/core#6931 every sync added another one. The other
40+
* account's contact is returned instead, for the session.
41+
*
42+
* @dataProvider getSyncPaths
43+
*/
44+
public function testSynchronizeUFMatchDoesNotCreateContactWhenEmailIsTaken(bool $isLogin): void {
45+
$email = 'taken@example.org';
46+
$this->setCMSAccountEmails([100 => $email]);
47+
$contactID = $this->individualCreate(['email' => $email]);
48+
$this->createUFMatch(100, $email, $contactID);
49+
50+
for ($i = 0; $i < 3; $i++) {
51+
$match = $this->synchronizeUser(200, $email, $isLogin);
52+
}
53+
54+
$this->assertSame([$contactID], $this->getContactIDsWithEmail($email));
55+
$this->assertEquals($contactID, $match->contact_id);
56+
$this->assertNull($this->getLinkedContactID(200));
57+
}
58+
59+
/**
60+
* A stale uf_name does not prove that this user is the same person.
61+
*
62+
* The account that holds it now has another email in the CMS, so its
63+
* contact must not be handed over.
64+
*/
65+
public function testSynchronizeUFMatchDoesNotHandOverContactOfStaleUFName(): void {
66+
$email = 'stale@example.org';
67+
$this->setCMSAccountEmails([100 => 'changed@example.org']);
68+
$contactID = $this->individualCreate(['email' => $email]);
69+
$this->createUFMatch(100, $email, $contactID);
70+
71+
$match = $this->synchronizeUser(200, $email, TRUE);
72+
73+
$this->assertNotEquals($contactID, $match->contact_id);
74+
$this->assertNull($this->getLinkedContactID(200));
75+
}
76+
77+
public function testSynchronizeUFMatchLinksUnlinkedContactWithSameEmail(): void {
78+
$email = 'unlinked@example.org';
79+
$contactID = $this->individualCreate(['email' => $email]);
80+
81+
$this->synchronizeUser(200, $email, TRUE);
82+
83+
$this->assertEquals($contactID, $this->getLinkedContactID(200));
84+
$this->assertSame([$contactID], $this->getContactIDsWithEmail($email));
85+
}
86+
87+
public function testSynchronizeUFMatchCreatesLinkedContactForNewEmail(): void {
88+
$email = 'new@example.org';
89+
90+
$this->synchronizeUser(200, $email, TRUE);
91+
92+
$contactIDs = $this->getContactIDsWithEmail($email);
93+
$this->assertCount(1, $contactIDs);
94+
$this->assertEquals($contactIDs[0], $this->getLinkedContactID(200));
95+
}
96+
97+
/**
98+
* A login takes the email-only match. A form submission takes the dedupe
99+
* rule.
100+
*/
101+
public static function getSyncPaths(): array {
102+
return [
103+
'login' => [TRUE],
104+
'form submission' => [FALSE],
105+
];
106+
}
107+
108+
/**
109+
* Uses a user system that knows the current email of each CMS account.
110+
*
111+
* @param array $emails
112+
* Email of each CMS account, keyed by uf_id.
113+
*/
114+
private function setCMSAccountEmails(array $emails): void {
115+
$this->originalUserSystem = CRM_Core_Config::singleton()->userSystem;
116+
CRM_Core_Config::singleton()->userSystem = new class($emails) extends CRM_Utils_System_UnitTests {
117+
118+
public function __construct(private array $emails) {
119+
parent::__construct();
120+
}
121+
122+
public function getUserObject($userID) {
123+
return isset($this->emails[$userID]) ? (object) ['email' => $this->emails[$userID]] : NULL;
124+
}
125+
126+
public function getUniqueIdentifierFromUserObject($user) {
127+
return $user->email;
128+
}
129+
130+
};
131+
}
132+
133+
private function createUFMatch(int $ufID, string $ufName, int $contactID): void {
134+
CRM_Core_BAO_UFMatch::create([
135+
'domain_id' => CRM_Core_Config::domainID(),
136+
'uf_id' => $ufID,
137+
'uf_name' => $ufName,
138+
'contact_id' => $contactID,
139+
]);
140+
}
141+
142+
private function synchronizeUser(int $ufID, string $email, bool $isLogin): CRM_Core_DAO_UFMatch {
143+
$user = (object) ['id' => $ufID, 'email' => $email, 'mail' => $email];
144+
$post = $_POST;
145+
$_POST = $isLogin ? [] : ['email' => $email];
146+
try {
147+
return CRM_Core_BAO_UFMatch::synchronizeUFMatch($user, $ufID, $email, 'Drupal', NULL, 'Individual', $isLogin);
148+
}
149+
finally {
150+
$_POST = $post;
151+
}
152+
}
153+
154+
/**
155+
* Reads the link from the table: getContactId() caches it across tests.
156+
*/
157+
private function getLinkedContactID(int $ufID): ?int {
158+
$contactID = CRM_Core_DAO::singleValueQuery(
159+
'SELECT contact_id FROM civicrm_uf_match WHERE uf_id = %1',
160+
[1 => [$ufID, 'Integer']]
161+
);
162+
return $contactID ? (int) $contactID : NULL;
163+
}
164+
165+
private function getContactIDsWithEmail(string $email): array {
166+
return array_map('intval', Email::get(FALSE)
167+
->addSelect('contact_id')
168+
->addWhere('email', '=', $email)
169+
->addWhere('contact_id.is_deleted', '=', FALSE)
170+
->addOrderBy('contact_id')
171+
->execute()
172+
->column('contact_id'));
173+
}
174+
18175
}

0 commit comments

Comments
 (0)