From 92a307c164b00f1b888b3ea9bd2f52b98bbbc7be Mon Sep 17 00:00:00 2001 From: Steven Nguyen Date: Wed, 13 Dec 2023 18:45:05 +0000 Subject: [PATCH] Fix user identity attaching to wrong user Suppose a user has 2 accounts on Appwrite: 1. joe@example.com 2. joe@gmail.com Prior to this PR, if joe@example.com created a Google OAuth2 session using his joe@gmail.com email, a new joe@gmail.com identity would be created linked to joe@example.com. This is especially problematic because if the user tried to create a Google OAuth2 session using joe@gmail.com, Appwrite would lookup the user via email and find the joe@gmail.com user, but then find an identity from joe@example.com. This mismatching user ID would then cause an error. This PR prevents an identity from being created if the email from the OAuth2 provider matches another user's email. --- app/controllers/api/account.php | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/app/controllers/api/account.php b/app/controllers/api/account.php index c210b19f4f..54967fb502 100644 --- a/app/controllers/api/account.php +++ b/app/controllers/api/account.php @@ -550,11 +550,19 @@ App::get('/v1/account/sessions/oauth2/:provider/redirect') if (!$user->isEmpty()) { $userId = $user->getId(); - $identitiesWithMatchingEmail = $dbForProject->find('identities', [ + $identityWithMatchingEmail = $dbForProject->findOne('identities', [ Query::equal('providerEmail', [$email]), Query::notEqual('userId', $userId), ]); - if (!empty($identitiesWithMatchingEmail)) { + if (!empty($identityWithMatchingEmail)) { + throw new Exception(Exception::USER_ALREADY_EXISTS); + } + + $userWithMatchingEmail = $dbForProject->find('users', [ + Query::equal('email', [$email]), + Query::notEqual('$id', $userId), + ]); + if (!empty($userWithMatchingEmail)) { throw new Exception(Exception::USER_ALREADY_EXISTS); } }