forked from authgear/authgear-sdk-android
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainViewModel.java
More file actions
970 lines (872 loc) · 39.3 KB
/
Copy pathMainViewModel.java
File metadata and controls
970 lines (872 loc) · 39.3 KB
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
package com.oursky.authgeartest;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.biometric.BiometricManager;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import com.oursky.authgear.BiometricAuthenticator;
import com.oursky.authgear.PreAuthenticatedURLNotAllowedException;
import com.oursky.authgear.PreAuthenticatedURLOptions;
import com.oursky.authgear.Authgear;
import com.oursky.authgear.AuthgearDelegate;
import com.oursky.authgear.AuthenticateOptions;
import com.oursky.authgear.AuthgearException;
import com.oursky.authgear.BiometricOptions;
import com.oursky.authgear.CancelException;
import com.oursky.authgear.ColorScheme;
import com.oursky.authgear.CustomTabsUIImplementation;
import com.oursky.authgear.OnAuthenticateAnonymouslyListener;
import com.oursky.authgear.OnAuthenticateBiometricListener;
import com.oursky.authgear.OnAuthenticateListener;
import com.oursky.authgear.OnConfigureListener;
import com.oursky.authgear.OnEnableBiometricListener;
import com.oursky.authgear.OnFetchUserInfoListener;
import com.oursky.authgear.OnHandleApp2AppAuthenticationRequestListener;
import com.oursky.authgear.OnLogoutListener;
import com.oursky.authgear.OnMakePreAuthenticatedURLListener;
import com.oursky.authgear.OnOpenAuthorizationURLListener;
import com.oursky.authgear.OnOpenSettingsActionListener;
import com.oursky.authgear.OnOpenURLListener;
import com.oursky.authgear.OnPromoteAnonymousUserListener;
import com.oursky.authgear.OnReauthenticateListener;
import com.oursky.authgear.OnRefreshIDTokenListener;
import com.oursky.authgear.OnWechatAuthCallbackListener;
import com.oursky.authgear.OpenAuthorizationURLOptions;
import com.oursky.authgear.Page;
import com.oursky.authgear.PersistentTokenStorage;
import com.oursky.authgear.PromoteOptions;
import com.oursky.authgear.ReauthenticateOptions;
import com.oursky.authgear.SessionState;
import com.oursky.authgear.SessionStateChangeReason;
import com.oursky.authgear.SettingOptions;
import com.oursky.authgear.TokenStorage;
import com.oursky.authgear.SettingsActionOptions;
import com.oursky.authgear.TransientTokenStorage;
import com.oursky.authgear.UIImplementation;
import com.oursky.authgear.UserInfo;
import com.oursky.authgear.WebKitWebViewUIImplementation;
import com.oursky.authgear.app2app.App2AppAuthenticateOptions;
import com.oursky.authgear.app2app.App2AppAuthenticateRequest;
import com.oursky.authgear.app2app.App2AppOptions;
import com.oursky.authgear.net.HTTPClient;
import com.oursky.authgeartest.wxapi.WXEntryActivity;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import java.util.Date;
import java.util.List;
@SuppressWarnings("ConstantConditions")
public class MainViewModel extends AndroidViewModel implements AuthgearDelegate {
private static final List<BiometricAuthenticator> ALLOWED_AUTHENTICATORS_ON_ENABLE = List.of(BiometricAuthenticator.BIOMETRIC_STRONG);
private static final List<BiometricAuthenticator> ALLOWED_AUTHENTICATORS_ON_AUTHENTICATE = List.of(BiometricAuthenticator.BIOMETRIC_STRONG, BiometricAuthenticator.DEVICE_CREDENTIAL);
private static final String TAG = MainViewModel.class.getSimpleName();
private Authgear mAuthgear = null;
private IWXAPI wechatAPI;
final private MutableLiveData<Boolean> mIsConfigured = new MutableLiveData<>(false);
final private MutableLiveData<String> mClientID = new MutableLiveData<>("");
final private MutableLiveData<String> mEndpoint = new MutableLiveData<>("");
final private MutableLiveData<String> mApp2AppEndpoint = new MutableLiveData<>("");
final private MutableLiveData<String> mOAuthProviderAlias = new MutableLiveData<>("");
final private MutableLiveData<String> mAuthenticationiFlowGroup = new MutableLiveData<>("");
final private MutableLiveData<String> mPreAuthenticatedURLClientID = new MutableLiveData<>("");
final private MutableLiveData<String> mPreAuthenticatedURLRedirectURI = new MutableLiveData<>("");
final private MutableLiveData<String> mPage = new MutableLiveData<>("");
final private MutableLiveData<String> mTokenStorage = new MutableLiveData<>("");
final private MutableLiveData<ColorScheme> mColorScheme = new MutableLiveData<>(null);
final private MutableLiveData<Boolean> mUseWebKitWebView = new MutableLiveData<>(false);
final private MutableLiveData<Boolean> mIsSsoEnabled = new MutableLiveData<>(false);
final private MutableLiveData<Boolean> mIsPreAuthenticatedURLEnabled = new MutableLiveData<>(false);
final private MutableLiveData<Boolean> mIsLoading = new MutableLiveData<>(false);
final private MutableLiveData<Boolean> mBiometricEnable = new MutableLiveData<>(false);
final private MutableLiveData<Boolean> mCanReauthenticate = new MutableLiveData<>(false);
final private MutableLiveData<UserInfo> mUserInfo = new MutableLiveData<>(null);
final private MutableLiveData<SessionState> mSessionState = new MutableLiveData<>(SessionState.UNKNOWN);
final private MutableLiveData<Throwable> mError = new MutableLiveData<>(null);
private Intent pendingApp2AppIntent = null;
final private MutableLiveData<Boolean> mAuthgearConfigured = new MutableLiveData<>(false);
final private MutableLiveData<ConfirmationViewModel> mApp2AppConfirmation = new MutableLiveData<>(null);
public MainViewModel(Application application) {
super(application);
MainApplication app = getApplication();
SharedPreferences preferences = app.getSharedPreferences("authgear.demo", Context.MODE_PRIVATE);
if (preferences != null) {
String storedClientID = preferences.getString("clientID", "");
String storedEndpoint = preferences.getString("endpoint", "");
String storedApp2AppEndpoint = preferences.getString("app2appendpoint", "");
String storedAuthenticationFlowGroup = preferences.getString("authenticationFlowGroup", "");
String storedPage = preferences.getString("page", "");
String storedTokenStorage = preferences.getString("tokenStorage", PersistentTokenStorage.class.getSimpleName());
String storedPreAuthenticatedURLClientID = preferences.getString("preAuthenticatedURLClientID", "");
String storedPreAuthenticatedURLRedirectURI = preferences.getString("preAuthenticatedURLRedirectURI", "");
Boolean storedIsSsoEnabled = preferences.getBoolean("isSsoEnabled", false);
Boolean storedIsPreAuthenticatedURLEnabled= preferences.getBoolean("isPreAuthenticatedURLEnabled", false);
Boolean storedUseWebKitWebView = preferences.getBoolean("useWebKitWebView", false);
mClientID.setValue(storedClientID);
mEndpoint.setValue(storedEndpoint);
mApp2AppEndpoint.setValue(storedApp2AppEndpoint);
mAuthenticationiFlowGroup.setValue(storedAuthenticationFlowGroup);
mPage.setValue(storedPage);
mTokenStorage.setValue(storedTokenStorage);
mIsSsoEnabled.setValue(storedIsSsoEnabled);
mIsPreAuthenticatedURLEnabled.setValue(storedIsPreAuthenticatedURLEnabled);
mPreAuthenticatedURLClientID.setValue(storedPreAuthenticatedURLClientID);
mPreAuthenticatedURLRedirectURI.setValue(storedPreAuthenticatedURLRedirectURI);
mUseWebKitWebView.setValue(storedUseWebKitWebView);
}
}
private void updateBiometricState() {
boolean supported = false;
try {
if (Build.VERSION.SDK_INT >= 23) {
mAuthgear.checkBiometricSupported(
this.getApplication(),
ALLOWED_AUTHENTICATORS_ON_ENABLE
);
supported = true;
}
} catch (Exception e) {}
boolean enabled = false;
if (supported) {
try {
enabled = mAuthgear.isBiometricEnabled();
} catch (Exception e) {}
}
mBiometricEnable.setValue(enabled);
}
private void resetState() {
mIsConfigured.setValue(true);
mCanReauthenticate.setValue(false);
mUserInfo.setValue(null);
mBiometricEnable.setValue(false);
mSessionState.setValue(SessionState.UNKNOWN);
mError.setValue(null);
}
private void setError(Throwable e) {
if (e instanceof CancelException) {
mError.setValue(null);
} else {
mError.setValue(e);
}
}
public void setOAuthProviderAlias(String s) {
mOAuthProviderAlias.setValue(s);
}
public void setAuthenticationiFlowGroup(String flowGroup) {
mAuthenticationiFlowGroup.setValue(flowGroup);
}
public void setPage(String page) {
mPage.setValue(page);
}
public void setTokenStorage(String tokenStorage) {
mTokenStorage.setValue(tokenStorage);
}
public void setColorScheme(ColorScheme colorScheme) {
mColorScheme.setValue(colorScheme);
}
public LiveData<String> clientID() {
return mClientID;
}
public LiveData<String> endpoint() {
return mEndpoint;
}
public LiveData<String> app2appEndpoint() {
return mApp2AppEndpoint;
}
public LiveData<String> preAuthenticatedURLRedirectURI() {
return mPreAuthenticatedURLRedirectURI;
}
public LiveData<String> preAuthenticatedURLClientID() {
return mPreAuthenticatedURLClientID;
}
public LiveData<Boolean> isPreAuthenticatedURLEnabled() {
return mIsPreAuthenticatedURLEnabled;
}
public LiveData<String> tokenStorage() { return mTokenStorage; }
public LiveData<Boolean> useWebKitWebView() { return mUseWebKitWebView; }
public LiveData<Boolean> isSsoEnabled() { return mIsSsoEnabled; }
public LiveData<Boolean> isConfigured() {
return mIsConfigured;
}
public LiveData<Boolean> isLoading() {
return mIsLoading;
}
public LiveData<Boolean> isBiometricEnabled() { return mBiometricEnable; }
public LiveData<Boolean> canReauthenticate() { return mCanReauthenticate; }
public LiveData<UserInfo> userInfo() {
return mUserInfo;
}
public LiveData<SessionState> sessionState() { return mSessionState; }
public LiveData<Throwable> error() {
return mError;
}
public LiveData<ConfirmationViewModel> app2appConfirmation() { return mApp2AppConfirmation; }
public void configure(
String clientID,
String endpoint,
Boolean isSsoEnabled,
Boolean useWebKitWebView,
String app2appEndpoint,
Boolean isPreAuthenticatedURLEnabled,
String preAuthenticatedURLClientID,
String preAuthenticatedURLRedirectURI) {
if (mIsLoading.getValue()) return;
mIsLoading.setValue(true);
MainApplication app = getApplication();
mClientID.setValue(clientID);
mEndpoint.setValue(endpoint);
mApp2AppEndpoint.setValue(app2appEndpoint);
mIsSsoEnabled.setValue(isSsoEnabled);
mIsPreAuthenticatedURLEnabled.setValue(isPreAuthenticatedURLEnabled);
mUseWebKitWebView.setValue(useWebKitWebView);
app.getSharedPreferences("authgear.demo", Context.MODE_PRIVATE)
.edit()
.putString("clientID", clientID)
.putString("endpoint", endpoint)
.putString("app2appendpoint", app2appEndpoint)
.putBoolean("isSsoEnabled", isSsoEnabled)
.putBoolean("isPreAuthenticatedURLEnabled", isPreAuthenticatedURLEnabled)
.putString("preAuthenticatedURLClientID", preAuthenticatedURLClientID)
.putString("preAuthenticatedURLRedirectURI", preAuthenticatedURLRedirectURI)
.putBoolean("useWebKitWebView", useWebKitWebView)
.apply();
Boolean isApp2AppEnabled = !app2appEndpoint.isEmpty();
App2AppOptions app2appOptions = new App2AppOptions(isApp2AppEnabled);
TokenStorage tokenStorage;
if (mTokenStorage.getValue().equals(TransientTokenStorage.class.getSimpleName())) {
tokenStorage = new TransientTokenStorage();
} else {
tokenStorage = new PersistentTokenStorage(getApplication());
}
UIImplementation uiImplementation;
if (mUseWebKitWebView.getValue()) {
WebKitWebViewUIImplementation impl = new WebKitWebViewUIImplementation();
impl.setActionBarBackgroundColor(0x00ffffff);
impl.setActionBarButtonTintColor(0xff000000);
impl.setWechatRedirectURI(Uri.parse(MainApplication.AUTHGEAR_WECHAT_REDIRECT_URI));
impl.setAuthgearDelegate(this);
uiImplementation = impl;
} else {
uiImplementation = new CustomTabsUIImplementation();
}
HTTPClient httpClient = new MyHTTPClient();
mAuthgear = new Authgear(
getApplication(),
clientID,
endpoint,
tokenStorage,
uiImplementation,
httpClient,
isSsoEnabled,
isPreAuthenticatedURLEnabled,
null,
app2appOptions
);
mAuthgear.configure(new OnConfigureListener() {
@Override
public void onConfigured() {
mIsLoading.setValue(false);
mAuthgearConfigured.setValue(true);
updateBiometricState();
handlePendingApp2AppRequest();
}
@Override
public void onConfigurationFailed(@NonNull Throwable throwable) {
Log.d(TAG, throwable.toString());
mIsLoading.setValue(false);
setError(throwable);
}
});
mAuthgear.setDelegate(this);
resetState();
wechatAPI = WXAPIFactory.createWXAPI(app, MainApplication.AUTHGEAR_WECHAT_APP_ID, true);
wechatAPI.registerApp(MainApplication.AUTHGEAR_WECHAT_APP_ID);
WXEntryActivity.setOnWeChatSendAuthResultListener((code, state) -> {
Log.d(TAG, "Sending WeChat Callback");
mAuthgear.wechatAuthCallback(code, state, new OnWechatAuthCallbackListener() {
@Override
public void onWechatAuthCallback() {
Log.d(TAG, "onWeChatAuthCallback");
}
@Override
public void onWechatAuthCallbackFailed(Throwable throwable) {
Log.e(TAG, "onWeChatAuthCallbackFailed", throwable);
}
});
});
}
@Override
public void onSessionStateChanged(Authgear container, SessionStateChangeReason reason) {
Log.d(TAG, "Session state=" + container.getSessionState() + " reason=" + reason);
this.mSessionState.setValue(container.getSessionState());
}
@Override
public void sendWechatAuthRequest(String state) {
Log.d(TAG, "Open wechat sdk state=" + state);
if (!this.wechatAPI.isWXAppInstalled()) {
setError(new RuntimeException("You have not installed the WeChat client app"));
return;
}
SendAuth.Req req = new SendAuth.Req();
req.scope = "snsapi_userinfo";
req.state = state;
this.wechatAPI.sendReq(req);
}
public void authenticate() {
mIsLoading.setValue(true);
AuthenticateOptions options = new AuthenticateOptions(MainApplication.AUTHGEAR_REDIRECT_URI);
options.setColorScheme(getColorScheme());
options.setPage(mPage.getValue());
options.setWechatRedirectURI(MainApplication.AUTHGEAR_WECHAT_REDIRECT_URI);
options.setAuthenticationFlowGroup(mAuthenticationiFlowGroup.getValue());
if (!mOAuthProviderAlias.getValue().isEmpty()) {
options.setOauthProviderAlias(mOAuthProviderAlias.getValue());
}
mAuthgear.authenticate(options, new OnAuthenticateListener() {
@Override
public void onAuthenticated(@Nullable UserInfo userInfo) {
mUserInfo.setValue(userInfo);
mCanReauthenticate.setValue(mAuthgear.getCanReauthenticate());
mIsLoading.setValue(false);
updateBiometricState();
}
@Override
public void onAuthenticationFailed(@NonNull Throwable throwable) {
Log.d(TAG, throwable.toString());
mIsLoading.setValue(false);
setError(throwable);
}
});
}
public void appendApp2AppRequest(Intent intent) {
this.pendingApp2AppIntent = intent;
if (mAuthgearConfigured.getValue()) {
handlePendingApp2AppRequest();
}
}
private void handlePendingApp2AppRequest() {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) {
throw new RuntimeException("app2app is not supported in current android version");
}
if (this.pendingApp2AppIntent == null) {
return;
}
Uri intentUri = this.pendingApp2AppIntent.getData();
this.pendingApp2AppIntent = null;
if (intentUri == null) {
return;
}
final App2AppAuthenticateRequest request = mAuthgear.parseApp2AppAuthenticationRequest(intentUri);
if (request == null) {
setError(new RuntimeException("Unexpected app2app uri"));
return;
}
if (mAuthgear.getSessionState() != SessionState.AUTHENTICATED) {
setError(new RuntimeException("must be in authenticated state to handle app2app request"));
return;
}
mAuthgear.fetchUserInfo(new OnFetchUserInfoListener() {
@Override
public void onFetchedUserInfo(@NonNull UserInfo userInfo) {
promptApp2AppConfirmation(userInfo, request);
}
@Override
public void onFetchingUserInfoFailed(@NonNull Throwable throwable) {
setError(throwable);
}
});
}
private void promptApp2AppConfirmation(UserInfo userInfo, App2AppAuthenticateRequest request) {
String message = "Approve app2app request?";
String userIdentity = "";
if (userInfo.getPhoneNumber() != null) {
userIdentity = userIdentity + "\n phone: " + userInfo.getPhoneNumber();
}
if (userInfo.getEmail() != null) {
userIdentity = userIdentity + "\n email: " + userInfo.getEmail();
}
if (!userIdentity.isEmpty()) {
message = message + "\ncurrent user:" + userIdentity;
}
if (request.getState() != null && !request.getState().isEmpty()) {
message = message + "\nstate: " + request.getState();
}
mApp2AppConfirmation.setValue(new ConfirmationViewModel(message) {
@Override
public void onConfirm() {
mAuthgear.approveApp2AppAuthenticationRequest(request, new OnHandleApp2AppAuthenticationRequestListener() {
@Override
public void onFinished() {
Log.d(TAG, "Handled app2app request successfully");
}
@Override
public void onFailed(@NonNull Throwable throwable) {
Log.d(TAG, throwable.toString());
setError(throwable);
}
});
}
@Override
public void onCancel() {
mApp2AppConfirmation.postValue(null);
mAuthgear.rejectApp2AppAuthenticationRequest(request, new AuthgearException("rejected"),new OnHandleApp2AppAuthenticationRequestListener() {
@Override
public void onFinished() {
Log.d(TAG, "Rejected app2app request successfully");
}
@Override
public void onFailed(@NonNull Throwable throwable) {
Log.d(TAG, throwable.toString());
setError(throwable);
}
});
}
});
}
public void authenticateApp2App(String state) {
mIsLoading.setValue(true);
App2AppAuthenticateOptions options = new App2AppAuthenticateOptions(
mApp2AppEndpoint.getValue(),
MainApplication.AUTHGEAR_APP2APP_REDIRECT_URI,
state);
mAuthgear.startApp2AppAuthentication(options, new OnAuthenticateListener() {
@Override
public void onAuthenticated(@Nullable UserInfo userInfo) {
mUserInfo.setValue(userInfo);
mCanReauthenticate.setValue(mAuthgear.getCanReauthenticate());
mIsLoading.setValue(false);
updateBiometricState();
}
@Override
public void onAuthenticationFailed(@NonNull Throwable throwable) {
Log.d(TAG, throwable.toString());
mIsLoading.setValue(false);
setError(throwable);
}
});
}
public void reauthenticate(FragmentActivity activity) {
mIsLoading.setValue(true);
mAuthgear.refreshIDToken(new OnRefreshIDTokenListener() {
@Override
public void onFinished() {
if (mAuthgear.getCanReauthenticate()) {
ReauthenticateOptions options = new ReauthenticateOptions(MainApplication.AUTHGEAR_REDIRECT_URI);
options.setWechatRedirectURI(MainApplication.AUTHGEAR_WECHAT_REDIRECT_URI);
options.setColorScheme(getColorScheme());
options.setAuthenticationFlowGroup(mAuthenticationiFlowGroup.getValue());
if (!mOAuthProviderAlias.getValue().isEmpty()) {
options.setOauthProviderAlias(mOAuthProviderAlias.getValue());
}
mAuthgear.reauthenticate(options, makeBiometricOptions(activity), new OnReauthenticateListener() {
@Override
public void onFinished(@Nullable UserInfo userInfo) {
mUserInfo.setValue(userInfo);
mIsLoading.setValue(false);
}
@Override
public void onFailed(@NonNull Throwable throwable) {
Log.d(TAG, throwable.toString());
mIsLoading.setValue(false);
setError(throwable);
}
});
}
}
@Override
public void onFailed(Throwable throwable) {
Log.d(TAG, throwable.toString());
mIsLoading.setValue(false);
setError(throwable);
}
});
}
public void reauthenticateWebOnly() {
mIsLoading.setValue(true);
mAuthgear.refreshIDToken(new OnRefreshIDTokenListener() {
@Override
public void onFinished() {
if (mAuthgear.getCanReauthenticate()) {
ReauthenticateOptions options = new ReauthenticateOptions(MainApplication.AUTHGEAR_REDIRECT_URI);
options.setWechatRedirectURI(MainApplication.AUTHGEAR_WECHAT_REDIRECT_URI);
mAuthgear.reauthenticate(options, null, new OnReauthenticateListener() {
@Override
public void onFinished(@Nullable UserInfo userInfo) {
mUserInfo.setValue(userInfo);
mIsLoading.setValue(false);
}
@Override
public void onFailed(@NonNull Throwable throwable) {
Log.d(TAG, throwable.toString());
mIsLoading.setValue(false);
setError(throwable);
}
});
}
}
@Override
public void onFailed(Throwable throwable) {
Log.d(TAG, throwable.toString());
mIsLoading.setValue(false);
setError(throwable);
}
});
}
public void authenticateAnonymously() {
mIsLoading.setValue(true);
mAuthgear.authenticateAnonymously(new OnAuthenticateAnonymouslyListener() {
@Override
public void onAuthenticated(@NonNull UserInfo userInfo) {
mUserInfo.setValue(userInfo);
mCanReauthenticate.setValue(false);
mIsLoading.setValue(false);
updateBiometricState();
}
@Override
public void onAuthenticationFailed(@NonNull Throwable throwable) {
Log.d(TAG, throwable.toString());
mIsLoading.setValue(false);
setError(throwable);
}
});
}
private BiometricOptions makeBiometricOptions(FragmentActivity activity) {
return new BiometricOptions(
activity,
"Biometric authentication",
"Biometric authentication",
"Use biometric to authenticate",
"Cancel",
ALLOWED_AUTHENTICATORS_ON_ENABLE,
ALLOWED_AUTHENTICATORS_ON_AUTHENTICATE,
true
);
}
private ColorScheme getColorScheme() {
ColorScheme explicit = mColorScheme.getValue();
if (explicit != null) {
return explicit;
}
return getSystemColorScheme();
}
private ColorScheme getSystemColorScheme() {
int currentNightMode = getApplication().getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
if (currentNightMode == Configuration.UI_MODE_NIGHT_YES) {
return ColorScheme.DARK;
}
return ColorScheme.LIGHT;
}
public void enableBiometric(FragmentActivity activity) {
mIsLoading.setValue(true);
try {
mAuthgear.checkBiometricSupported(activity, ALLOWED_AUTHENTICATORS_ON_ENABLE);
} catch (Exception e) {
mIsLoading.setValue(false);
setError(e);
return;
}
mAuthgear.enableBiometric(
makeBiometricOptions(activity),
new OnEnableBiometricListener() {
@Override
public void onEnabled() {
mIsLoading.setValue(false);
updateBiometricState();
}
@Override
public void onFailed(Throwable throwable) {
mIsLoading.setValue(false);
setError(throwable);
}
}
);
}
public void disableBiometric() {
try {
mAuthgear.disableBiometric();
updateBiometricState();
} catch (Exception e) {
setError(e);
}
}
public void authenticateBiometric(FragmentActivity activity) {
mIsLoading.setValue(true);
mAuthgear.authenticateBiometric(
makeBiometricOptions(activity),
new OnAuthenticateBiometricListener() {
@Override
public void onAuthenticated(UserInfo userInfo) {
mIsLoading.setValue(false);
mUserInfo.setValue(userInfo);
mCanReauthenticate.setValue(mAuthgear.getCanReauthenticate());
updateBiometricState();
}
@Override
public void onAuthenticationFailed(Throwable throwable) {
Log.d(TAG, throwable.toString());
mIsLoading.setValue(false);
setError(throwable);
updateBiometricState();
}
}
);
}
public void logout() {
mIsLoading.setValue(true);
mAuthgear.logout(new OnLogoutListener() {
@Override
public void onLogout() {
mIsLoading.setValue(false);
mUserInfo.setValue(null);
mCanReauthenticate.setValue(false);
updateBiometricState();
}
@Override
public void onLogoutFailed(@NonNull Throwable throwable) {
Log.d(TAG, throwable.toString());
mIsLoading.setValue(false);
setError(throwable);
}
});
}
public void openSettings() {
mIsLoading.setValue(true);
SettingOptions options = new SettingOptions();
options.setColorScheme(getColorScheme());
options.setWechatRedirectURI(MainApplication.AUTHGEAR_WECHAT_REDIRECT_URI);
mAuthgear.open(Page.SETTINGS, options, new OnOpenURLListener() {
@Override
public void onClosed() {
mIsLoading.setValue(false);
Log.d(TAG, "openSettings closed");
}
@Override
public void onFailed(Throwable throwable) {
Log.d(TAG, throwable.toString());
mIsLoading.setValue(false);
setError(throwable);
}
});
}
public void openChangePassword() {
mIsLoading.setValue(true);
mAuthgear.refreshIDToken(new OnRefreshIDTokenListener() {
@Override
public void onFinished() {
SettingsActionOptions options = new SettingsActionOptions(
MainApplication.AUTHGEAR_REDIRECT_URI
);
options.setColorScheme(getColorScheme());
options.setWechatRedirectURI(MainApplication.AUTHGEAR_WECHAT_REDIRECT_URI);
mAuthgear.changePassword(options, new OnOpenSettingsActionListener() {
@Override
public void onFinished() {
mIsLoading.setValue(false);
Log.d(TAG, "changePassword finished");
}
@Override
public void onFailed(Throwable throwable) {
Log.d(TAG, throwable.toString());
mIsLoading.setValue(false);
setError(throwable);
}
});
}
@Override
public void onFailed(Throwable throwable) {
Log.d(TAG, throwable.toString());
mIsLoading.setValue(false);
setError(throwable);
}
});
}
public void openDeleteAccount() {
mIsLoading.setValue(true);
mAuthgear.refreshIDToken(new OnRefreshIDTokenListener() {
@Override
public void onFinished() {
SettingsActionOptions options = new SettingsActionOptions(
MainApplication.AUTHGEAR_REDIRECT_URI
);
options.setColorScheme(getColorScheme());
options.setWechatRedirectURI(MainApplication.AUTHGEAR_WECHAT_REDIRECT_URI);
mAuthgear.deleteAccount(options, new OnOpenSettingsActionListener() {
@Override
public void onFinished() {
mIsLoading.setValue(false);
Log.d(TAG, "deleteAccount finished");
}
@Override
public void onFailed(Throwable throwable) {
Log.d(TAG, throwable.toString());
mIsLoading.setValue(false);
setError(throwable);
}
});
}
@Override
public void onFailed(Throwable throwable) {
Log.d(TAG, throwable.toString());
mIsLoading.setValue(false);
setError(throwable);
}
});
}
public void promoteAnonymousUser() {
mIsLoading.setValue(true);
PromoteOptions options = new PromoteOptions(MainApplication.AUTHGEAR_REDIRECT_URI);
options.setWechatRedirectURI(MainApplication.AUTHGEAR_WECHAT_REDIRECT_URI);
options.setColorScheme(getColorScheme());
mAuthgear.promoteAnonymousUser(options, new OnPromoteAnonymousUserListener() {
@Override
public void onPromoted(@NonNull UserInfo userInfo) {
mUserInfo.setValue(userInfo);
mCanReauthenticate.setValue(mAuthgear.getCanReauthenticate());
mIsLoading.setValue(false);
}
@Override
public void onPromotionFailed(@NonNull Throwable throwable) {
Log.d(TAG, throwable.toString());
mIsLoading.setValue(false);
setError(throwable);
}
});
}
public void fetchUserInfo() {
mAuthgear.fetchUserInfo(new OnFetchUserInfoListener() {
@Override
public void onFetchedUserInfo(@NonNull UserInfo userInfo) {
mUserInfo.setValue(userInfo);
}
@Override
public void onFetchingUserInfoFailed(@NonNull Throwable throwable) {
mUserInfo.setValue(null);
setError(throwable);
}
});
}
public void showAuthTime(FragmentActivity activity) {
Date nullable = mAuthgear.getAuthTime();
if (nullable != null) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("auth_time");
builder.setMessage(nullable.toString());
builder.setPositiveButton("OK", (dialogInterface, i) -> {
});
builder.create().show();
}
}
public void preAuthenticatedURL(FragmentActivity activity) {
boolean shouldUseAnotherBrowser = !mPreAuthenticatedURLRedirectURI.getValue().isEmpty();
String targetRedirectURI = MainApplication.AUTHGEAR_REDIRECT_URI;
String targetClientID = mClientID.getValue();
if (!mPreAuthenticatedURLRedirectURI.getValue().isEmpty()) {
targetRedirectURI = mPreAuthenticatedURLRedirectURI.getValue();
}
if (!mPreAuthenticatedURLClientID.getValue().isEmpty()) {
targetClientID = mPreAuthenticatedURLClientID.getValue();
}
mIsLoading.setValue(true);
PreAuthenticatedURLOptions options = new PreAuthenticatedURLOptions(
targetClientID,
targetRedirectURI,
null
);
String finalTargetClientID = targetClientID;
mAuthgear.makePreAuthenticatedURL(options, new OnMakePreAuthenticatedURLListener() {
@Override
public void onSuccess(@NonNull Uri uri) {
mIsLoading.setValue(false);
UIImplementation uiImpl = new CustomTabsUIImplementation();
if (!shouldUseAnotherBrowser) {
uiImpl.openAuthorizationURL(
activity,
new OpenAuthorizationURLOptions(
uri,
Uri.parse(MainApplication.AUTHGEAR_REDIRECT_URI)
),
new OnOpenAuthorizationURLListener() {
@Override
public void onSuccess(@NonNull Uri url) {
Authgear newContainer = new Authgear(
getApplication(),
finalTargetClientID,
mEndpoint.getValue(),
new TransientTokenStorage(),
uiImpl,
new MyHTTPClient(),
true,
false,
"preAuthenticatedURL"
);
newContainer.configure(new OnConfigureListener() {
@Override
public void onConfigured() {
newContainer.authenticate(new AuthenticateOptions(
MainApplication.AUTHGEAR_REDIRECT_URI
), new OnAuthenticateListener() {
@Override
public void onAuthenticated(@NonNull UserInfo userInfo) {
promptPreAuthenticatedURLSuccessAlert(activity, userInfo);
}
@Override
public void onAuthenticationFailed(@NonNull Throwable throwable) {
// Ignore
}
});
}
@Override
public void onConfigurationFailed(@NonNull Throwable throwable) {}
});
}
@Override
public void onFailed(@NonNull Throwable e) {
setError(e);
}
}
);
} else {
uiImpl.openAuthorizationURL(
activity,
new OpenAuthorizationURLOptions(
uri,
Uri.parse(MainApplication.AUTHGEAR_REDIRECT_URI)
),
new OnOpenAuthorizationURLListener() {
@Override
public void onSuccess(@NonNull Uri url) {}
@Override
public void onFailed(@NonNull Throwable throwable) {}
}
);
}
}
@Override
public void onFailed(@NonNull Throwable e) {
if (e instanceof PreAuthenticatedURLNotAllowedException) {
Log.w(TAG, "pre authenticated url not allowed");
}
setError(e);
mIsLoading.setValue(false);
}
});
}
private void promptPreAuthenticatedURLSuccessAlert(Context context, UserInfo userInfo) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("PreAuthenticatedURL");
builder.setMessage("Successfully logged in");
builder.setPositiveButton("OK", (dialogInterface, i) -> {
});
builder.create().show();
}
}