-
Notifications
You must be signed in to change notification settings - Fork 385
/
SalesforceSDKManager.kt
1772 lines (1597 loc) · 62.6 KB
/
SalesforceSDKManager.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2014-present, salesforce.com, inc.
* All rights reserved.
* Redistribution and use of this software in source and binary forms, with or
* without modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of salesforce.com, inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission of salesforce.com, inc.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.androidsdk.app
import android.accounts.Account
import android.accounts.AccountManager
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.app.Application
import android.app.Application.ActivityLifecycleCallbacks
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import android.content.IntentFilter
import android.content.res.Configuration.UI_MODE_NIGHT_MASK
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import android.os.Build.MODEL
import android.os.Build.VERSION.RELEASE
import android.os.Build.VERSION.SECURITY_PATCH
import android.os.Bundle
import android.os.Handler
import android.os.Looper.getMainLooper
import android.provider.Settings.Secure.ANDROID_ID
import android.provider.Settings.Secure.getString
import android.text.TextUtils.isEmpty
import android.text.TextUtils.join
import android.view.View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
import android.view.View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
import android.webkit.CookieManager
import android.webkit.URLUtil.isHttpsUrl
import androidx.core.content.ContextCompat.RECEIVER_EXPORTED
import androidx.core.content.ContextCompat.RECEIVER_NOT_EXPORTED
import androidx.core.content.ContextCompat.registerReceiver
import androidx.lifecycle.Lifecycle.Event.ON_START
import androidx.lifecycle.Lifecycle.Event.ON_STOP
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.ProcessLifecycleOwner
import androidx.window.core.layout.WindowHeightSizeClass
import androidx.window.core.layout.WindowSizeClass
import androidx.window.core.layout.WindowWidthSizeClass
import androidx.window.layout.WindowMetricsCalculator
import com.salesforce.androidsdk.BuildConfig.DEBUG
import com.salesforce.androidsdk.R.string.account_type
import com.salesforce.androidsdk.R.string.sf__dev_support_title
import com.salesforce.androidsdk.R.style.SalesforceSDK_AlertDialog
import com.salesforce.androidsdk.R.style.SalesforceSDK_AlertDialog_Dark
import com.salesforce.androidsdk.accounts.UserAccount
import com.salesforce.androidsdk.accounts.UserAccountManager
import com.salesforce.androidsdk.accounts.UserAccountManager.USER_SWITCH_TYPE_LOGOUT
import com.salesforce.androidsdk.analytics.EventBuilderHelper.createAndStoreEvent
import com.salesforce.androidsdk.analytics.SalesforceAnalyticsManager
import com.salesforce.androidsdk.analytics.security.Encryptor
import com.salesforce.androidsdk.app.Features.FEATURE_APP_IS_IDP
import com.salesforce.androidsdk.app.Features.FEATURE_APP_IS_SP
import com.salesforce.androidsdk.app.Features.FEATURE_BROWSER_LOGIN
import com.salesforce.androidsdk.app.SalesforceSDKManager.Theme.DARK
import com.salesforce.androidsdk.app.SalesforceSDKManager.Theme.SYSTEM_DEFAULT
import com.salesforce.androidsdk.auth.AuthenticatorService.KEY_INSTANCE_URL
import com.salesforce.androidsdk.auth.HttpAccess
import com.salesforce.androidsdk.auth.HttpAccess.DEFAULT
import com.salesforce.androidsdk.auth.NativeLoginManager
import com.salesforce.androidsdk.auth.OAuth2.revokeRefreshToken
import com.salesforce.androidsdk.auth.idp.SPConfig
import com.salesforce.androidsdk.auth.idp.interfaces.IDPManager
import com.salesforce.androidsdk.auth.idp.interfaces.SPManager
import com.salesforce.androidsdk.config.AdminPermsManager
import com.salesforce.androidsdk.config.AdminSettingsManager
import com.salesforce.androidsdk.config.BootConfig.getBootConfig
import com.salesforce.androidsdk.config.LoginServerManager
import com.salesforce.androidsdk.config.LoginServerManager.PRODUCTION_LOGIN_URL
import com.salesforce.androidsdk.config.LoginServerManager.SANDBOX_LOGIN_URL
import com.salesforce.androidsdk.config.RuntimeConfig.ConfigKey.IDPAppPackageName
import com.salesforce.androidsdk.config.RuntimeConfig.getRuntimeConfig
import com.salesforce.androidsdk.developer.support.notifications.local.ShowDeveloperSupportNotifier.Companion.BROADCAST_INTENT_ACTION_SHOW_DEVELOPER_SUPPORT
import com.salesforce.androidsdk.developer.support.notifications.local.ShowDeveloperSupportNotifier.Companion.hideDeveloperSupportNotification
import com.salesforce.androidsdk.developer.support.notifications.local.ShowDeveloperSupportNotifier.Companion.showDeveloperSupportNotification
import com.salesforce.androidsdk.push.PushMessaging
import com.salesforce.androidsdk.push.PushMessaging.UNREGISTERED_ATTEMPT_COMPLETE_EVENT
import com.salesforce.androidsdk.push.PushMessaging.isRegistered
import com.salesforce.androidsdk.push.PushMessaging.unregister
import com.salesforce.androidsdk.push.PushNotificationInterface
import com.salesforce.androidsdk.push.PushService
import com.salesforce.androidsdk.rest.ClientManager
import com.salesforce.androidsdk.rest.ClientManager.LoginOptions
import com.salesforce.androidsdk.rest.RestClient
import com.salesforce.androidsdk.security.BiometricAuthenticationManager
import com.salesforce.androidsdk.security.SalesforceKeyGenerator.getEncryptionKey
import com.salesforce.androidsdk.security.ScreenLockManager
import com.salesforce.androidsdk.ui.AccountSwitcherActivity
import com.salesforce.androidsdk.ui.DevInfoActivity
import com.salesforce.androidsdk.ui.LoginActivity
import com.salesforce.androidsdk.util.AuthConfigUtil.getMyDomainAuthConfig
import com.salesforce.androidsdk.util.EventsObservable
import com.salesforce.androidsdk.util.EventsObservable.EventType.AppCreateComplete
import com.salesforce.androidsdk.util.EventsObservable.EventType.LogoutComplete
import com.salesforce.androidsdk.util.SalesforceSDKLogger.e
import com.salesforce.androidsdk.util.SalesforceSDKLogger.w
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.Default
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import org.json.JSONObject
import java.lang.String.CASE_INSENSITIVE_ORDER
import java.net.URI
import java.util.Locale.US
import java.util.SortedSet
import java.util.UUID.randomUUID
import java.util.concurrent.ConcurrentSkipListSet
import java.util.regex.Pattern
import com.salesforce.androidsdk.auth.idp.IDPManager as DefaultIDPManager
import com.salesforce.androidsdk.auth.idp.SPManager as DefaultSPManager
import com.salesforce.androidsdk.auth.interfaces.NativeLoginManager as NativeLoginManagerInterface
import com.salesforce.androidsdk.security.interfaces.BiometricAuthenticationManager as BiometricAuthenticationManagerInterface
/**
* This class serves as an interface to the various functions of the Salesforce
* SDK. In order to use the SDK, your app must first instantiate the singleton
* SalesforceSDKManager object by calling the static init() method. After
* calling init(), use the static getInstance() method to access the singleton
* SalesforceSDKManager object.
*
* TODO: Remove the Android `Context` property of this object, as it is a memory leak.
*
* @param context The Android context
* @param mainActivity Activity that should be launched after the login flow
* @param loginActivity Login activity
*/
open class SalesforceSDKManager protected constructor(
@JvmField
protected val context: Context,
mainActivity: Class<out Activity>,
private val loginActivity: Class<out Activity>? = null,
internal val nativeLoginActivity: Class<out Activity>? = null,
) : LifecycleObserver {
constructor(
context: Context,
mainActivity: Class<out Activity>,
loginActivity: Class<out Activity>? = null
) : this(context, mainActivity, loginActivity, nativeLoginActivity = null)
/** The Android context */
val appContext: Context = context
/** Login options associated with the app */
private var loginOptionsInternal: LoginOptions? = null
/**
* Returns the class for the main activity.
*
* @return The class for the main activity.
*/
val mainActivityClass: Class<out Activity>
/**
* Null or an authenticated Activity for private use when developer support
* is enabled.
*/
private var authenticatedActivityForDeveloperSupport: Activity? = null
/**
* Null or the Android Activity lifecycle callbacks object registered when
* developer support is enabled.
*/
private var activityLifecycleCallbacksForDeveloperSupport: ActivityLifecycleCallbacks? = null
/**
* Null or the show developer support Android broadcast Intent receiver when
* developer support is enabled.
*/
private var showDeveloperSupportBroadcastIntentReceiver: BroadcastReceiver? = null
val webviewLoginActivityClass: Class<out Activity> = loginActivity ?: LoginActivity::class.java
/**
* The class of the activity used to perform the login process and create
* the account.
*/
val loginActivityClass: Class<out Activity> = nativeLoginActivity ?: webviewLoginActivityClass
/** The class for the account switcher activity */
var accountSwitcherActivityClass = AccountSwitcherActivity::class.java
/** The screen lock manager initialization synchronization lock object */
private val screenLockManagerLock = Any()
/** The Salesforce SDK manager's screen lock manager */
internal var screenLockManager: ScreenLockManager? = null
@JvmName("getScreenLockManager")
get() = field ?: synchronized(screenLockManagerLock) {
ScreenLockManager()
}.also { field = it }
/** The screen lock manager initialization synchronization lock object */
private val bioAuthManagerLock = Any()
/** The Salesforce SDK manager's biometric authentication manager */
var biometricAuthenticationManager: BiometricAuthenticationManagerInterface? = null
get() = field ?: synchronized(bioAuthManagerLock) {
BiometricAuthenticationManager()
}.also { field = it }
/** The Salesforce SDK manager's login server manager */
val loginServerManager by lazy {
LoginServerManager(appContext)
}
/** The Salesforce SDK manager's native login manager */
var nativeLoginManager: NativeLoginManagerInterface? = null
private set
/** Optionally enables features for automated testing.
*
* Note that accessors are named for compatibility with Salesforce Mobile
* SDK 11 */
@Suppress("RedundantGetter", "RedundantSetter")
var isTestRun = false
@JvmName("getIsTestRun")
get() = field
@JvmName("setIsTestRun")
set(value) {
field = value
}
/** Indicates if logout is in progress */
var isLoggingOut = false
private set
/** The Salesforce SDK manager's admin settings manager */
var adminSettingsManager: AdminSettingsManager? = null
get() = field ?: AdminSettingsManager().also { field = it }
/** The Salesforce SDK manager's admin permissions manager */
var adminPermsManager: AdminPermsManager? = null
get() = field ?: AdminPermsManager().also { field = it }
/**
* An implementation of [PushNotificationInterface] that handles received
* push notifications.
*/
@get:Synchronized
@set:Synchronized
var pushNotificationReceiver: PushNotificationInterface? = null
set(value) {
field = value
PushMessaging.onPushReceiverSetup(appContext)
}
/**
* The class fulfilling push notification registration features. A default
* implementation is provided in [PushService]. Setting this property to a
* subclass will inject the specified class instead.
*
* Note, the specified class no longer needs to be specified in the Android
* manifest as a service.
*/
@Suppress("unused")
@get:Synchronized
@set:Synchronized
var pushServiceType: Class<out PushService> = PushService::class.java
/** The unique device ID */
@SuppressLint("HardwareIds")
val deviceId: String = getString(appContext.contentResolver, ANDROID_ID)
/** App feature codes for reporting in the user agent header */
private val features: SortedSet<String?>
/**
* An additional list of OAuth keys to fetch and store from the token
* endpoint
*/
var additionalOauthKeys: List<String>? = null
/**
* The login brand. In the following example, "<brand>" should be set here.
* https://community.force.com/services/oauth2/authorize/<brand>?response_type=code&...
*
* Note: This API might change in the future.
*/
@set:Synchronized
var loginBrand: String? = null
/**
* Optionally enables browser based login instead of web view login. This
* should NOT be used directly by apps as this is meant for internal use
* based on the value configured on the server
*/
@set:Synchronized
var isBrowserLoginEnabled = false
private set
/** Optionally enables browser session sharing */
var isShareBrowserSessionEnabled = false
private set
/**
* The custom tab browser to use during advanced authentication.
* NB: The default browser on the device is used:
* - If null is specified
* - Or, if the specified browser is not installed
*
* Defaults to Chrome.
*/
@get:Synchronized
@set:Synchronized
var customTabBrowser: String? = "com.android.chrome"
/**
* Optionally enables the web server flow for web view log on. Defaults to
* true
*/
@get:JvmName("shouldUseWebServerAuthentication")
@set:Synchronized
var useWebServerAuthentication = true
/**
* Optionally, enables the hybrid authentication flow. Defaults to true
*/
@Synchronized
fun shouldUseHybridAuthentication() = true
/**
* The regular expression pattern used to detect "Use Custom Domain" input
* from login web view.
*
* Example for a specific org:
* "^https:\\/\\/mobilesdk\\.my\\.salesforce\\.com\\/\\?startURL=%2Fsetup%2Fsecur%2FRemoteAccessAuthorizationPage\\.apexp"
*
* For any my domain:
* "^https:\\/\\/[a-zA-Z0-9]+\\.my\\.salesforce\\.com/\\?startURL=%2Fsetup%2Fsecur%2FRemoteAccessAuthorizationPage\\.apexp"
*/
@JvmField
@get:Synchronized
@set:Synchronized
var customDomainInferencePattern: Pattern? = null
/**
* The Salesforce Mobile SDK user interface theme. The value is not
* persistent across instances of Salesforce SDK Manager
*/
@set:Synchronized
var theme = SYSTEM_DEFAULT
/**
* The app name to use in [.getUserAgent]. This string must only contain
* printable ASCII characters.
*
* By default, the display name under
* [android.content.pm.ApplicationInfo.labelRes] will be used.
*/
@get:JvmName("provideAppName")
var appName: String? = null
get() = runCatching {
if (field == null) {
val packageInfo = appContext.packageManager.getPackageInfo(
appContext.packageName, 0
)
appName = appContext.getString(
packageInfo.applicationInfo.labelRes
)
}
field
}.onFailure { e ->
w(TAG, "Package info could not be retrieved", e)
}.getOrDefault("")
/**
* The Salesforce SDK manager's admin settings manager. Only
* defined if setAllowedSPApps() was called first
*/
var idpManager: IDPManager? = null
private set
/**
* The Salesforce SDK manager's SP manager. Only defined if
* setIdpAppPackageName() was called first
*/
var spManager: SPManager? = null
private set
/** Indicates if IDP login flow is enabled */
val isIDPLoginFlowEnabled
get() = spManager != null
/**
* The available Mobile SDK style themes.
*/
enum class Theme {
LIGHT,
DARK,
SYSTEM_DEFAULT
}
/** The developer support dialog */
private var devActionsDialog: AlertDialog? = null
/**
* The app specified option to enable developer support features, which
* overrides the default value from BuildConfig.DEBUG.
*/
private var isDevSupportEnabledOverride: Boolean? = null
/**
* Indicates if developer support features are enabled. Defaults to
* BuildConfig.DEBUG unless another value is specified.
* @return Boolean true enables developer support features; false otherwise
*/
fun isDevSupportEnabled() = isDevSupportEnabledOverride ?: isDebugBuild
/**
* Sets if developer support features are enabled.
* @param value Boolean true enables developer support features; false
* otherwise
*/
@Suppress("unused")
fun setIsDevSupportEnabled(value: Boolean) {
isDevSupportEnabledOverride = value
}
/** Initializer */
init {
mainActivityClass = mainActivity
features = ConcurrentSkipListSet(CASE_INSENSITIVE_ORDER)
/*
* Checks if an analytics app name has already been set by the app.
* If not, fetches the default app name to be used and sets it.
*/
val currentAiltnAppName = ailtnAppName
if (isEmpty(currentAiltnAppName)) {
var ailtnAppName: String? = null
runCatching {
val packageInfo = appContext.packageManager.getPackageInfo(appContext.packageName, 0)
ailtnAppName = appContext.getString(packageInfo.applicationInfo.labelRes)
}.onFailure { e ->
e(TAG, "Package not found", e)
}
if (!isEmpty(ailtnAppName)) {
Companion.ailtnAppName = ailtnAppName
}
}
// If the app runs in multiple processes, all Salesforce SDK manager instances need to run cleanup during logout.
val cleanupReceiver = CleanupReceiver()
registerReceiver(
appContext,
cleanupReceiver,
IntentFilter(CLEANUP_INTENT_ACTION),
RECEIVER_NOT_EXPORTED
)
Handler(getMainLooper()).post {
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
}
}
/** Login options associated with the app */
val loginOptions: LoginOptions get() = getLoginOptions(null, null)
/**
* Sets the login options associated with the app.
*
* @param jwt The `jwt`
* @param url The URL
*/
fun getLoginOptions(
jwt: String?,
url: String?
) = loginOptionsInternal?.apply {
this.jwt = jwt
setUrl(url)
} ?: getBootConfig(
appContext
).let { config ->
when {
isEmpty(jwt) -> LoginOptions(
url,
config.oauthRedirectURI,
config.remoteAccessConsumerKey,
config.oauthScopes
)
else -> LoginOptions(
url,
config.oauthRedirectURI,
config.remoteAccessConsumerKey,
config.oauthScopes,
jwt
)
}.also { loginOptionsInternal = it }
}
/**
* Indicates if the Salesforce Mobile SDK should automatically log out when
* the access token is revoked. When overriding this method to return false,
* the subclass is responsible for handling cleanup when the access token is
* revoked.
*
* @return True if the Salesforce Mobile SDK should automatically logout when
* the access token is revoked
*/
fun shouldLogoutWhenTokenRevoked() = true
/** The Salesforce SDK manager's user account manager */
val userAccountManager: UserAccountManager by lazy {
UserAccountManager.getInstance()
}
/**
* Sets authentication ability for Salesforce integration users. When true,
* Salesforce integration users will be prohibited from initial
* authentication and receive an error message.
*
* Defaults to false as Salesforce-authored apps are the primary audience
* for this option. This functionality will eventually be provided by the
* backend.
*/
var shouldBlockSalesforceIntegrationUser = false
/**
* Creates a NativeLoginManager instance that allows the app to use its
* own native UI for authentication.
*
* @param consumerKey The Connected App consumer key.
* @param callbackUrl The Connected App redirect URI.
* @param communityUrl The login url for native login.
* @param reCaptchaSiteKeyId The Google Cloud project reCAPTCHA Key's "Id"
* as shown in Google Cloud Console under "Products & Solutions", "Security"
* and "reCAPTCHA Enterprise"
* @param googleCloudProjectId The Google Cloud project's "Id" as shown in
* Google Cloud Console
* @param isReCaptchaEnterprise Specifies if reCAPTCHA uses the enterprise
* license
* @return The Native Login Manager.
*/
fun useNativeLogin(
consumerKey: String,
callbackUrl: String,
communityUrl: String,
reCaptchaSiteKeyId: String? = null,
googleCloudProjectId: String? = null,
isReCaptchaEnterprise: Boolean = false
): NativeLoginManagerInterface {
nativeLoginManager = NativeLoginManager(
consumerKey,
callbackUrl,
communityUrl,
reCaptchaSiteKeyId,
googleCloudProjectId,
isReCaptchaEnterprise
)
return nativeLoginManager as NativeLoginManagerInterface
}
/**
* Optionally enables browser based login instead of web view login. This
* should NOT be used directly by apps as this is meant for internal use
* based on the value configured on the server.
*
* @param browserLoginEnabled True if Chrome should be used for login; false
* otherwise
* @param shareBrowserSessionEnabled True enables browser session sharing;
* false otherwise
*/
@Synchronized
fun setBrowserLoginEnabled(
browserLoginEnabled: Boolean,
shareBrowserSessionEnabled: Boolean
) {
isBrowserLoginEnabled = browserLoginEnabled
isShareBrowserSessionEnabled = shareBrowserSessionEnabled
when {
browserLoginEnabled ->
registerUsedAppFeature(FEATURE_BROWSER_LOGIN)
else ->
unregisterUsedAppFeature(FEATURE_BROWSER_LOGIN)
}
}
/** Indicates if this app is configured as an identity provider */
private val isIdentityProvider
get() = idpManager != null
/**
* Sets the IDP package name for this app.
* As a result, this app gets an SP Manager and can be used as an SP
* @param idpAppPackageName The IDP app package name
*/
fun setIDPAppPackageName(idpAppPackageName: String?) {
registerUsedAppFeature(FEATURE_APP_IS_SP)
spManager = idpAppPackageName?.let { DefaultSPManager(it) }
}
/**
* Sets the allowed SP apps for this app.
* As a result this app gets an IDP manager and can be used as an IDP
* @param allowedSPApps The list of allows SP app
*/
@Suppress("unused")
fun setAllowedSPApps(allowedSPApps: List<SPConfig>) {
registerUsedAppFeature(FEATURE_APP_IS_IDP)
idpManager = DefaultIDPManager(allowedSPApps)
}
/** Returns the app display name used by the passcode dialog */
@Suppress("unused")
val appDisplayString = DEFAULT_APP_DISPLAY_NAME
/** Returns the name of the app as defined in AndroidManifest.xml */
val applicationName
get() = appContext.packageManager.getApplicationLabel(
appContext.applicationInfo
).toString()
/**
* Indicates if a network connection is available.
*
* @return True if a network connection is available
*/
fun hasNetwork() = DEFAULT.hasNetwork()
/**
* Cleans cached credentials and data.
*
* @param frontActivity The front activity
* @param account The user account
* @param shouldDismissActivity Dismisses the current activity if true; does
* nothing otherwise
*/
private fun cleanUp(
frontActivity: Activity?,
account: Account?,
shouldDismissActivity: Boolean
) {
val userAccount = UserAccountManager.getInstance().buildUserAccount(account)
// Clean up within this process
cleanUp(userAccount)
// Clean up Salesforce SDK manager instances in separate processes
sendCleanupIntent(userAccount)
val users = userAccountManager.authenticatedUsers
// If this is the last account, finish the front activity if specified
if (shouldDismissActivity && frontActivity != null && (users == null || users.size <= 1)) {
frontActivity.finish()
}
/*
* Check how many authenticated accounts are left. If only one account
* is left, this is the account that is being removed. In this case,
* safely reset the screen lock manager, admin prefs and encryption
* keys. Otherwise, don't reset the screen lock manager and admin prefs
* since there might be other accounts on that same org and these
* policies are stored at the org level.
*/
if (users == null || users.size <= 1) {
adminSettingsManager?.resetAll()
adminPermsManager?.resetAll()
adminSettingsManager = null
adminPermsManager = null
screenLockManager?.reset()
screenLockManager = null
biometricAuthenticationManager = null
}
}
/**
* Clean up cached data.
*
* @param userAccount The user account
*/
protected open fun cleanUp(userAccount: UserAccount?) {
SalesforceAnalyticsManager.reset(userAccount)
RestClient.clearCaches(userAccount)
UserAccountManager.getInstance().clearCachedCurrentUser()
userAccount?.let { userAccountResolved ->
screenLockManager?.cleanUp(userAccountResolved)
(biometricAuthenticationManager as BiometricAuthenticationManager)
.cleanUp(userAccountResolved)
}
}
/**
* Starts the login flow if user account has been removed.
*/
@Suppress("MemberVisibilityCanBePrivate")
protected fun startLoginPage() {
// Clear cookies
CookieManager.getInstance().removeAllCookies(null)
// Restart the app
appContext.startActivity(
Intent(
appContext,
mainActivityClass
).apply {
setPackage(appContext.packageName)
flags = FLAG_ACTIVITY_NEW_TASK
})
}
/**
* Starts the account switcher activity if an account has been removed.
*/
private fun startSwitcherActivityIfRequired() {
// Clear cookies
CookieManager.getInstance().removeAllCookies(null)
/*
* If the number of accounts remaining is 0, show the login page.
*
* If the number of accounts remaining is 1, switch to that user
* automatically.
*
* If there is more than 1 account logged in, shows the account switcher
* screen so that the user can pick which account to switch to
*/
val userAccMgr = userAccountManager
val accounts = userAccMgr.authenticatedUsers
if (accounts == null || accounts.size == 0) {
startLoginPage()
} else if (accounts.size == 1) {
userAccMgr.switchToUser(
accounts[0],
USER_SWITCH_TYPE_LOGOUT,
null
)
} else {
appContext.startActivity(Intent(
appContext,
accountSwitcherActivityClass
).apply {
flags = FLAG_ACTIVITY_NEW_TASK
})
}
}
/**
* Updates developer support features to match an Android Activity lifecycle
* event, including updating the app's authenticated Android Activity.
*
* @param authenticatedActivity The new authenticated Android Activity
* instance, or null
* @param lifecycleActivity The Android Activity instance provided by the
* Activity lifecycle event
*/
private fun updateDeveloperSupportForActivityLifecycle(
authenticatedActivity: Activity?,
lifecycleActivity: Activity
) {
// Assign the authenticated Activity
authenticatedActivityForDeveloperSupport = authenticatedActivity
// Display or hide the show developer support notification
when (userAccountManager.currentAccount == null || authenticatedActivityForDeveloperSupport == null) {
true -> hideDeveloperSupportNotification(lifecycleActivity)
else -> showDeveloperSupportNotification(lifecycleActivity)
}
}
/**
* Unregisters from push notifications.
* @param clientMgr The client manager
* @param showLoginPage Shows the login page after push notification
* unregistration
* @param refreshToken The refresh token
* @param loginServer The login server
* @param account The user account
* @param frontActivity The front activity
* @param isLastAccount Indicates if the account is the last authenticated
* account
*/
@Synchronized
private fun unregisterPush(
clientMgr: ClientManager,
showLoginPage: Boolean,
refreshToken: String,
loginServer: String?,
account: Account?,
frontActivity: Activity?,
isLastAccount: Boolean
) {
val intentFilter = IntentFilter(UNREGISTERED_ATTEMPT_COMPLETE_EVENT)
val pushUnregisterReceiver = object : BroadcastReceiver() {
override fun onReceive(
context: Context,
intent: Intent
) {
if (UNREGISTERED_ATTEMPT_COMPLETE_EVENT == intent.action) {
runCatching {
appContext.unregisterReceiver(this)
}.onFailure { e ->
e(TAG, "Exception occurred while un-registering", e)
}
removeAccount(
clientMgr,
showLoginPage,
refreshToken,
loginServer,
account,
frontActivity
)
}
}
}
registerReceiver(
appContext,
pushUnregisterReceiver,
intentFilter,
RECEIVER_NOT_EXPORTED
)
// Unregisters from notifications on logout
unregister(
appContext,
userAccountManager.buildUserAccount(account),
isLastAccount
)
}
/**
* Destroys the stored authentication credentials (removes the account)
* and, if requested, restarts the app.
*
* This overload uses a null user account.
*
* @param frontActivity The front activity
* @param showLoginPage If true, displays the login page after removing the
* account
*/
fun logout(
/* Note: Kotlin's @JvmOverloads annotations does not generate this overload */
frontActivity: Activity?,
showLoginPage: Boolean = true
) {
logout(null, frontActivity, showLoginPage)
}
/**
* Destroys the stored authentication credentials (removes the account)
* and, if requested, restarts the app.
*
* @param account The user account to logout. Defaults to the current user
* account
* @param frontActivity The front activity
* @param showLoginPage If true, displays the login page after removing the
* account
*/
@JvmOverloads
fun logout(
account: Account? = null,
frontActivity: Activity?,
showLoginPage: Boolean = true
) {
createAndStoreEvent("userLogout", null, TAG, null)
val clientMgr = ClientManager(
appContext,
accountType,
null,
shouldLogoutWhenTokenRevoked()
)
val accountToLogout = account ?: clientMgr.account
isLoggingOut = true
val mgr = AccountManager.get(appContext)
var refreshToken: String? = null
var loginServer: String? = null
if (accountToLogout != null) {
val encryptionKey = encryptionKey
refreshToken = decrypt(
mgr.getPassword(accountToLogout),
encryptionKey
)
loginServer = decrypt(
mgr.getUserData(
accountToLogout,
KEY_INSTANCE_URL
),
encryptionKey
)
}
/*
* Makes a call to un-register from push notifications only if the
* refresh token is available.
*/
val userAcc = userAccountManager.buildUserAccount(accountToLogout)
val numAccounts = mgr.getAccountsByType(accountType).size
if (isRegistered(
appContext,
userAcc
) && refreshToken != null
) {
unregisterPush(
clientMgr,
showLoginPage,
refreshToken,
loginServer,
accountToLogout,
frontActivity,
numAccounts == 1
)
} else {
removeAccount(
clientMgr,
showLoginPage,
refreshToken,
loginServer,
accountToLogout,
frontActivity
)
}
}
/**
* Removes the account upon logout.
*
* @param clientMgr The client manager instance
* @param showLoginPage If true, displays the login page after removing the
* account
* @param refreshToken The refresh token
* @param loginServer The login server
* @param account The user account
* @param frontActivity The front activity
*/
private fun removeAccount(
clientMgr: ClientManager,
showLoginPage: Boolean,
refreshToken: String?,
loginServer: String?,
account: Account?,
frontActivity: Activity?
) {
cleanUp(
frontActivity,
account,
showLoginPage
)
clientMgr.removeAccount(account)
isLoggingOut = false
notifyLogoutComplete(showLoginPage)
// Revoke the existing refresh token
if (shouldLogoutWhenTokenRevoked() && refreshToken != null) {
CoroutineScope(Default).launch {
runCatching {
revokeRefreshToken(
DEFAULT,
URI(loginServer),
refreshToken
)
}.onFailure { e ->
w(TAG, "Revoking token failed", e)
}
}
}
}
/**