Skip to content

Commit 3d4ea53

Browse files
jinliu9508jkasten2
authored andcommitted
Init behavior change based on identity verification
1 parent ac1dda5 commit 3d4ea53

File tree

5 files changed

+62
-36
lines changed

5 files changed

+62
-36
lines changed

Examples/OneSignalDemo/app/src/main/java/com/onesignal/sdktest/application/MainApplication.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ public void onCreate() {
6666
// This will reproduce result similar to Kotlin CouroutineScope.launch{}, which may potentially crash the app
6767
ExecutorService executor = Executors.newSingleThreadExecutor();
6868
@SuppressLint({"NewApi", "LocalSuppress"}) CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
69-
OneSignal.getNotifications().requestPermission(true, Continue.none());
69+
//OneSignal.getNotifications().requestPermission(true, Continue.none());
7070
}, executor);
7171
future.join(); // Waits for the task to complete
7272
executor.shutdown();
@@ -145,7 +145,7 @@ public void onUserStateChange(@NonNull UserChangedState state) {
145145
@Override
146146
public void onUserJwtInvalidated(@NonNull UserJwtInvalidatedEvent event) {
147147
// !!! For manual testing only
148-
String jwt = "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiIxNjg4ZDhmMi1kYTdmLTQ4MTUtOGVlMy05ZDEzNzg4NDgyYzgiLCJpYXQiOjE3MTgzMDk5NzIsImlkZW50aXR5Ijp7ImV4dGVybmFsX2lkIjoiYWxleC0wNjE0Iiwib25lc2lnbmFsX2lkIjoiYTViYjc4NDYtYzExNC00YzdkLTkzMWYtNGQ0NjhiMGE5OWJhIn0sInN1YnNjcmlwdGlvbnMiOlt7InR5cGUiOiJFbWFpbCIsInRva2VuIjoidGVzdEBkb21haW4uY29tIn0seyJpZCI6ImE2YzQxNmY3LTMxMGUtNDgzNi05Yjc4LWZiZmQ5NTgyNWNjNCJ9XX0.HsjsA2qNPwd9qov_8Px01km-dzRug-YKNNG85cMrGYI9Pdb2uoPQSdAN3Uqu7_o4pL8FRxXliYJrC52-9wH3FQ";
148+
String jwt = "SecondJWT";
149149
OneSignal.updateUserJwt(event.getExternalId(), jwt);
150150
Log.v(Tag.LOG_TAG, "onUserJwtInvalidated fired with ID:" + event.getExternalId());
151151
}

Examples/OneSignalDemo/app/src/main/java/com/onesignal/sdktest/model/MainActivityViewModel.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -411,7 +411,7 @@ private void setupAppLayout() {
411411
@Override
412412
public void onSuccess(String update) {
413413
if (update != null && !update.isEmpty()) {
414-
String jwt = "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiIxNjg4ZDhmMi1kYTdmLTQ4MTUtOGVlMy05ZDEzNzg4NDgyYzgiLCJpYXQiOjE3MTU5NzMwNzAsImlkZW50aXR5Ijp7ImV4dGVybmFsX2lkIjoiYWxleC0wNTE3Iiwib25lc2lnbmFsX2lkIjoiMGIzYWMyN2EtYWQ4Yi00MWVjLWJhYTYtMzI0NmNkODIyMjJkIn0sInN1YnNjcmlwdGlvbnMiOlt7InR5cGUiOiJFbWFpbCIsInRva2VuIjoiYWxleHRzYXktMDUxN0BvbmVzaWduYWwuY29tIn0seyJ0eXBlIjoiQW5kcm9pZFB1c2giLCJpZCI6ImFkMTAxY2FjLTA5MWItNDkyYy04OGJiLTgxNmZkNTNjYTBmMSJ9XX0._tlD2X8J16gDkP7__FJ8CwpqCLDwb8T14m2ugJwQvuQqbIn4b8o75cKbffbjVGcKP3YaudLCebit53aR9LTQCw";
414+
String jwt = "InitialJWT";
415415
OneSignal.login(update, jwt);
416416
refreshState();
417417
}

OneSignalSDK/onesignal/core/src/main/java/com/onesignal/core/internal/operations/impl/OperationRepo.kt

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ import com.onesignal.core.internal.startup.IStartableService
1212
import com.onesignal.core.internal.time.ITime
1313
import com.onesignal.debug.LogLevel
1414
import com.onesignal.debug.internal.logging.Logging
15-
import com.onesignal.user.internal.backend.IdentityConstants
1615
import com.onesignal.user.internal.identity.IdentityModelStore
1716
import com.onesignal.user.internal.operations.impl.states.NewRecordsState
1817
import kotlinx.coroutines.CompletableDeferred
@@ -98,10 +97,10 @@ internal class OperationRepo(
9897
}
9998

10099
override fun start() {
101-
paused = false
102100
coroutineScope.launch {
103101
// load saved operations first then start processing the queue to ensure correct operation order
104102
loadSavedOperations()
103+
paused = false
105104
processQueueForever()
106105
}
107106
}
@@ -268,9 +267,7 @@ internal class OperationRepo(
268267
ops.forEach { it.waiter?.wake(true) }
269268
}
270269
ExecutionResult.FAIL_UNAUTHORIZED -> {
271-
Logging.error("Operation execution failed with invalid jwt, pausing the operation repo: $operations")
272-
// keep the failed operation and pause the operation repo from executing
273-
paused = true
270+
Logging.error("Operation execution failed with invalid jwt")
274271
// add back all operations to the front of the queue to be re-executed.
275272
synchronized(queue) {
276273
ops.reversed().forEach { queue.add(0, it) }
@@ -396,7 +393,6 @@ internal class OperationRepo(
396393

397394
// Ensure the operation does not have empty JWT if identity verification is on
398395
if (_configModelStore.model.useIdentityVerification &&
399-
operation.hasProperty(IdentityConstants.EXTERNAL_ID) &&
400396
_identityModelStore.model.jwtToken.isNullOrEmpty()
401397
) {
402398
continue

OneSignalSDK/onesignal/core/src/main/java/com/onesignal/internal/OneSignalImp.kt

Lines changed: 56 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -269,14 +269,7 @@ internal class OneSignalImp : IOneSignal, IServiceProvider {
269269
)
270270
if (legacyPlayerId == null) {
271271
Logging.debug("initWithContext: creating new device-scoped user")
272-
createAndSwitchToNewUser()
273-
operationRepo!!.enqueue(
274-
LoginUserOperation(
275-
configModel!!.appId,
276-
identityModelStore!!.model.onesignalId,
277-
identityModelStore!!.model.externalId,
278-
),
279-
)
272+
createAndSwitchToNewUser(suppressBackendOperation = true)
280273
} else {
281274
Logging.debug("initWithContext: creating user linked to subscription $legacyPlayerId")
282275

@@ -325,7 +318,7 @@ internal class OneSignalImp : IOneSignal, IServiceProvider {
325318
suppressBackendOperation = true
326319
}
327320

328-
createAndSwitchToNewUser(suppressBackendOperation = suppressBackendOperation)
321+
createAndSwitchToNewUser(suppressBackendOperation = true)
329322

330323
// ** No longer allowed when identity verification is on
331324
operationRepo!!.enqueue(
@@ -380,7 +373,7 @@ internal class OneSignalImp : IOneSignal, IServiceProvider {
380373
}
381374

382375
// TODO: Set JWT Token for all future requests.
383-
createAndSwitchToNewUser { identityModel, _ ->
376+
createAndSwitchToNewUser(suppressBackendOperation = false) { identityModel, _ ->
384377
identityModel.externalId = externalId
385378
identityModel.jwtToken = jwtBearerToken
386379
}
@@ -396,17 +389,31 @@ internal class OneSignalImp : IOneSignal, IServiceProvider {
396389
// time if network conditions prevent the operation to succeed. This allows us to
397390
// provide a callback to the caller when we can absolutely say the user is logged
398391
// in, so they may take action on their own backend.
392+
399393
val result =
400-
operationRepo!!.enqueueAndWait(
401-
LoginUserOperation(
402-
configModel!!.appId,
403-
newIdentityOneSignalId,
404-
externalId,
405-
if (currentIdentityExternalId == null) currentIdentityOneSignalId else null,
406-
),
407-
)
408-
409-
if (!result) {
394+
when (useIdentityVerification) {
395+
true -> {
396+
operationRepo!!.enqueue(
397+
LoginUserOperation(
398+
configModel!!.appId,
399+
identityModelStore!!.model.onesignalId,
400+
identityModelStore!!.model.externalId,
401+
),
402+
)
403+
}
404+
else -> {
405+
operationRepo!!.enqueueAndWait(
406+
LoginUserOperation(
407+
configModel!!.appId,
408+
newIdentityOneSignalId,
409+
externalId,
410+
if (currentIdentityExternalId == null) currentIdentityOneSignalId else null,
411+
),
412+
)
413+
}
414+
}
415+
416+
if (result == false) {
410417
Logging.log(LogLevel.ERROR, "Could not login user")
411418
}
412419
}
@@ -455,7 +462,6 @@ internal class OneSignalImp : IOneSignal, IServiceProvider {
455462
for (model in identityModelStore!!.store.list()) {
456463
if (externalId == model.externalId) {
457464
identityModelStore!!.model.jwtToken = token
458-
operationRepo!!.setPaused(false)
459465
operationRepo!!.forceExecuteOperations()
460466
Logging.log(LogLevel.DEBUG, "JWT $token is updated for externalId $externalId")
461467
return
@@ -494,6 +500,20 @@ internal class OneSignalImp : IOneSignal, IServiceProvider {
494500
modify(identityModel, propertiesModel)
495501
}
496502

503+
if (!identityModel.jwtToken.isNullOrEmpty()) {
504+
setupNewSubscription(identityModel, propertiesModel, suppressBackendOperation, sdkId)
505+
}
506+
507+
identityModelStore!!.replace(identityModel)
508+
propertiesModelStore!!.replace(propertiesModel)
509+
}
510+
511+
private fun setupNewSubscription(
512+
identityModel: IdentityModel,
513+
propertiesModel: PropertiesModel,
514+
suppressBackendOperation: Boolean,
515+
sdkId: String,
516+
) {
497517
val subscriptions = mutableListOf<SubscriptionModel>()
498518

499519
// Create the push subscription for this device under the new user, copying the current
@@ -502,7 +522,7 @@ internal class OneSignalImp : IOneSignal, IServiceProvider {
502522
// will be automatically transferred over to this new user being created. If there is no
503523
// current push subscription we do a "normal" replace which will drive adding a CreateSubscriptionOperation
504524
// to the queue.
505-
val currentPushSubscription = subscriptionModelStore!!.list().firstOrNull { it.id == configModel!!.pushSubscriptionId }
525+
val currentPushSubscription = subscriptionModelStore!!.list().firstOrNull { it.type == SubscriptionType.PUSH }
506526
val newPushSubscription = SubscriptionModel()
507527

508528
newPushSubscription.id = currentPushSubscription?.id ?: IDManager.createLocalId()
@@ -530,7 +550,13 @@ internal class OneSignalImp : IOneSignal, IServiceProvider {
530550

531551
if (suppressBackendOperation) {
532552
subscriptionModelStore!!.replaceAll(subscriptions, ModelChangeTags.NO_PROPOGATE)
533-
} else if (currentPushSubscription != null) {
553+
} else if (currentPushSubscription != null && (
554+
!useIdentityVerification || useIdentityVerification &&
555+
!IDManager.isLocalId(
556+
currentPushSubscription.id,
557+
)
558+
)
559+
) {
534560
operationRepo!!.enqueue(TransferSubscriptionOperation(configModel!!.appId, currentPushSubscription.id, sdkId))
535561
subscriptionModelStore!!.replaceAll(subscriptions, ModelChangeTags.NO_PROPOGATE)
536562
} else {
@@ -539,14 +565,18 @@ internal class OneSignalImp : IOneSignal, IServiceProvider {
539565
}
540566

541567
private fun resumeOperationRepoAfterFetchParams(configModel: ConfigModel) {
542-
// pause operation repo until useIdentityVerification is determined
543-
operationRepo!!.setPaused(true)
544568
configModel.addFetchParamsObserver(
545569
object : FetchParamsObserver {
546570
override fun onParamsFetched(params: ParamsObject) {
547571
// resume operations if identity verification is turned off or a jwt is cached
548572
if (params.useIdentityVerification == false || identityModelStore!!.model.jwtToken != null) {
549-
operationRepo!!.setPaused(false)
573+
operationRepo!!.enqueue(
574+
LoginUserOperation(
575+
configModel!!.appId,
576+
identityModelStore!!.model.onesignalId,
577+
identityModelStore!!.model.externalId,
578+
),
579+
)
550580
} else {
551581
Logging.log(LogLevel.ERROR, "A valid JWT is required for user ${identityModelStore!!.model.externalId}.")
552582
}

OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/UserManager.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,7 @@ internal open class UserManager(
285285
// prevent same JWT from being invalidated twice in a row
286286
if (OneSignal.useIdentityVerification && jwtTokenInvalidated != oldJwt && newJwt.isEmpty()) {
287287
jwtInvalidatedCallback.fire {
288-
it.onUserJwtInvalidated(UserJwtInvalidatedEvent((externalId)))
288+
it.onUserJwtInvalidated(UserJwtInvalidatedEvent(externalId))
289289
}
290290
}
291291

0 commit comments

Comments
 (0)