Skip to content

Commit 3b26b66

Browse files
committed
Init behavior change based on identity verification
1 parent af3ba8a commit 3b26b66

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
@@ -11,7 +11,6 @@ import com.onesignal.core.internal.startup.IStartableService
1111
import com.onesignal.core.internal.time.ITime
1212
import com.onesignal.debug.LogLevel
1313
import com.onesignal.debug.internal.logging.Logging
14-
import com.onesignal.user.internal.backend.IdentityConstants
1514
import com.onesignal.user.internal.identity.IdentityModelStore
1615
import com.onesignal.user.internal.operations.impl.states.NewRecordsState
1716
import kotlinx.coroutines.CompletableDeferred
@@ -97,10 +96,10 @@ internal class OperationRepo(
9796
}
9897

9998
override fun start() {
100-
paused = false
10199
coroutineScope.launch {
102100
// load saved operations first then start processing the queue to ensure correct operation order
103101
loadSavedOperations()
102+
paused = false
104103
processQueueForever()
105104
}
106105
}
@@ -270,9 +269,7 @@ internal class OperationRepo(
270269
ops.forEach { it.waiter?.wake(true) }
271270
}
272271
ExecutionResult.FAIL_UNAUTHORIZED -> {
273-
Logging.error("Operation execution failed with invalid jwt, pausing the operation repo: $operations")
274-
// keep the failed operation and pause the operation repo from executing
275-
paused = true
272+
Logging.error("Operation execution failed with invalid jwt")
276273
// add back all operations to the front of the queue to be re-executed.
277274
synchronized(queue) {
278275
ops.reversed().forEach { queue.add(0, it) }
@@ -378,7 +375,6 @@ internal class OperationRepo(
378375

379376
// Ensure the operation does not have empty JWT if identity verification is on
380377
if (_configModelStore.model.useIdentityVerification &&
381-
operation.hasProperty(IdentityConstants.EXTERNAL_ID) &&
382378
_identityModelStore.model.jwtToken.isNullOrEmpty()
383379
) {
384380
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
@@ -261,14 +261,7 @@ internal class OneSignalImp : IOneSignal, IServiceProvider {
261261
)
262262
if (legacyPlayerId == null) {
263263
Logging.debug("initWithContext: creating new device-scoped user")
264-
createAndSwitchToNewUser()
265-
operationRepo!!.enqueue(
266-
LoginUserOperation(
267-
configModel!!.appId,
268-
identityModelStore!!.model.onesignalId,
269-
identityModelStore!!.model.externalId,
270-
),
271-
)
264+
createAndSwitchToNewUser(suppressBackendOperation = true)
272265
} else {
273266
Logging.debug("initWithContext: creating user linked to subscription $legacyPlayerId")
274267

@@ -317,7 +310,7 @@ internal class OneSignalImp : IOneSignal, IServiceProvider {
317310
suppressBackendOperation = true
318311
}
319312

320-
createAndSwitchToNewUser(suppressBackendOperation = suppressBackendOperation)
313+
createAndSwitchToNewUser(suppressBackendOperation = true)
321314

322315
// ** No longer allowed when identity verification is on
323316
operationRepo!!.enqueue(
@@ -372,7 +365,7 @@ internal class OneSignalImp : IOneSignal, IServiceProvider {
372365
}
373366

374367
// TODO: Set JWT Token for all future requests.
375-
createAndSwitchToNewUser { identityModel, _ ->
368+
createAndSwitchToNewUser(suppressBackendOperation = false) { identityModel, _ ->
376369
identityModel.externalId = externalId
377370
identityModel.jwtToken = jwtBearerToken
378371
}
@@ -388,17 +381,31 @@ internal class OneSignalImp : IOneSignal, IServiceProvider {
388381
// time if network conditions prevent the operation to succeed. This allows us to
389382
// provide a callback to the caller when we can absolutely say the user is logged
390383
// in, so they may take action on their own backend.
384+
391385
val result =
392-
operationRepo!!.enqueueAndWait(
393-
LoginUserOperation(
394-
configModel!!.appId,
395-
newIdentityOneSignalId,
396-
externalId,
397-
if (currentIdentityExternalId == null) currentIdentityOneSignalId else null,
398-
),
399-
)
400-
401-
if (!result) {
386+
when (useIdentityVerification) {
387+
true -> {
388+
operationRepo!!.enqueue(
389+
LoginUserOperation(
390+
configModel!!.appId,
391+
identityModelStore!!.model.onesignalId,
392+
identityModelStore!!.model.externalId,
393+
),
394+
)
395+
}
396+
else -> {
397+
operationRepo!!.enqueueAndWait(
398+
LoginUserOperation(
399+
configModel!!.appId,
400+
newIdentityOneSignalId,
401+
externalId,
402+
if (currentIdentityExternalId == null) currentIdentityOneSignalId else null,
403+
),
404+
)
405+
}
406+
}
407+
408+
if (result == false) {
402409
Logging.log(LogLevel.ERROR, "Could not login user")
403410
}
404411
}
@@ -437,7 +444,6 @@ internal class OneSignalImp : IOneSignal, IServiceProvider {
437444
for (model in identityModelStore!!.store.list()) {
438445
if (externalId == model.externalId) {
439446
identityModelStore!!.model.jwtToken = token
440-
operationRepo!!.setPaused(false)
441447
operationRepo!!.forceExecuteOperations()
442448
Logging.log(LogLevel.DEBUG, "JWT $token is updated for externalId $externalId")
443449
return
@@ -476,6 +482,20 @@ internal class OneSignalImp : IOneSignal, IServiceProvider {
476482
modify(identityModel, propertiesModel)
477483
}
478484

485+
if (!identityModel.jwtToken.isNullOrEmpty()) {
486+
setupNewSubscription(identityModel, propertiesModel, suppressBackendOperation, sdkId)
487+
}
488+
489+
identityModelStore!!.replace(identityModel)
490+
propertiesModelStore!!.replace(propertiesModel)
491+
}
492+
493+
private fun setupNewSubscription(
494+
identityModel: IdentityModel,
495+
propertiesModel: PropertiesModel,
496+
suppressBackendOperation: Boolean,
497+
sdkId: String,
498+
) {
479499
val subscriptions = mutableListOf<SubscriptionModel>()
480500

481501
// Create the push subscription for this device under the new user, copying the current
@@ -484,7 +504,7 @@ internal class OneSignalImp : IOneSignal, IServiceProvider {
484504
// will be automatically transferred over to this new user being created. If there is no
485505
// current push subscription we do a "normal" replace which will drive adding a CreateSubscriptionOperation
486506
// to the queue.
487-
val currentPushSubscription = subscriptionModelStore!!.list().firstOrNull { it.id == configModel!!.pushSubscriptionId }
507+
val currentPushSubscription = subscriptionModelStore!!.list().firstOrNull { it.type == SubscriptionType.PUSH }
488508
val newPushSubscription = SubscriptionModel()
489509

490510
newPushSubscription.id = currentPushSubscription?.id ?: IDManager.createLocalId()
@@ -512,7 +532,13 @@ internal class OneSignalImp : IOneSignal, IServiceProvider {
512532

513533
if (suppressBackendOperation) {
514534
subscriptionModelStore!!.replaceAll(subscriptions, ModelChangeTags.NO_PROPOGATE)
515-
} else if (currentPushSubscription != null) {
535+
} else if (currentPushSubscription != null && (
536+
!useIdentityVerification || useIdentityVerification &&
537+
!IDManager.isLocalId(
538+
currentPushSubscription.id,
539+
)
540+
)
541+
) {
516542
operationRepo!!.enqueue(TransferSubscriptionOperation(configModel!!.appId, currentPushSubscription.id, sdkId))
517543
subscriptionModelStore!!.replaceAll(subscriptions, ModelChangeTags.NO_PROPOGATE)
518544
} else {
@@ -521,14 +547,18 @@ internal class OneSignalImp : IOneSignal, IServiceProvider {
521547
}
522548

523549
private fun resumeOperationRepoAfterFetchParams(configModel: ConfigModel) {
524-
// pause operation repo until useIdentityVerification is determined
525-
operationRepo!!.setPaused(true)
526550
configModel.addFetchParamsObserver(
527551
object : FetchParamsObserver {
528552
override fun onParamsFetched(params: ParamsObject) {
529553
// resume operations if identity verification is turned off or a jwt is cached
530554
if (params.useIdentityVerification == false || identityModelStore!!.model.jwtToken != null) {
531-
operationRepo!!.setPaused(false)
555+
operationRepo!!.enqueue(
556+
LoginUserOperation(
557+
configModel!!.appId,
558+
identityModelStore!!.model.onesignalId,
559+
identityModelStore!!.model.externalId,
560+
),
561+
)
532562
} else {
533563
Logging.log(LogLevel.ERROR, "A valid JWT is required for user ${identityModelStore!!.model.externalId}.")
534564
}

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)