Merge pull request #10611 from nextcloud/fix/2fa-provider-user-dao-duplicate-key

Fix duplicate key violation in 2FA provider registry DAO
This commit is contained in:
Roeland Jago Douma 2018-08-09 15:52:51 +02:00 committed by GitHub
commit 88603e98f8
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 38 additions and 6 deletions

View file

@ -72,15 +72,26 @@ class ProviderUserAssignmentDao {
public function persist(string $providerId, string $uid, int $enabled) {
$qb = $this->conn->getQueryBuilder();
// First, try to update an existing entry
$updateQuery = $qb->update(self::TABLE_NAME)
->set('enabled', $qb->createNamedParameter($enabled))
$this->conn->beginTransaction();
// To prevent duplicate primary key, we have to first check if an INSERT
// or UPDATE is required
$query = $qb->select('*')
->from(self::TABLE_NAME)
->where($qb->expr()->eq('provider_id', $qb->createNamedParameter($providerId)))
->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($uid)));
$updatedRows = $updateQuery->execute();
$result = $query->execute();
$rowCount = count($result->fetchAll());
$result->closeCursor();
// If this (providerId, UID) key tuple is new, we have to insert it
if (0 === (int)$updatedRows) {
if ($rowCount > 0) {
// There is an entry -> update it
$updateQuery = $qb->update(self::TABLE_NAME)
->set('enabled', $qb->createNamedParameter($enabled))
->where($qb->expr()->eq('provider_id', $qb->createNamedParameter($providerId)))
->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($uid)));
$updateQuery->execute();
} else {
// Insert a new entry
$insertQuery = $qb->insert(self::TABLE_NAME)->values([
'provider_id' => $qb->createNamedParameter($providerId),
'uid' => $qb->createNamedParameter($uid),
@ -89,6 +100,8 @@ class ProviderUserAssignmentDao {
$insertQuery->execute();
}
$this->conn->commit();
}
}

View file

@ -112,4 +112,23 @@ class ProviderUserAssignmentDaoTest extends TestCase {
$this->assertCount(1, $data);
}
public function testPersistSameStateTwice() {
$qb = $this->dbConn->getQueryBuilder();
$this->dao->persist('twofactor_totp', 'user123', 1);
$this->dao->persist('twofactor_totp', 'user123', 1);
$q = $qb
->select('*')
->from(ProviderUserAssignmentDao::TABLE_NAME)
->where($qb->expr()->eq('provider_id', $qb->createNamedParameter('twofactor_totp')))
->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter('user123')))
->andWhere($qb->expr()->eq('enabled', $qb->createNamedParameter(1)));
$res = $q->execute();
$data = $res->fetchAll();
$res->closeCursor();
$this->assertCount(1, $data);
}
}