Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: createNewRecipeUser input in consume code API #910

Merged
merged 4 commits into from
Jan 27, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 49 additions & 45 deletions src/main/java/io/supertokens/passwordless/Passwordless.java
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ public static ConsumeCodeResponse consumeCode(Main main,
Storage storage = StorageLayer.getStorage(main);
return consumeCode(
new TenantIdentifierWithStorage(null, null, null, storage),
main, deviceId, deviceIdHashFromUser, userInputCode, linkCode, false);
main, deviceId, deviceIdHashFromUser, userInputCode, linkCode, false, true);
} catch (TenantOrAppNotFoundException | BadPermissionException e) {
throw new IllegalStateException(e);
}
Expand All @@ -267,7 +267,7 @@ public static ConsumeCodeResponse consumeCode(Main main,
Storage storage = StorageLayer.getStorage(main);
return consumeCode(
new TenantIdentifierWithStorage(null, null, null, storage),
main, deviceId, deviceIdHashFromUser, userInputCode, linkCode, setEmailVerified);
main, deviceId, deviceIdHashFromUser, userInputCode, linkCode, setEmailVerified, true);
} catch (TenantOrAppNotFoundException | BadPermissionException e) {
throw new IllegalStateException(e);
}
Expand All @@ -282,12 +282,12 @@ public static ConsumeCodeResponse consumeCode(TenantIdentifierWithStorage tenant
StorageQueryException, NoSuchAlgorithmException, InvalidKeyException, IOException, Base64EncodingException,
TenantOrAppNotFoundException, BadPermissionException {
return consumeCode(tenantIdentifierWithStorage, main, deviceId, deviceIdHashFromUser, userInputCode, linkCode,
false);
false, true);
}

public static ConsumeCodeResponse consumeCode(TenantIdentifierWithStorage tenantIdentifierWithStorage, Main main,
String deviceId, String deviceIdHashFromUser,
String userInputCode, String linkCode, boolean setEmailVerified)
String userInputCode, String linkCode, boolean setEmailVerified, boolean createRecipeUserIfNotExists)
throws RestartFlowException, ExpiredUserInputCodeException,
IncorrectUserInputCodeException, DeviceIdHashMismatchException, StorageTransactionLogicException,
StorageQueryException, NoSuchAlgorithmException, InvalidKeyException, IOException, Base64EncodingException,
Expand Down Expand Up @@ -439,50 +439,52 @@ public static ConsumeCodeResponse consumeCode(TenantIdentifierWithStorage tenant
}

if (user == null) {
while (true) {
try {
String userId = Utils.getUUID();
long timeJoined = System.currentTimeMillis();
user = passwordlessStorage.createUser(tenantIdentifierWithStorage, userId, consumedDevice.email,
consumedDevice.phoneNumber, timeJoined);

// Set email as verified, if using email
if (setEmailVerified && consumedDevice.email != null) {
try {
AuthRecipeUserInfo finalUser = user;
tenantIdentifierWithStorage.getEmailVerificationStorage().startTransaction(con -> {
try {
tenantIdentifierWithStorage.getEmailVerificationStorage()
.updateIsEmailVerified_Transaction(tenantIdentifierWithStorage.toAppIdentifier(), con,
finalUser.getSupertokensUserId(), consumedDevice.email, true);
tenantIdentifierWithStorage.getEmailVerificationStorage()
.commitTransaction(con);

return null;
} catch (TenantOrAppNotFoundException e) {
throw new StorageTransactionLogicException(e);
if (createRecipeUserIfNotExists) {
while (true) {
try {
String userId = Utils.getUUID();
long timeJoined = System.currentTimeMillis();
user = passwordlessStorage.createUser(tenantIdentifierWithStorage, userId, consumedDevice.email,
consumedDevice.phoneNumber, timeJoined);

// Set email as verified, if using email
if (setEmailVerified && consumedDevice.email != null) {
try {
AuthRecipeUserInfo finalUser = user;
tenantIdentifierWithStorage.getEmailVerificationStorage().startTransaction(con -> {
try {
tenantIdentifierWithStorage.getEmailVerificationStorage()
.updateIsEmailVerified_Transaction(tenantIdentifierWithStorage.toAppIdentifier(), con,
finalUser.getSupertokensUserId(), consumedDevice.email, true);
tenantIdentifierWithStorage.getEmailVerificationStorage()
.commitTransaction(con);

return null;
} catch (TenantOrAppNotFoundException e) {
throw new StorageTransactionLogicException(e);
}
});
user.loginMethods[0].setVerified(); // newly created user has only one loginMethod
} catch (StorageTransactionLogicException e) {
if (e.actualException instanceof TenantOrAppNotFoundException) {
throw (TenantOrAppNotFoundException) e.actualException;
}
});
user.loginMethods[0].setVerified(); // newly created user has only one loginMethod
} catch (StorageTransactionLogicException e) {
if (e.actualException instanceof TenantOrAppNotFoundException) {
throw (TenantOrAppNotFoundException) e.actualException;
throw new StorageQueryException(e);
}
throw new StorageQueryException(e);
}
}

return new ConsumeCodeResponse(true, user, consumedDevice.email, consumedDevice.phoneNumber);
} catch (DuplicateEmailException | DuplicatePhoneNumberException e) {
// Getting these would mean that between getting the user and trying creating it:
// 1. the user managed to do a full create+consume flow
// 2. the users email or phoneNumber was updated to the new one (including device cleanup)
// These should be almost impossibly rare, so it's safe to just ask the user to restart.
// Also, both would make the current login fail if done before the transaction
// by cleaning up the device/code this consume would've used.
throw new RestartFlowException();
} catch (DuplicateUserIdException e) {
// We can retry..
return new ConsumeCodeResponse(true, user, consumedDevice.email, consumedDevice.phoneNumber);
} catch (DuplicateEmailException | DuplicatePhoneNumberException e) {
// Getting these would mean that between getting the user and trying creating it:
// 1. the user managed to do a full create+consume flow
// 2. the users email or phoneNumber was updated to the new one (including device cleanup)
// These should be almost impossibly rare, so it's safe to just ask the user to restart.
// Also, both would make the current login fail if done before the transaction
// by cleaning up the device/code this consume would've used.
throw new RestartFlowException();
} catch (DuplicateUserIdException e) {
// We can retry..
}
}
}
} else {
Expand Down Expand Up @@ -862,11 +864,13 @@ public CreateCodeResponse(String deviceIdHash, String codeId, String deviceId, S

public static class ConsumeCodeResponse {
public boolean createdNewUser;

@Nullable
public AuthRecipeUserInfo user;
public String email;
public String phoneNumber;

public ConsumeCodeResponse(boolean createdNewUser, AuthRecipeUserInfo user, String email, String phoneNumber) {
public ConsumeCodeResponse(boolean createdNewUser, @Nullable AuthRecipeUserInfo user, String email, String phoneNumber) {
this.createdNewUser = createdNewUser;
this.user = user;
this.email = email;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I
String linkCode = null;
String deviceId = null;
String userInputCode = null;
Boolean createRecipeUserIfNotExists = true;

String deviceIdHash = InputParser.parseStringOrThrowError(input, "preAuthSessionId", false);

Expand All @@ -81,36 +82,46 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I
new BadRequestException("Please provide exactly one of linkCode or deviceId+userInputCode"));
}

if (getVersionFromRequest(req).greaterThanOrEqualTo(SemVer.v5_0)) {
if (input.has("createRecipeUserIfNotExists")) {
createRecipeUserIfNotExists = InputParser.parseBooleanOrThrowError(input, "createRecipeUserIfNotExists", false);
}
}

try {
ConsumeCodeResponse consumeCodeResponse = Passwordless.consumeCode(
this.getTenantIdentifierWithStorageFromRequest(req), main,
deviceId, deviceIdHash,
userInputCode, linkCode,
// From CDI version 4.0 onwards, the email verification will be set
getVersionFromRequest(req).greaterThanOrEqualTo(SemVer.v4_0));
io.supertokens.useridmapping.UserIdMapping.populateExternalUserIdForUsers(this.getTenantIdentifierWithStorageFromRequest(req), new AuthRecipeUserInfo[]{consumeCodeResponse.user});

ActiveUsers.updateLastActive(this.getPublicTenantStorage(req), main, consumeCodeResponse.user.getSupertokensUserId());
getVersionFromRequest(req).greaterThanOrEqualTo(SemVer.v4_0),
createRecipeUserIfNotExists);

JsonObject result = new JsonObject();
result.addProperty("status", "OK");
JsonObject userJson =
getVersionFromRequest(req).greaterThanOrEqualTo(SemVer.v4_0) ? consumeCodeResponse.user.toJson() :
consumeCodeResponse.user.toJsonWithoutAccountLinking();

if (getVersionFromRequest(req).lesserThan(SemVer.v3_0)) {
userJson.remove("tenantIds");
}
if (consumeCodeResponse.user != null) {
io.supertokens.useridmapping.UserIdMapping.populateExternalUserIdForUsers(this.getTenantIdentifierWithStorageFromRequest(req), new AuthRecipeUserInfo[]{consumeCodeResponse.user});

ActiveUsers.updateLastActive(this.getPublicTenantStorage(req), main, consumeCodeResponse.user.getSupertokensUserId());

JsonObject userJson = getVersionFromRequest(req).greaterThanOrEqualTo(SemVer.v4_0) ? consumeCodeResponse.user.toJson() :
consumeCodeResponse.user.toJsonWithoutAccountLinking();

if (getVersionFromRequest(req).lesserThan(SemVer.v3_0)) {
userJson.remove("tenantIds");
}

result.addProperty("createdNewUser", consumeCodeResponse.createdNewUser);
result.add("user", userJson);
if (getVersionFromRequest(req).greaterThanOrEqualTo(SemVer.v4_0)) {
for (LoginMethod loginMethod : consumeCodeResponse.user.loginMethods) {
if (loginMethod.recipeId.equals(RECIPE_ID.PASSWORDLESS)
&& (consumeCodeResponse.email == null || Objects.equals(loginMethod.email, consumeCodeResponse.email))
&& (consumeCodeResponse.phoneNumber == null || Objects.equals(loginMethod.phoneNumber, consumeCodeResponse.phoneNumber))) {
result.addProperty("recipeUserId", loginMethod.getSupertokensOrExternalUserId());
break;
result.addProperty("createdNewUser", consumeCodeResponse.createdNewUser);
result.add("user", userJson);
if (getVersionFromRequest(req).greaterThanOrEqualTo(SemVer.v4_0)) {
for (LoginMethod loginMethod : consumeCodeResponse.user.loginMethods) {
if (loginMethod.recipeId.equals(RECIPE_ID.PASSWORDLESS)
&& (consumeCodeResponse.email == null || Objects.equals(loginMethod.email, consumeCodeResponse.email))
&& (consumeCodeResponse.phoneNumber == null || Objects.equals(loginMethod.phoneNumber, consumeCodeResponse.phoneNumber))) {
result.addProperty("recipeUserId", loginMethod.getSupertokensOrExternalUserId());
break;
}
rishabhpoddar marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
Expand Down
Loading
Loading