From 3bb6adfdc651bacf5d87bcc2b416aa6ee482e916 Mon Sep 17 00:00:00 2001 From: Ankit Tiwari Date: Wed, 28 Feb 2024 10:16:27 +0530 Subject: [PATCH] fix: PR changes --- .../io/supertokens/bulkimport/BulkImport.java | 7 ++-- .../BulkImportUserPaginationContainer.java | 6 ++-- .../bulkimport/BulkImportUserUtils.java | 35 +++++++++--------- .../supertokens/utils/JsonValidatorUtils.java | 8 ++++- .../api/bulkimport/BulkImportAPI.java | 17 +++++---- .../test/bulkimport/BulkImportTest.java | 31 ++++++++-------- .../test/bulkimport/BulkImportTestUtils.java | 15 ++------ .../apis/AddBulkImportUsersTest.java | 36 ++++++++++++++++--- 8 files changed, 92 insertions(+), 63 deletions(-) diff --git a/src/main/java/io/supertokens/bulkimport/BulkImport.java b/src/main/java/io/supertokens/bulkimport/BulkImport.java index 49e539bfc..f2136064d 100644 --- a/src/main/java/io/supertokens/bulkimport/BulkImport.java +++ b/src/main/java/io/supertokens/bulkimport/BulkImport.java @@ -18,7 +18,6 @@ import io.supertokens.pluginInterface.bulkimport.BulkImportStorage.BulkImportUserStatus; import io.supertokens.pluginInterface.bulkimport.BulkImportUser; -import io.supertokens.pluginInterface.bulkimport.BulkImportUserInfo; import io.supertokens.pluginInterface.exceptions.StorageQueryException; import io.supertokens.pluginInterface.multitenancy.AppIdentifierWithStorage; import io.supertokens.pluginInterface.multitenancy.exceptions.TenantOrAppNotFoundException; @@ -54,7 +53,7 @@ public static void addUsers(AppIdentifierWithStorage appIdentifierWithStorage, L public static BulkImportUserPaginationContainer getUsers(AppIdentifierWithStorage appIdentifierWithStorage, @Nonnull Integer limit, @Nullable BulkImportUserStatus status, @Nullable String paginationToken) throws StorageQueryException, BulkImportUserPaginationToken.InvalidTokenException { - List users; + List users; if (paginationToken == null) { users = appIdentifierWithStorage.getBulkImportStorage() @@ -69,11 +68,11 @@ public static BulkImportUserPaginationContainer getUsers(AppIdentifierWithStorag int maxLoop = users.size(); if (users.size() == limit + 1) { maxLoop = limit; - BulkImportUserInfo user = users.get(limit); + BulkImportUser user = users.get(limit); nextPaginationToken = new BulkImportUserPaginationToken(user.id, user.createdAt).generateToken(); } - List resultUsers = users.subList(0, maxLoop); + List resultUsers = users.subList(0, maxLoop); return new BulkImportUserPaginationContainer(resultUsers, nextPaginationToken); } } diff --git a/src/main/java/io/supertokens/bulkimport/BulkImportUserPaginationContainer.java b/src/main/java/io/supertokens/bulkimport/BulkImportUserPaginationContainer.java index 2993a83a7..f691c68c3 100644 --- a/src/main/java/io/supertokens/bulkimport/BulkImportUserPaginationContainer.java +++ b/src/main/java/io/supertokens/bulkimport/BulkImportUserPaginationContainer.java @@ -21,13 +21,13 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; -import io.supertokens.pluginInterface.bulkimport.BulkImportUserInfo; +import io.supertokens.pluginInterface.bulkimport.BulkImportUser; public class BulkImportUserPaginationContainer { - public final List users; + public final List users; public final String nextPaginationToken; - public BulkImportUserPaginationContainer(@Nonnull List users, @Nullable String nextPaginationToken) { + public BulkImportUserPaginationContainer(@Nonnull List users, @Nullable String nextPaginationToken) { this.users = users; this.nextPaginationToken = nextPaginationToken; } diff --git a/src/main/java/io/supertokens/bulkimport/BulkImportUserUtils.java b/src/main/java/io/supertokens/bulkimport/BulkImportUserUtils.java index 083d280f1..7b1f20a3c 100644 --- a/src/main/java/io/supertokens/bulkimport/BulkImportUserUtils.java +++ b/src/main/java/io/supertokens/bulkimport/BulkImportUserUtils.java @@ -36,9 +36,6 @@ import io.supertokens.multitenancy.Multitenancy; import io.supertokens.pluginInterface.bulkimport.BulkImportUser; import io.supertokens.pluginInterface.bulkimport.BulkImportUser.LoginMethod; -import io.supertokens.pluginInterface.bulkimport.BulkImportUser.LoginMethod.EmailPasswordLoginMethod; -import io.supertokens.pluginInterface.bulkimport.BulkImportUser.LoginMethod.ThirdPartyLoginMethod; -import io.supertokens.pluginInterface.bulkimport.BulkImportUser.LoginMethod.PasswordlessLoginMethod; import io.supertokens.pluginInterface.bulkimport.BulkImportUser.TotpDevice; import io.supertokens.pluginInterface.exceptions.StorageQueryException; import io.supertokens.pluginInterface.multitenancy.AppIdentifier; @@ -52,7 +49,7 @@ import static io.supertokens.utils.JsonValidatorUtils.validateJsonFieldType; public class BulkImportUserUtils { - public static BulkImportUser createBulkImportUserFromJSON(Main main, AppIdentifier appIdentifier, JsonObject userData, String id) + public static BulkImportUser createBulkImportUserFromJSON(Main main, AppIdentifier appIdentifier, JsonObject userData, String id, String[] allUserRoles) throws InvalidBulkImportDataException, StorageQueryException, TenantOrAppNotFoundException { List errors = new ArrayList<>(); @@ -60,7 +57,7 @@ public static BulkImportUser createBulkImportUserFromJSON(Main main, AppIdentifi errors, "."); JsonObject userMetadata = parseAndValidateFieldType(userData, "userMetadata", ValueType.OBJECT, false, JsonObject.class, errors, "."); - List userRoles = getParsedUserRoles(userData, errors); + List userRoles = getParsedUserRoles(userData, allUserRoles, errors); List totpDevices = getParsedTotpDevices(userData, errors); List loginMethods = getParsedLoginMethods(main, appIdentifier, userData, errors); @@ -72,7 +69,7 @@ public static BulkImportUser createBulkImportUserFromJSON(Main main, AppIdentifi return new BulkImportUser(id, externalUserId, userMetadata, userRoles, totpDevices, loginMethods); } - private static List getParsedUserRoles(JsonObject userData, List errors) { + private static List getParsedUserRoles(JsonObject userData, String[] allUserRoles, List errors) { JsonArray jsonUserRoles = parseAndValidateFieldType(userData, "roles", ValueType.ARRAY_OF_STRING, false, JsonArray.class, errors, "."); @@ -83,7 +80,14 @@ private static List getParsedUserRoles(JsonObject userData, List // We already know that the jsonUserRoles is an array of non-empty strings, we will normalise each role now List userRoles = new ArrayList<>(); - jsonUserRoles.forEach(role -> userRoles.add(validateAndNormaliseUserRole(role.getAsString(), errors))); + jsonUserRoles.forEach(role -> { + String normalisedRole = validateAndNormaliseUserRole(role.getAsString(), errors); + if (Arrays.asList(allUserRoles).contains(normalisedRole)) { + userRoles.add(normalisedRole); + } else { + errors.add("Role " + normalisedRole + " does not exist."); + } + }); return userRoles; } @@ -138,7 +142,7 @@ private static List getParsedLoginMethods(Main main, AppIdentifier String tenantId = parseAndValidateFieldType(jsonLoginMethodObj, "tenantId", ValueType.STRING, false, String.class, errors, " for a loginMethod."); Boolean isVerified = parseAndValidateFieldType(jsonLoginMethodObj, "isVerified", ValueType.BOOLEAN, false, Boolean.class, errors, " for a loginMethod."); Boolean isPrimary = parseAndValidateFieldType(jsonLoginMethodObj, "isPrimary", ValueType.BOOLEAN, false, Boolean.class, errors, " for a loginMethod."); - Integer timeJoined = parseAndValidateFieldType(jsonLoginMethodObj, "timeJoinedInMSSinceEpoch", ValueType.INTEGER, false, Integer.class, errors, " for a loginMethod"); + Long timeJoined = parseAndValidateFieldType(jsonLoginMethodObj, "timeJoinedInMSSinceEpoch", ValueType.LONG, false, Long.class, errors, " for a loginMethod"); recipeId = validateAndNormaliseRecipeId(recipeId, errors); tenantId= validateAndNormaliseTenantId(main, appIdentifier, tenantId, recipeId, errors); @@ -157,8 +161,7 @@ private static List getParsedLoginMethods(Main main, AppIdentifier hashingAlgorithm = normalisedHashingAlgorithm != null ? normalisedHashingAlgorithm.toString() : hashingAlgorithm; passwordHash = validateAndNormalisePasswordHash(main, appIdentifier, normalisedHashingAlgorithm, passwordHash, errors); - EmailPasswordLoginMethod emailPasswordLoginMethod = new EmailPasswordLoginMethod(email, passwordHash, hashingAlgorithm); - loginMethods.add(new LoginMethod(tenantId, recipeId, isVerified, isPrimary, timeJoinedInMSSinceEpoch, emailPasswordLoginMethod, null, null)); + loginMethods.add(new LoginMethod(tenantId, recipeId, isVerified, isPrimary, timeJoinedInMSSinceEpoch, email, passwordHash, hashingAlgorithm, null, null, null)); } else if ("thirdparty".equals(recipeId)) { String email = parseAndValidateFieldType(jsonLoginMethodObj, "email", ValueType.STRING, true, String.class, errors, " for a thirdparty recipe."); String thirdPartyId = parseAndValidateFieldType(jsonLoginMethodObj, "thirdPartyId", ValueType.STRING, true, String.class, errors, " for a thirdparty recipe."); @@ -168,8 +171,7 @@ private static List getParsedLoginMethods(Main main, AppIdentifier thirdPartyId = validateAndNormaliseThirdPartyId(thirdPartyId, errors); thirdPartyUserId = validateAndNormaliseThirdPartyUserId(thirdPartyUserId, errors); - ThirdPartyLoginMethod thirdPartyLoginMethod = new ThirdPartyLoginMethod(email, thirdPartyId, thirdPartyUserId); - loginMethods.add(new LoginMethod(tenantId, recipeId, isVerified, isPrimary, timeJoinedInMSSinceEpoch, null, thirdPartyLoginMethod, null)); + loginMethods.add(new LoginMethod(tenantId, recipeId, isVerified, isPrimary, timeJoinedInMSSinceEpoch, email, null, null, thirdPartyId, thirdPartyUserId, null)); } else if ("passwordless".equals(recipeId)) { String email = parseAndValidateFieldType(jsonLoginMethodObj, "email", ValueType.STRING, false, String.class, errors, " for a passwordless recipe."); String phoneNumber = parseAndValidateFieldType(jsonLoginMethodObj, "phoneNumber", ValueType.STRING, false, String.class, errors, " for a passwordless recipe."); @@ -177,8 +179,7 @@ private static List getParsedLoginMethods(Main main, AppIdentifier email = validateAndNormaliseEmail(email, errors); phoneNumber = validateAndNormalisePhoneNumber(phoneNumber, errors); - PasswordlessLoginMethod passwordlessLoginMethod = new PasswordlessLoginMethod(email, phoneNumber); - loginMethods.add(new LoginMethod(tenantId, recipeId, isVerified, isPrimary, timeJoinedInMSSinceEpoch, null, null, passwordlessLoginMethod)); + loginMethods.add(new LoginMethod(tenantId, recipeId, isVerified, isPrimary, timeJoinedInMSSinceEpoch, email, null, null, null, null, phoneNumber)); } } return loginMethods; @@ -314,10 +315,10 @@ private static Boolean validateAndNormaliseIsVerified(Boolean isVerified) { return isVerified == null ? false : isVerified; } - private static long validateAndNormaliseTimeJoined(Integer timeJoined, List errors) { - // We default timeJoined to 0 if it is null + private static long validateAndNormaliseTimeJoined(Long timeJoined, List errors) { + // We default timeJoined to currentTime if it is null if (timeJoined == null) { - return 0; + return System.currentTimeMillis(); } if (timeJoined > System.currentTimeMillis()) { diff --git a/src/main/java/io/supertokens/utils/JsonValidatorUtils.java b/src/main/java/io/supertokens/utils/JsonValidatorUtils.java index 7fdc564fa..6c2f81cf3 100644 --- a/src/main/java/io/supertokens/utils/JsonValidatorUtils.java +++ b/src/main/java/io/supertokens/utils/JsonValidatorUtils.java @@ -38,6 +38,10 @@ public static T parseAndValidateFieldType(JsonObject jsonObject, String key, Integer intValue = jsonObject.get(key).getAsNumber().intValue(); value = (T) intValue; break; + case LONG: + Long longValue = jsonObject.get(key).getAsNumber().longValue(); + value = (T) longValue; + break; case BOOLEAN: Boolean boolValue = jsonObject.get(key).getAsBoolean(); value = (T) boolValue; @@ -69,6 +73,7 @@ public static T parseAndValidateFieldType(JsonObject jsonObject, String key, public enum ValueType { STRING, INTEGER, + LONG, BOOLEAN, OBJECT, ARRAY_OF_STRING, @@ -79,6 +84,7 @@ private static String getTypeForErrorMessage(ValueType type) { return switch (type) { case STRING -> "string"; case INTEGER -> "integer"; + case LONG -> "integer"; // choosing integer over long because it is user facing case BOOLEAN -> "boolean"; case OBJECT -> "object"; case ARRAY_OF_STRING -> "array of string"; @@ -91,7 +97,7 @@ public static boolean validateJsonFieldType(JsonObject jsonObject, String key, V return switch (expectedType) { case STRING -> jsonObject.get(key).isJsonPrimitive() && jsonObject.getAsJsonPrimitive(key).isString() && !jsonObject.get(key).getAsString().isBlank(); - case INTEGER -> jsonObject.get(key).isJsonPrimitive() && jsonObject.getAsJsonPrimitive(key).isNumber(); + case INTEGER, LONG -> jsonObject.get(key).isJsonPrimitive() && jsonObject.getAsJsonPrimitive(key).isNumber(); case BOOLEAN -> jsonObject.get(key).isJsonPrimitive() && jsonObject.getAsJsonPrimitive(key).isBoolean(); case OBJECT -> jsonObject.get(key).isJsonObject(); case ARRAY_OF_OBJECT, ARRAY_OF_STRING -> jsonObject.get(key).isJsonArray() diff --git a/src/main/java/io/supertokens/webserver/api/bulkimport/BulkImportAPI.java b/src/main/java/io/supertokens/webserver/api/bulkimport/BulkImportAPI.java index 9c6d64310..2f1f5f94a 100644 --- a/src/main/java/io/supertokens/webserver/api/bulkimport/BulkImportAPI.java +++ b/src/main/java/io/supertokens/webserver/api/bulkimport/BulkImportAPI.java @@ -32,7 +32,6 @@ import io.supertokens.output.Logging; import io.supertokens.pluginInterface.bulkimport.BulkImportStorage.BulkImportUserStatus; import io.supertokens.pluginInterface.bulkimport.BulkImportUser; -import io.supertokens.pluginInterface.bulkimport.BulkImportUserInfo; import io.supertokens.pluginInterface.exceptions.StorageQueryException; import io.supertokens.pluginInterface.multitenancy.AppIdentifierWithStorage; import io.supertokens.pluginInterface.multitenancy.exceptions.TenantOrAppNotFoundException; @@ -93,7 +92,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se result.addProperty("status", "OK"); JsonArray usersJson = new JsonArray(); - for (BulkImportUserInfo user : users.users) { + for (BulkImportUser user : users.users) { usersJson.add(user.toJsonObject()); } result.add("users", usersJson); @@ -130,12 +129,20 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws S throw new ServletException(e); } + String[] allUserRoles = null; + + try { + allUserRoles = appIdentifierWithStorage.getUserRolesStorage().getRoles(appIdentifierWithStorage); + } catch (StorageQueryException e) { + throw new ServletException(e); + } + JsonArray errorsJson = new JsonArray(); ArrayList usersToAdd = new ArrayList<>(); for (int i = 0; i < users.size(); i++) { try { - BulkImportUser user = BulkImportUserUtils.createBulkImportUserFromJSON(main, appIdentifierWithStorage, users.get(i).getAsJsonObject(), Utils.getUUID()); + BulkImportUser user = BulkImportUserUtils.createBulkImportUserFromJSON(main, appIdentifierWithStorage, users.get(i).getAsJsonObject(), Utils.getUUID(), allUserRoles); usersToAdd.add(user); } catch (io.supertokens.bulkimport.exceptions.InvalidBulkImportDataException e) { JsonObject errorObj = new JsonObject(); @@ -147,9 +154,7 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws S errorObj.addProperty("index", i); errorObj.add("errors", errors); errorsJson.add(errorObj); - } catch (Exception e) { - System.out.println("error: " + e.getMessage()); - e.printStackTrace(); + } catch (StorageQueryException | TenantOrAppNotFoundException e) { throw new ServletException(e); } } diff --git a/src/test/java/io/supertokens/test/bulkimport/BulkImportTest.java b/src/test/java/io/supertokens/test/bulkimport/BulkImportTest.java index 6d9b327c5..4ff949e09 100644 --- a/src/test/java/io/supertokens/test/bulkimport/BulkImportTest.java +++ b/src/test/java/io/supertokens/test/bulkimport/BulkImportTest.java @@ -37,7 +37,6 @@ import io.supertokens.pluginInterface.bulkimport.BulkImportUser; import io.supertokens.pluginInterface.bulkimport.BulkImportStorage.BulkImportUserStatus; import io.supertokens.pluginInterface.bulkimport.sqlStorage.BulkImportSQLStorage; -import io.supertokens.pluginInterface.bulkimport.BulkImportUserInfo; import io.supertokens.pluginInterface.multitenancy.AppIdentifier; import io.supertokens.pluginInterface.multitenancy.AppIdentifierWithStorage; import io.supertokens.storageLayer.StorageLayer; @@ -76,18 +75,18 @@ public void shouldAddUsersInBulkImportUsersTable() throws Exception { BulkImportStorage storage = (BulkImportStorage) StorageLayer.getStorage(process.main); BulkImport.addUsers(new AppIdentifierWithStorage(null, null, storage), users); - List addedUsers = storage.getBulkImportUsers(new AppIdentifier(null, null), null, BulkImportUserStatus.NEW, null, null); + List addedUsers = storage.getBulkImportUsers(new AppIdentifier(null, null), null, BulkImportUserStatus.NEW, null, null); // Verify that all users are present in addedUsers for (BulkImportUser user : users) { - BulkImportUserInfo matchingUser = addedUsers.stream() + BulkImportUser matchingUser = addedUsers.stream() .filter(addedUser -> user.id.equals(addedUser.id)) .findFirst() .orElse(null); assertNotNull(matchingUser); assertEquals(BulkImportUserStatus.NEW, matchingUser.status); - assertEquals(user.toString(), matchingUser.rawData); + assertEquals(user.toString(), matchingUser.toRawData()); } process.kill(); @@ -116,12 +115,12 @@ public void shouldCreatedNewIdsIfDuplicateIdIsFound() throws Exception { AppIdentifierWithStorage appIdentifierWithStorage = new AppIdentifierWithStorage(null, null, storage); BulkImport.addUsers(appIdentifierWithStorage, users); - List addedUsers = storage.getBulkImportUsers(appIdentifierWithStorage, null, BulkImportUserStatus.NEW, null, null); + List addedUsers = storage.getBulkImportUsers(appIdentifierWithStorage, null, BulkImportUserStatus.NEW, null, null); // Verify that the other properties are same but ids changed for (BulkImportUser user : users) { - BulkImportUserInfo matchingUser = addedUsers.stream() - .filter(addedUser -> user.toString().equals(addedUser.rawData)) + BulkImportUser matchingUser = addedUsers.stream() + .filter(addedUser -> user.toString().equals(addedUser.toRawData())) .findFirst() .orElse(null); @@ -153,7 +152,7 @@ public void testGetUsersStatusFilter() throws Exception { List users = generateBulkImportUser(10); BulkImport.addUsers(appIdentifierWithStorage, users); - List addedUsers = storage.getBulkImportUsers(appIdentifierWithStorage, null, BulkImportUserStatus.NEW, null, null); + List addedUsers = storage.getBulkImportUsers(appIdentifierWithStorage, null, BulkImportUserStatus.NEW, null, null); assertEquals(10, addedUsers.size()); } @@ -171,7 +170,7 @@ public void testGetUsersStatusFilter() throws Exception { return null; }); - List addedUsers = storage.getBulkImportUsers(appIdentifierWithStorage, null, BulkImportUserStatus.PROCESSING, null, null); + List addedUsers = storage.getBulkImportUsers(appIdentifierWithStorage, null, BulkImportUserStatus.PROCESSING, null, null); assertEquals(10, addedUsers.size()); } @@ -189,7 +188,7 @@ public void testGetUsersStatusFilter() throws Exception { return null; }); - List addedUsers = storage.getBulkImportUsers(appIdentifierWithStorage, null, BulkImportUserStatus.FAILED, null, null); + List addedUsers = storage.getBulkImportUsers(appIdentifierWithStorage, null, BulkImportUserStatus.FAILED, null, null); assertEquals(10, addedUsers.size()); } @@ -223,13 +222,13 @@ public void randomPaginationTest() throws Exception { } // Get all inserted users - List addedUsers = storage.getBulkImportUsers(new AppIdentifier(null, null), null, null, null, null); + List addedUsers = storage.getBulkImportUsers(new AppIdentifier(null, null), null, null, null, null); assertEquals(numberOfUsers, addedUsers.size()); // We are sorting the users based on createdAt and id like we do in the storage layer - List sortedUsers = addedUsers.stream() + List sortedUsers = addedUsers.stream() .sorted((user1, user2) -> { - int compareResult = user2.createdAt.compareTo(user1.createdAt); + int compareResult = Long.compare(user2.createdAt, user1.createdAt); if (compareResult == 0) { return user2.id.compareTo(user1.id); } @@ -245,11 +244,11 @@ public void randomPaginationTest() throws Exception { do { BulkImportUserPaginationContainer users = BulkImport.getUsers(new AppIdentifierWithStorage(null, null, storage), limit, null, paginationToken); - for (BulkImportUserInfo actualUser : users.users) { - BulkImportUserInfo expectedUser = sortedUsers.get(indexIntoUsers); + for (BulkImportUser actualUser : users.users) { + BulkImportUser expectedUser = sortedUsers.get(indexIntoUsers); assertEquals(expectedUser.id, actualUser.id); - assertEquals(expectedUser.rawData, actualUser.rawData); + assertEquals(expectedUser.toString(), actualUser.toString()); indexIntoUsers++; } diff --git a/src/test/java/io/supertokens/test/bulkimport/BulkImportTestUtils.java b/src/test/java/io/supertokens/test/bulkimport/BulkImportTestUtils.java index 61e9c6241..1aecc66c6 100644 --- a/src/test/java/io/supertokens/test/bulkimport/BulkImportTestUtils.java +++ b/src/test/java/io/supertokens/test/bulkimport/BulkImportTestUtils.java @@ -25,9 +25,6 @@ import io.supertokens.pluginInterface.bulkimport.BulkImportUser; import io.supertokens.pluginInterface.bulkimport.BulkImportUser.LoginMethod; -import io.supertokens.pluginInterface.bulkimport.BulkImportUser.LoginMethod.EmailPasswordLoginMethod; -import io.supertokens.pluginInterface.bulkimport.BulkImportUser.LoginMethod.PasswordlessLoginMethod; -import io.supertokens.pluginInterface.bulkimport.BulkImportUser.LoginMethod.ThirdPartyLoginMethod; import io.supertokens.pluginInterface.bulkimport.BulkImportUser.TotpDevice; public class BulkImportTestUtils { @@ -43,20 +40,14 @@ public static List generateBulkImportUser(int numberOfUsers) { JsonObject userMetadata = parser.parse("{\"key1\":\"value1\",\"key2\":{\"key3\":\"value3\"}}").getAsJsonObject(); List userRoles = new ArrayList<>(); - userRoles.add("role1"); - userRoles.add("role2"); List totpDevices = new ArrayList<>(); totpDevices.add(new TotpDevice("secretKey", 30, 1, "deviceName")); - EmailPasswordLoginMethod emailPasswordLoginMethod = new EmailPasswordLoginMethod(email, "$2a", "BCRYPT"); - ThirdPartyLoginMethod thirdPartyLoginMethod = new ThirdPartyLoginMethod(email, "thirdPartyId", "thirdPartyUserId"); - PasswordlessLoginMethod passwordlessLoginMethod = new PasswordlessLoginMethod(email, "+911234567890"); - List loginMethods = new ArrayList<>(); - loginMethods.add(new LoginMethod("public", "emailpassword", true, true, 0, emailPasswordLoginMethod, null, null)); - loginMethods.add(new LoginMethod("public", "thirdparty", true, false, 0, null, thirdPartyLoginMethod, null)); - loginMethods.add(new LoginMethod("public", "passwordless", true, false, 0, null, null, passwordlessLoginMethod)); + loginMethods.add(new LoginMethod("public", "emailpassword", true, true, 0, email, "$2a", "BCRYPT", null, null, null)); + loginMethods.add(new LoginMethod("public", "thirdparty", true, false, 0, email, null, null, "thirdPartyId", "thirdPartyUserId", null)); + loginMethods.add(new LoginMethod("public", "passwordless", true, false, 0, email, null, null, null, null, "+911234567890")); users.add(new BulkImportUser(id, externalId, userMetadata, userRoles, totpDevices, loginMethods)); } return users; diff --git a/src/test/java/io/supertokens/test/bulkimport/apis/AddBulkImportUsersTest.java b/src/test/java/io/supertokens/test/bulkimport/apis/AddBulkImportUsersTest.java index 376f4b3ff..4684b0f92 100644 --- a/src/test/java/io/supertokens/test/bulkimport/apis/AddBulkImportUsersTest.java +++ b/src/test/java/io/supertokens/test/bulkimport/apis/AddBulkImportUsersTest.java @@ -41,6 +41,7 @@ import io.supertokens.test.TestingProcessManager; import io.supertokens.test.Utils; import io.supertokens.test.httpRequest.HttpRequestForTesting; +import io.supertokens.userroles.UserRoles; public class AddBulkImportUsersTest { @Rule @@ -151,6 +152,21 @@ public void shouldThrow400Error() throws Exception { assertEquals(responseString, "{\"error\":\"" + genericErrMsg + "\",\"users\":[{\"index\":0,\"errors\":[\"externalUserId should be of type string.\",\"roles should be of type array of string.\",\"totp should be of type array of object.\",\"loginMethods is required.\"]}]}"); } + // Invalid role (does not exist) + try { + JsonObject request = new JsonParser() + .parse("{\"users\":[{\"roles\":[\"role5\"]}]}") + .getAsJsonObject(); + HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", + "http://localhost:3567/bulk-import/users", + request, 1000, 1000, null, Utils.getCdiVersionStringLatestForTests(), null); + } catch (io.supertokens.test.httpRequest.HttpResponseException e) { + String responseString = getResponseMessageFromError(e.getMessage()); + assertEquals(400, e.statusCode); + + assertEquals(responseString, + "{\"error\":\"" + genericErrMsg + "\",\"users\":[{\"index\":0,\"errors\":[\"Role role5 does not exist.\",\"loginMethods is required.\"]}]}"); + } } // Invalid field type of non required fields inside loginMethod { @@ -380,6 +396,12 @@ public void shouldReturn200Response() throws Exception { return; } + // Create user roles before inserting bulk users + { + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), "role1", null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), "role2", null); + } + JsonObject request = generateUsersJson(10000); JsonObject response = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", "http://localhost:3567/bulk-import/users", @@ -401,6 +423,12 @@ public void shouldNormaliseFields() throws Exception { return; } + // Create user roles before inserting bulk users + { + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), "role1", null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), "role2", null); + } + JsonObject request = generateUsersJson(1); JsonObject response = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", "http://localhost:3567/bulk-import/users", @@ -422,10 +450,10 @@ public void shouldNormaliseFields() throws Exception { for (int i = 0; i < loginMethods.size(); i++) { JsonObject loginMethod = loginMethods.get(i).getAsJsonObject(); if (loginMethod.has("email")) { - assertEquals("johndoe+1@gmail.com", loginMethod.get("hashingAlgorithm").getAsString()); + assertEquals("johndoe+0@gmail.com", loginMethod.get("email").getAsString()); } if (loginMethod.has("phoneNumber")) { - assertEquals("919999999999", loginMethod.get("phoneNumber").getAsString()); + assertEquals("+919999999999", loginMethod.get("phoneNumber").getAsString()); } if (loginMethod.has("hashingAlgorithm")) { assertEquals("ARGON2", loginMethod.get("hashingAlgorithm").getAsString()); @@ -446,8 +474,8 @@ public static JsonObject generateUsersJson(int numberOfUsers) { user.addProperty("externalUserId", UUID.randomUUID().toString()); user.add("userMetadata", parser.parse("{\"key1\":\"value1\",\"key2\":{\"key3\":\"value3\"}}")); - user.add("roles", parser.parse("[\"role1\", \"role2\"]")); - user.add("totp", parser.parse("[{\"secretKey\":\"secretKey\",\"period\": 30,\"skew\":1,\"deviceName\":\"deviceName\"}]")); + user.add("userRoles", parser.parse("[\"role1\", \"role2\"]")); + user.add("totpDevices", parser.parse("[{\"secretKey\":\"secretKey\",\"period\": 30,\"skew\":1,\"deviceName\":\"deviceName\"}]")); String email = " johndoe+" + i + "@gmail.com ";