Skip to content
27 changes: 27 additions & 0 deletions src/main/java/io/supertokens/storage/postgresql/LockFailure.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/*
* Copyright (c) 2020, VRAI Labs and/or its affiliates. All rights reserved.
*
* This software is licensed under the Apache License, Version 2.0 (the
* "License") as published by the Apache Software Foundation.
*
* You may not use this file except in compliance with the License. You may
* obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/

package io.supertokens.storage.postgresql;

public class LockFailure extends Exception {
public LockFailure() {
super("Failed to acquire advisory lock");
}

public LockFailure(String message) {
super(message);
}
}
93 changes: 74 additions & 19 deletions src/main/java/io/supertokens/storage/postgresql/Start.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@

import javax.annotation.Nonnull;

import io.supertokens.pluginInterface.authRecipe.exceptions.AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException;
import io.supertokens.pluginInterface.authRecipe.exceptions.AnotherPrimaryUserWithEmailAlreadyExistsException;
import io.supertokens.pluginInterface.authRecipe.exceptions.AnotherPrimaryUserWithPhoneNumberAlreadyExistsException;
import io.supertokens.pluginInterface.authRecipe.exceptions.AnotherPrimaryUserWithThirdPartyInfoAlreadyExistsException;
import io.supertokens.storage.postgresql.queries.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
Expand Down Expand Up @@ -151,24 +156,6 @@
import io.supertokens.storage.postgresql.config.Config;
import io.supertokens.storage.postgresql.config.PostgreSQLConfig;
import io.supertokens.storage.postgresql.output.Logging;
import io.supertokens.storage.postgresql.queries.ActiveUsersQueries;
import io.supertokens.storage.postgresql.queries.BulkImportQueries;
import io.supertokens.storage.postgresql.queries.DashboardQueries;
import io.supertokens.storage.postgresql.queries.EmailPasswordQueries;
import io.supertokens.storage.postgresql.queries.EmailVerificationQueries;
import io.supertokens.storage.postgresql.queries.GeneralQueries;
import io.supertokens.storage.postgresql.queries.JWTSigningQueries;
import io.supertokens.storage.postgresql.queries.MultitenancyQueries;
import io.supertokens.storage.postgresql.queries.OAuthQueries;
import io.supertokens.storage.postgresql.queries.PasswordlessQueries;
import io.supertokens.storage.postgresql.queries.SAMLQueries;
import io.supertokens.storage.postgresql.queries.SessionQueries;
import io.supertokens.storage.postgresql.queries.TOTPQueries;
import io.supertokens.storage.postgresql.queries.ThirdPartyQueries;
import io.supertokens.storage.postgresql.queries.UserIdMappingQueries;
import io.supertokens.storage.postgresql.queries.UserMetadataQueries;
import io.supertokens.storage.postgresql.queries.UserRolesQueries;
import io.supertokens.storage.postgresql.queries.WebAuthNQueries;

@WithinOtelSpan
public class Start
Expand Down Expand Up @@ -342,7 +329,7 @@ public void initStorage(boolean shouldWait, List<TenantIdentifier> tenantIdentif
@Override
public <T> T startTransaction(TransactionLogic<T> logic)
throws StorageTransactionLogicException, StorageQueryException {
return startTransaction(logic, TransactionIsolationLevel.SERIALIZABLE);
return startTransaction(logic, TransactionIsolationLevel.READ_COMMITTED);
}

@Override
Expand Down Expand Up @@ -384,6 +371,7 @@ public <T> T startTransaction(TransactionLogic<T> logic, TransactionIsolationLev
// We could get here if the new logic hits a false negative,
// e.g., in case someone renamed constraints/tables
boolean isDeadlockException = actualException instanceof SQLTransactionRollbackException
|| actualException instanceof LockFailure
|| exceptionMessage.toLowerCase().contains("concurrent update")
|| exceptionMessage.toLowerCase().contains("concurrent delete")
|| exceptionMessage.toLowerCase().contains("the transaction might succeed if retried") ||
Expand Down Expand Up @@ -1112,6 +1100,8 @@ public AuthRecipeUserInfo signUp(TenantIdentifier tenantIdentifier, String id, S

if (isUniqueConstraintError(serverMessage, config.getEmailPasswordUserToTenantTable(), "email")) {
throw new DuplicateEmailException();
} else if (isPrimaryKeyError(serverMessage, config.getRecipeUserTenantsTable())) {
throw new DuplicateEmailException();
} else if (isPrimaryKeyError(serverMessage, config.getEmailPasswordUsersTable())
|| isPrimaryKeyError(serverMessage, config.getUsersTable())
|| isPrimaryKeyError(serverMessage, config.getEmailPasswordUserToTenantTable())
Expand Down Expand Up @@ -1565,6 +1555,9 @@ public AuthRecipeUserInfo signUp(
"third_party_user_id")) {
throw new DuplicateThirdPartyUserException();

} else if (isPrimaryKeyError(serverMessage, config.getRecipeUserTenantsTable())) {
throw new DuplicateThirdPartyUserException();

} else if (isPrimaryKeyError(serverMessage, config.getThirdPartyUsersTable())
|| isPrimaryKeyError(serverMessage, config.getUsersTable())
|| isPrimaryKeyError(serverMessage, config.getThirdPartyUserToTenantTable())
Expand Down Expand Up @@ -2159,6 +2152,16 @@ public AuthRecipeUserInfo createUser(TenantIdentifier tenantIdentifier,
PostgreSQLConfig config = Config.getConfig(this);
ServerErrorMessage serverMessage = ((PSQLException) actualException).getServerErrorMessage();

if (isPrimaryKeyError(serverMessage, config.getRecipeUserTenantsTable())) {
// For passwordless, recipe_user_tenants primary key error means duplicate email or phone number
// Determine which one based on what was provided
if (email != null) {
throw new DuplicateEmailException();
} else {
throw new DuplicatePhoneNumberException();
}
}

if (isPrimaryKeyError(serverMessage, config.getPasswordlessUsersTable())
|| isPrimaryKeyError(serverMessage, config.getUsersTable())
|| isPrimaryKeyError(serverMessage, config.getPasswordlessUserToTenantTable())
Expand Down Expand Up @@ -2913,6 +2916,8 @@ public boolean addUserIdToTenant_Transaction(TenantIdentifier tenantIdentifier,
throw new UnknownUserIdException();
}

AccountInfoQueries.addTenantIdToRecipeUser_Transaction(this, sqlCon, tenantIdentifier, userId);

boolean added;
if (recipeId.equals("emailpassword")) {
added = EmailPasswordQueries.addUserIdToTenant_Transaction(this, sqlCon, tenantIdentifier,
Expand Down Expand Up @@ -2983,6 +2988,8 @@ public boolean removeUserIdFromTenant(TenantIdentifier tenantIdentifier, String
} else {
throw new IllegalStateException("Should never come here!");
}
AccountInfoQueries.removeAccountInfoForPrimaryUserIfNecessary_Transaction(this, sqlCon, tenantIdentifier, userId);
AccountInfoQueries.removeAccountInfoForRecipeUser_Transaction(this, sqlCon, tenantIdentifier, userId);

sqlCon.commit();
return removed;
Expand Down Expand Up @@ -3529,6 +3536,7 @@ public void makePrimaryUser_Transaction(AppIdentifier appIdentifier, Transaction
// we do not bother returning if a row was updated here or not, cause it's happening
// in a transaction anyway.
GeneralQueries.makePrimaryUser_Transaction(this, sqlCon, appIdentifier, userId);
AccountInfoQueries.addPrimaryUserAccountInfo_Transaction(this, sqlCon, appIdentifier, userId);
} catch (SQLException e) {
throw new StorageQueryException(e);
}
Expand All @@ -3553,6 +3561,7 @@ public void linkAccounts_Transaction(AppIdentifier appIdentifier, TransactionCon
// we do not bother returning if a row was updated here or not, cause it's happening
// in a transaction anyway.
GeneralQueries.linkAccounts_Transaction(this, sqlCon, appIdentifier, recipeUserId, primaryUserId);
AccountInfoQueries.reserveAccountInfoForLinking_Transaction(this, sqlCon, appIdentifier, recipeUserId, primaryUserId);
Comment on lines 3555 to +3564
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the idea here that we can just drop the GeneralQueries one sooner or later?

} catch (SQLException e) {
throw new StorageQueryException(e);
}
Expand Down Expand Up @@ -3580,6 +3589,7 @@ public void unlinkAccounts_Transaction(AppIdentifier appIdentifier, TransactionC
// we do not bother returning if a row was updated here or not, cause it's happening
// in a transaction anyway.
GeneralQueries.unlinkAccounts_Transaction(this, sqlCon, appIdentifier, primaryUserId, recipeUserId);
AccountInfoQueries.removeAccountInfoForPrimaryUserIfNecessary_Transaction(this, sqlCon, appIdentifier, recipeUserId);
} catch (SQLException e) {
throw new StorageQueryException(e);
}
Expand All @@ -3596,6 +3606,47 @@ public boolean doesUserIdExist_Transaction(TransactionConnection con, AppIdentif
}
}

@Override
public void checkIfLoginMethodCanBecomePrimary_Transaction(AppIdentifier appIdentifier, TransactionConnection con,
LoginMethod loginMethod)
throws AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException, StorageQueryException {
try {
AccountInfoQueries.checkIfLoginMethodCanBecomePrimary_Transaction(this, con, appIdentifier, loginMethod);
} catch (SQLException e) {
throw new StorageQueryException(e);
}
}

@Override
public void checkIfLoginMethodsCanBeLinked_Transaction(TransactionConnection con, AppIdentifier appIdentifier,
Set<String> tenantIds, Set<String> emails,
Set<String> phoneNumbers,
Set<LoginMethod.ThirdParty> thirdParties,
String primaryUserId)
throws AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException, StorageQueryException {
try {
AccountInfoQueries.checkIfLoginMethodsCanBeLinked_Transaction(this, con, appIdentifier, tenantIds, emails, phoneNumbers, thirdParties, primaryUserId);
} catch (SQLException e) {
throw new StorageQueryException(e);
}
}

@Override
public void addTenantIdToPrimaryUser_Transaction(TenantIdentifier tenantIdentifier, TransactionConnection con,
String supertokensUserId)
throws AnotherPrimaryUserWithPhoneNumberAlreadyExistsException,
AnotherPrimaryUserWithEmailAlreadyExistsException,
AnotherPrimaryUserWithThirdPartyInfoAlreadyExistsException,
StorageQueryException {
AccountInfoQueries.addTenantIdToPrimaryUser_Transaction(this, con, tenantIdentifier, supertokensUserId);
}

@Override
public void deleteAccountInfoReservations_Transaction(TransactionConnection con, AppIdentifier appIdentifier,
String userId) throws StorageQueryException {
AccountInfoQueries.removeAccountInfoReservations_Transaction(this, con, appIdentifier, userId);
}

@Override
public boolean checkIfUsesAccountLinking(AppIdentifier appIdentifier) throws StorageQueryException {
try {
Expand Down Expand Up @@ -4214,6 +4265,8 @@ public AuthRecipeUserInfo signUpWithCredentialsRegister_Transaction(TenantIdenti
Logging.error(this, errorMessage.getMessage(), true);
Logging.error(this, email, true);
throw new DuplicateUserEmailException();
} else if (isPrimaryKeyError(errorMessage, config.getRecipeUserTenantsTable())) {
throw new DuplicateUserEmailException();
} else if (isPrimaryKeyError(errorMessage, config.getWebAuthNUsersTable())
|| isPrimaryKeyError(errorMessage, config.getUsersTable())
|| isPrimaryKeyError(errorMessage, config.getWebAuthNUserToTenantTable())
Expand Down Expand Up @@ -4253,6 +4306,8 @@ public AuthRecipeUserInfo signUp_Transaction(TenantIdentifier tenantIdentifier,

if (isUniqueConstraintError(errorMessage, config.getWebAuthNUserToTenantTable(),"email")) {
throw new DuplicateUserEmailException();
} else if (isPrimaryKeyError(errorMessage, config.getRecipeUserTenantsTable())) {
throw new DuplicateUserEmailException();
} else if (isPrimaryKeyError(errorMessage, config.getWebAuthNUsersTable())
|| isPrimaryKeyError(errorMessage, config.getUsersTable())
|| isPrimaryKeyError(errorMessage, config.getWebAuthNUserToTenantTable())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -506,6 +506,13 @@ public String getBulkImportUsersTable() {
return addSchemaAndPrefixToTableName("bulk_import_users");
}

public String getRecipeUserTenantsTable() {
return addSchemaAndPrefixToTableName("recipe_user_tenants");
}

public String getPrimaryUserTenantsTable() {
return addSchemaAndPrefixToTableName("primary_user_tenants");
}

private String addSchemaAndPrefixToTableName(String tableName) {
return addSchemaToTableName(postgresql_table_names_prefix + tableName);
Expand Down
Loading
Loading