-
-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathAuthenticatorActivity.java
More file actions
1794 lines (1536 loc) · 74.2 KB
/
AuthenticatorActivity.java
File metadata and controls
1794 lines (1536 loc) · 74.2 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
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
/*
* Nextcloud - Android Client
*
* SPDX-FileCopyrightText: 2023-2025 TSI-mc <surinder.kumar@t-systems.com>
* SPDX-FileCopyrightText: 2019-2021 Tobias Kaminsky <tobias@kaminsky.me>
* SPDX-FileCopyrightText: 2018 Andy Scherzinger <info@andy-scherzinger>
* SPDX-FileCopyrightText: 2017 Mario Danic <mario@lovelyhq.com>
* SPDX-FileCopyrightText: 2015 ownCloud Inc.
* SPDX-FileCopyrightText: 2013-2015 María Asensio Valverde <masensio@solidgear.es>
* SPDX-FileCopyrightText: 2013-2015 David A. Velasco <dvelasco@solidgear.es>
* SPDX-FileCopyrightText: 2011-2012 Bartosz Przybylski <bart.p.pl@gmail.com>
* SPDX-License-Identifier: GPL-2.0-only AND (AGPL-3.0-or-later OR GPL-2.0-only)
*/
package com.owncloud.android.authentication;
import android.Manifest;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.webkit.CookieManager;
import android.webkit.URLUtil;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import com.blikoon.qrcodescanner.QrCodeActivity;
import com.google.android.material.button.MaterialButton;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.nextcloud.android.common.ui.color.ColorUtil;
import com.nextcloud.android.common.ui.theme.utils.ColorRole;
import com.nextcloud.android.lib.resources.users.GenerateOneTimeAppPasswordRemoteOperation;
import com.nextcloud.client.account.User;
import com.nextcloud.client.account.UserAccountManager;
import com.nextcloud.client.device.DeviceInfo;
import com.nextcloud.client.di.Injectable;
import com.nextcloud.client.network.ClientFactory;
import com.nextcloud.client.onboarding.FirstRunActivity;
import com.nextcloud.client.onboarding.OnboardingService;
import com.nextcloud.client.preferences.AppPreferences;
import com.nextcloud.common.NextcloudClient;
import com.nextcloud.common.PlainClient;
import com.nextcloud.operations.PostMethod;
import com.nextcloud.utils.extensions.BundleExtensionsKt;
import com.nextcloud.utils.mdm.MDMConfig;
import com.owncloud.android.MainApp;
import com.owncloud.android.R;
import com.owncloud.android.databinding.AccountSetupBinding;
import com.owncloud.android.databinding.AccountSetupWebviewBinding;
import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.lib.common.OwnCloudAccount;
import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
import com.owncloud.android.lib.common.OwnCloudCredentials;
import com.owncloud.android.lib.common.OwnCloudCredentialsFactory;
import com.owncloud.android.lib.common.UserInfo;
import com.owncloud.android.lib.common.accounts.AccountUtils;
import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;
import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;
import com.owncloud.android.lib.common.network.CertificateCombinedException;
import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
import com.owncloud.android.lib.common.operations.RemoteOperation;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.status.OwnCloudVersion;
import com.owncloud.android.lib.resources.users.GetUserInfoRemoteOperation;
import com.owncloud.android.operations.DetectAuthenticationMethodOperation.AuthenticationMethod;
import com.owncloud.android.operations.GetCapabilitiesOperation;
import com.owncloud.android.operations.GetServerInfoOperation;
import com.owncloud.android.providers.DocumentsStorageProvider;
import com.owncloud.android.services.OperationsService;
import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
import com.owncloud.android.ui.NextcloudWebViewClient;
import com.owncloud.android.ui.activity.FileDisplayActivity;
import com.owncloud.android.ui.activity.SettingsActivity;
import com.owncloud.android.ui.dialog.IndeterminateProgressDialog;
import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;
import com.owncloud.android.utils.DisplayUtils;
import com.owncloud.android.utils.ErrorMessageAdapter;
import com.owncloud.android.utils.PermissionUtil;
import com.owncloud.android.utils.WebViewUtil;
import com.owncloud.android.utils.theme.ViewThemeUtils;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import androidx.appcompat.app.ActionBar;
import androidx.browser.auth.AuthTabIntent;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.ProcessLifecycleOwner;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import okhttp3.Credentials;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import static com.owncloud.android.utils.PermissionUtil.PERMISSIONS_CAMERA;
/**
* This Activity is used to add an ownCloud account to the App
*/
public class AuthenticatorActivity extends AccountAuthenticatorActivity
implements OnRemoteOperationListener, OnEditorActionListener, OnSslUntrustedCertListener,
AuthenticatorAsyncTask.OnAuthenticatorTaskListener, Injectable {
private static final String TAG = AuthenticatorActivity.class.getSimpleName();
public static final String EXTRA_ACTION = "ACTION";
public static final String EXTRA_ACCOUNT = "ACCOUNT";
public static final String EXTRA_USE_PROVIDER_AS_WEBLOGIN = "USE_PROVIDER_AS_WEBLOGIN";
private static final String KEY_HOST_URL_TEXT = "HOST_URL_TEXT";
private static final String KEY_OC_VERSION = "OC_VERSION";
private static final String KEY_SERVER_STATUS_TEXT = "SERVER_STATUS_TEXT";
private static final String KEY_SERVER_STATUS_ICON = "SERVER_STATUS_ICON";
private static final String KEY_IS_SSL_CONN = "IS_SSL_CONN";
private static final String KEY_AUTH_STATUS_TEXT = "AUTH_STATUS_TEXT";
private static final String KEY_AUTH_STATUS_ICON = "AUTH_STATUS_ICON";
private static final String KEY_SERVER_AUTH_METHOD = "SERVER_AUTH_METHOD";
private static final String KEY_WAITING_FOR_OP_ID = "WAITING_FOR_OP_ID";
private static final String KEY_ONLY_ADD = "onlyAdd";
public static final byte ACTION_CREATE = 0;
public static final byte ACTION_UPDATE_EXPIRED_TOKEN = 2; // detected by the app
public static final String UNTRUSTED_CERT_DIALOG_TAG = "UNTRUSTED_CERT_DIALOG";
private static final String WAIT_DIALOG_TAG = "WAIT_DIALOG";
private static final String KEY_AUTH_IS_FIRST_ATTEMPT_TAG = "KEY_AUTH_IS_FIRST_ATTEMPT";
private static final String KEY_USERNAME = "USERNAME";
private static final String KEY_PASSWORD = "PASSWORD";
private static final String KEY_ASYNC_TASK_IN_PROGRESS = "AUTH_IN_PROGRESS";
public static final String WEB_LOGIN = "/index.php/login/v2";
public static final String PROTOCOL_SUFFIX = "://";
public static final String LOGIN_URL_DATA_KEY_VALUE_SEPARATOR = ":";
public static final String HTTPS_PROTOCOL = "https://";
public static final String HTTP_PROTOCOL = "http://";
public static final int NO_ICON = 0;
public static final String EMPTY_STRING = "";
public static final int REQUEST_CODE_FIRST_RUN = 102;
/// parameters from EXTRAs in starter Intent
private byte mAction;
private Account mAccount;
/// activity-level references / state
private final Handler mHandler = new Handler();
private ServiceConnection mOperationsServiceConnection;
private OperationsServiceBinder mOperationsServiceBinder;
private AccountManager mAccountMgr;
/// Server PRE-Fragment elements
private AccountSetupBinding accountSetupBinding = null;
private AccountSetupWebviewBinding accountSetupWebviewBinding;
private String mServerStatusText = EMPTY_STRING;
private int mServerStatusIcon;
private GetServerInfoOperation.ServerInfo mServerInfo = new GetServerInfoOperation.ServerInfo();
/// Authentication PRE-Fragment elements
private String mAuthStatusText = EMPTY_STRING;
private int mAuthStatusIcon;
private AuthenticatorAsyncTask mAsyncTask;
private boolean mIsFirstAuthAttempt;
/// Identifier of operation in progress which result shouldn't be lost
private long mWaitingForOpId = Long.MAX_VALUE;
private boolean showWebViewLoginUrl;
private String webViewUser;
private String webViewPassword;
@Inject UserAccountManager accountManager;
@Inject AppPreferences preferences;
@Inject OnboardingService onboarding;
@Inject DeviceInfo deviceInfo;
@Inject PassCodeManager passCodeManager;
@Inject ViewThemeUtils.Factory viewThemeUtilsFactory;
@Inject ColorUtil colorUtil;
@Inject ClientFactory clientFactory;
private AuthObject authObject = null;
private String fallbackToken;
private boolean onlyAdd = false;
private final Gson gson = new Gson();
private ViewThemeUtils viewThemeUtils;
private final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
@VisibleForTesting
public AccountSetupBinding getAccountSetupBinding() {
return accountSetupBinding;
}
/**
* {@inheritDoc}
* <p>
* IMPORTANT ENTRY POINT 1: activity is shown to the user
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewThemeUtils = viewThemeUtilsFactory.withPrimaryAsBackground();
viewThemeUtils.platform.colorStatusBar(this, getResources().getColor(R.color.primary));
Uri data = getIntent().getData();
boolean directLogin = data != null && data.toString().startsWith(getString(R.string.login_data_own_scheme));
if (savedInstanceState == null && !directLogin) {
onboarding.launchFirstRunIfNeeded(this);
}
onlyAdd = getIntent().getBooleanExtra(KEY_ONLY_ADD, false) || checkIfViaSSO(getIntent());
// delete cookies for webView
deleteCookies();
// Workaround, for fixing a problem with Android Library Support v7 19
//getWindow().requestFeature(Window.FEATURE_NO_TITLE);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
}
mIsFirstAuthAttempt = true;
/// init activity state
mAccountMgr = AccountManager.get(this);
/// get input values
mAction = getIntent().getByteExtra(EXTRA_ACTION, ACTION_CREATE);
Bundle extras = getIntent().getExtras();
if (extras != null) {
mAccount = BundleExtensionsKt.getParcelableArgument(extras, EXTRA_ACCOUNT, Account.class);
}
if (savedInstanceState != null) {
mWaitingForOpId = savedInstanceState.getLong(KEY_WAITING_FOR_OP_ID);
mIsFirstAuthAttempt = savedInstanceState.getBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG);
}
boolean webViewLoginMethod = false;
String webloginUrl = null;
if (MainApp.isClientBrandedPlus()) {
String baseUrl = MDMConfig.INSTANCE.getBaseUrl(this);
if (!TextUtils.isEmpty(baseUrl)) {
webloginUrl = baseUrl + WEB_LOGIN;
}
}
if (!TextUtils.isEmpty(webloginUrl)) {
webViewLoginMethod = true;
} else if (getIntent().getBooleanExtra(EXTRA_USE_PROVIDER_AS_WEBLOGIN, false)) {
webViewLoginMethod = true;
webloginUrl = getString(R.string.provider_registration_server);
} else if (!TextUtils.isEmpty(getResources().getString(R.string.webview_login_url))) {
webViewLoginMethod = true;
webloginUrl = getResources().getString(R.string.webview_login_url);
showWebViewLoginUrl = getResources().getBoolean(R.bool.show_server_url_input);
}
/// load user interface
if (webViewLoginMethod) {
accountSetupWebviewBinding = AccountSetupWebviewBinding.inflate(getLayoutInflater());
setContentView(accountSetupWebviewBinding.getRoot());
anonymouslyPostLoginRequest(webloginUrl);
} else {
accountSetupBinding = AccountSetupBinding.inflate(getLayoutInflater());
setContentView(accountSetupBinding.getRoot());
/// initialize general UI elements
initOverallUi();
/// initialize block to be moved to single Fragment to check server and get info about it
/// initialize block to be moved to single Fragment to retrieve and validate credentials
if (TextUtils.isEmpty(getString(R.string.enforce_servers))) {
initAuthorizationPreFragment(savedInstanceState);
} else {
showEnforcedServers();
}
initServerPreFragment(savedInstanceState);
}
ProcessLifecycleOwner.get().getLifecycle().addObserver(lifecycleEventObserver);
}
private void showEnforcedServers() {
showAuthStatus();
accountSetupBinding.hostUrlFrame.setVisibility(View.GONE);
accountSetupBinding.hostUrlInputHelperText.setVisibility(View.GONE);
accountSetupBinding.scanQr.setVisibility(View.GONE);
accountSetupBinding.serversSpinner.setVisibility(View.VISIBLE);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.enforced_servers_spinner);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ArrayList<String> servers = new ArrayList<>();
servers.add("");
adapter.add(getString(R.string.please_select_a_server));
ArrayList<EnforcedServer> t = new Gson().fromJson(getString(R.string.enforce_servers),
new TypeToken<ArrayList<EnforcedServer>>() {
}
.getType());
for (EnforcedServer e : t) {
adapter.add(e.getName());
servers.add(e.getUrl());
}
accountSetupBinding.serversSpinner.setAdapter(adapter);
accountSetupBinding.serversSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String url = servers.get(position);
if (URLUtil.isValidUrl(url)) {
accountSetupBinding.hostUrlInput.setText(url);
checkOcServer();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// do nothing
}
});
}
private void deleteCookies() {
try {
CookieManager.getInstance().removeAllCookies(null);
} catch (Exception e) {
Log_OC.e(TAG, e.getMessage());
}
}
// region LoginFlow
private final ScheduledExecutorService loginFlowExecutorService = Executors.newSingleThreadScheduledExecutor();
private boolean isLoginProcessCompleted = false;
private boolean isRedirectedToTheDefaultBrowser = false;
private String baseUrl;
private void poolLogin() {
loginFlowExecutorService.scheduleWithFixedDelay(() -> {
if (!isLoginProcessCompleted) {
performLoginFlowV2();
}
}, 0, 30, TimeUnit.SECONDS);
}
/**
* This function facilitates the login process by anonymously posting a login request to a specified URL.
* After posting the request, it retrieves the login URL for completing the login flow.
* The login flow version used is v2.
*
* @param url The URL where the login request is to be anonymously posted.
* This URL should handle the login request and return the login URL.
* It's typically the entry point for the login process.
* Example: "<a href="https://example.com/index.php/login/v2">...</a>"
*/
private void anonymouslyPostLoginRequest(String url) {
if (TextUtils.isEmpty(url)) {
DisplayUtils.showSnackMessage(this, R.string.authenticator_activity_empty_base_url);
return;
}
baseUrl = url;
singleThreadExecutor.execute(() -> {
String response = getResponseOfAnonymouslyPostLoginRequest();
if (TextUtils.isEmpty(response)) {
DisplayUtils.showSnackMessage(AuthenticatorActivity.this, R.string.authenticator_activity_empty_response_message);
return;
}
String loginUrl = extractLoginUrl(response);
runOnUiThread(() -> {
initLoginInfoView();
launchDefaultWebBrowser(loginUrl);
});
});
}
private String extractLoginUrl(String response) {
try {
authObject = gson.fromJson(response, AuthObject.class);
if (authObject != null && !TextUtils.isEmpty(authObject.getLogin())) {
return authObject.getLogin();
} else {
Log_OC.e(TAG, "AuthObject parsing failed or login empty, trying JSONObject fallback");
}
} catch (Exception e) {
Log_OC.e(TAG, "Error parsing AuthObject: " + e.getMessage(), e);
}
try {
String fallbackUrl = getLoginFromJsonObject(response);
if (!TextUtils.isEmpty(fallbackUrl)) {
return fallbackUrl;
} else {
Log_OC.e(TAG, "Fallback JSONObject parsing failed or login empty");
}
} catch (Exception e) {
Log_OC.e(TAG, "Error parsing fallback JSONObject: " + e.getMessage(), e);
}
Log_OC.e(TAG, "Both AuthObject and fallback parsing failed, returning default login URL");
DisplayUtils.showSnackMessage(this, R.string.authenticator_activity_login_error);
return getResources().getString(R.string.webview_login_url);
}
private String getLoginFromJsonObject(String response) {
JsonObject jsonObject = JsonParser.parseString(response).getAsJsonObject();
fallbackToken = jsonObject.getAsJsonObject("poll").get("token").getAsString();
return jsonObject.get("login").getAsString();
}
private String getResponseOfAnonymouslyPostLoginRequest() {
PostMethod post = new PostMethod(baseUrl, false, new FormBody.Builder().build());
PlainClient client = clientFactory.createPlainClient();
post.execute(client);
return post.getResponseBodyAsString();
}
private void launchDefaultWebBrowser(String url) {
if (url == null || url.isBlank()) {
DisplayUtils.showSnackMessage(this, R.string.invalid_url);
return;
}
Uri uri = Uri.parse(url);
String loginScheme = getString(R.string.login_data_own_scheme);
try {
int toolbarColor = ContextCompat.getColor(this, R.color.primary);
AuthTabIntent authTabIntent = new AuthTabIntent.Builder().setColorScheme(toolbarColor).build();
authTabIntent.launch(authTabResultLauncher, uri, loginScheme);
return;
} catch (Exception e) {
Log_OC.e(TAG, "Auth Tab login URL launch failed: " + e);
}
try {
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
PackageManager packageManager = getPackageManager();
if (intent.resolveActivity(packageManager) != null) {
startActivity(intent);
return;
}
} catch (Exception e) {
Log_OC.e(TAG, "External browser launch failed: " + e);
}
DisplayUtils.showSnackMessage(this, R.string.authenticator_activity_no_web_browser_found);
}
private Pair<String, String> extractPollUrlAndToken() {
if (authObject != null) {
final var poll = authObject.getPoll();
String pollUrl = poll.getEndpoint();
String token = poll.getToken();
if (TextUtils.isEmpty(pollUrl)) {
Log_OC.e(TAG, "auth object poll url is empty.");
}
if (TextUtils.isEmpty(token)) {
Log_OC.e(TAG, "auth object token is empty.");
}
if (!TextUtils.isEmpty(pollUrl) && !TextUtils.isEmpty(token)) {
return new Pair<>(pollUrl, token);
}
}
return new Pair<>(baseUrl + "/poll", fallbackToken);
}
private void performLoginFlowV2() {
final var pollUrlAndToken = extractPollUrlAndToken();
RequestBody requestBody = new FormBody.Builder()
.add("token", pollUrlAndToken.second)
.build();
PlainClient client = clientFactory.createPlainClient();
PostMethod post = new PostMethod(pollUrlAndToken.first, false, requestBody);
int status = post.execute(client);
String response = post.getResponseBodyAsString();
Log_OC.d(TAG, "performLoginFlowV2 status: " + status);
Log_OC.d(TAG, "performLoginFlowV2 response: " + response);
if (!response.isEmpty()) {
runOnUiThread(() -> completeLoginFlow(response, status));
}
}
private void completeLoginFlow(String response, int status) {
try {
LoginUrlInfo loginUrlInfo = gson.fromJson(response, LoginUrlInfo.class);
if (loginUrlInfo == null) {
Log_OC.e(TAG, "cannot complete login flow loginUrl is null");
return;
}
isLoginProcessCompleted = loginUrlInfo.isValid(status);
if (accountSetupBinding != null) {
accountSetupBinding.hostUrlInput.setText("");
}
mServerInfo.mBaseUrl = AuthenticatorUrlUtils.INSTANCE.normalizeUrlSuffix(loginUrlInfo.getServer());
webViewUser = loginUrlInfo.getLoginName();
webViewPassword = loginUrlInfo.getAppPassword();
} catch (Exception e) {
Log_OC.d(TAG, "Error completeLoginFlow: " + e);
mServerStatusIcon = R.drawable.ic_alert;
mServerStatusText = getString(R.string.qr_could_not_be_read);
showServerStatus();
}
checkOcServer();
loginFlowExecutorService.shutdown();
ProcessLifecycleOwner.get().getLifecycle().removeObserver(lifecycleEventObserver);
}
private final LifecycleEventObserver lifecycleEventObserver = ((lifecycleOwner, event) -> {
if (event == Lifecycle.Event.ON_START && authObject != null && !TextUtils.isEmpty(authObject.getPoll().getToken())) {
Log_OC.d(TAG, "Start poolLogin");
poolLogin();
}
});
// endregion
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (accountSetupWebviewBinding != null && event.getAction() == KeyEvent.ACTION_DOWN &&
keyCode == KeyEvent.KEYCODE_BACK) {
if (accountSetupWebviewBinding.loginWebview.canGoBack()) {
accountSetupWebviewBinding.loginWebview.goBack();
} else {
finish();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
private void setClient() {
accountSetupWebviewBinding.loginWebview.setWebViewClient(new NextcloudWebViewClient(getSupportFragmentManager()) {
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (url.startsWith(getString(R.string.login_data_own_scheme) + PROTOCOL_SUFFIX + "login/")) {
parseAndLoginFromWebView(url);
return true;
}
return false;
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
accountSetupWebviewBinding.loginWebviewProgressBar.setVisibility(View.GONE);
accountSetupWebviewBinding.loginWebview.setVisibility(View.VISIBLE);
}
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
accountSetupWebviewBinding.loginWebviewProgressBar.setVisibility(View.GONE);
accountSetupWebviewBinding.loginWebview.setVisibility(View.VISIBLE);
InputStream resources = getResources().openRawResource(R.raw.custom_error);
String customError = DisplayUtils.getData(resources);
if (!customError.isEmpty()) {
accountSetupWebviewBinding.loginWebview.loadData(customError, "text/html; charset=UTF-8", null);
}
}
});
}
private void parseAndLoginFromWebView(String dataString) {
try {
String prefix = getString(R.string.login_data_own_scheme) + PROTOCOL_SUFFIX + "login/";
LoginUrlInfo loginUrlInfo = parseLoginDataUrl(prefix, dataString);
if (accountSetupBinding != null) {
accountSetupBinding.hostUrlInput.setText("");
}
mServerInfo.mBaseUrl = AuthenticatorUrlUtils.INSTANCE.normalizeUrlSuffix(loginUrlInfo.getServer());
webViewUser = loginUrlInfo.getLoginName();
webViewPassword = loginUrlInfo.getAppPassword();
} catch (Exception e) {
mServerStatusIcon = R.drawable.ic_alert;
mServerStatusText = getString(R.string.qr_could_not_be_read);
showServerStatus();
}
checkOcServer();
}
/**
* parses a URI string and returns a login data object with the information from the URI string.
*
* @param prefix URI beginning, e.g. cloud://login/
* @param dataString the complete URI
* @return login data
* @throws IllegalArgumentException when
*/
public static LoginUrlInfo parseLoginDataUrl(String prefix, String dataString) throws IllegalArgumentException {
if (dataString.length() < prefix.length()) {
throw new IllegalArgumentException("Invalid login URL detected");
}
// format is basically xxx://login/server:xxx&user:xxx&password while all variables are optional
String data = dataString.substring(prefix.length());
// parse data
String[] values = data.split("&");
if (values.length < 1 || values.length > 3) {
// error illegal number of URL elements detected
throw new IllegalArgumentException("Illegal number of login URL elements detected: " + values.length);
}
LoginUrlInfo loginUrlInfo = new LoginUrlInfo("", "", "");
for (String value : values) {
if (value.startsWith("user" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR)) {
loginUrlInfo.setLoginName(URLDecoder.decode(
value.substring(("user" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR).length())));
} else if (value.startsWith("password" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR)) {
loginUrlInfo.setAppPassword(URLDecoder.decode(
value.substring(("password" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR).length())));
} else if (value.startsWith("server" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR)) {
loginUrlInfo.setServer(URLDecoder.decode(
value.substring(("server" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR).length())));
}
}
return loginUrlInfo;
}
/**
* Configures elements in the user interface under direct control of the Activity.
*/
private void initOverallUi() {
accountSetupBinding.hostUrlContainer.setEndIconOnClickListener(v -> checkOcServer());
accountSetupBinding.hostUrlInputHelperText.setText(
String.format(getString(R.string.login_url_helper_text), getString(R.string.app_name)));
viewThemeUtils.platform.colorTextView(accountSetupBinding.hostUrlInputHelperText, ColorRole.ON_PRIMARY);
viewThemeUtils.platform.colorTextView(accountSetupBinding.serverStatusText, ColorRole.ON_PRIMARY);
viewThemeUtils.platform.colorTextView(accountSetupBinding.authStatusText, ColorRole.ON_PRIMARY);
viewThemeUtils.material.colorTextInputLayout(accountSetupBinding.hostUrlContainer, ColorRole.ON_PRIMARY);
viewThemeUtils.platform.colorEditTextOnPrimary(accountSetupBinding.hostUrlInput);
if (deviceInfo.hasCamera(this)) {
accountSetupBinding.scanQr.setOnClickListener(v -> onScan());
viewThemeUtils.platform.tintDrawable(this, accountSetupBinding.scanQr.getDrawable(), ColorRole.ON_PRIMARY);
} else {
accountSetupBinding.scanQr.setVisibility(View.GONE);
}
}
/**
* @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
*/
private void initServerPreFragment(Bundle savedInstanceState) {
// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
if (savedInstanceState == null) {
if (mAccount != null) {
String baseUrl = mAccountMgr.getUserData(mAccount, Constants.KEY_OC_BASE_URL);
if (TextUtils.isEmpty(baseUrl)) {
mServerInfo.mBaseUrl = "";
} else {
mServerInfo.mBaseUrl = baseUrl;
}
// TODO do next in a setter for mBaseUrl
mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith(HTTPS_PROTOCOL);
mServerInfo.mVersion = accountManager.getServerVersion(mAccount);
} else {
mServerInfo.mBaseUrl = getString(R.string.webview_login_url).trim();
mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith(HTTPS_PROTOCOL);
}
} else {
mServerStatusText = savedInstanceState.getString(KEY_SERVER_STATUS_TEXT);
mServerStatusIcon = savedInstanceState.getInt(KEY_SERVER_STATUS_ICON);
// TODO parcelable
mServerInfo.mIsSslConn = savedInstanceState.getBoolean(KEY_IS_SSL_CONN);
mServerInfo.mBaseUrl = savedInstanceState.getString(KEY_HOST_URL_TEXT);
String ocVersion = savedInstanceState.getString(KEY_OC_VERSION);
if (ocVersion != null) {
mServerInfo.mVersion = new OwnCloudVersion(ocVersion);
}
mServerInfo.mAuthMethod = AuthenticationMethod.valueOf(
savedInstanceState.getString(KEY_SERVER_AUTH_METHOD));
}
}
/**
* @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
*/
private void initAuthorizationPreFragment(Bundle savedInstanceState) {
/// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
if (savedInstanceState != null) {
mAuthStatusText = savedInstanceState.getString(KEY_AUTH_STATUS_TEXT);
mAuthStatusIcon = savedInstanceState.getInt(KEY_AUTH_STATUS_ICON);
}
/// step 2 - set properties of UI elements (text, visibility, enabled...)
showAuthStatus();
accountSetupBinding.hostUrlInput.setImeOptions(EditorInfo.IME_ACTION_NEXT);
accountSetupBinding.hostUrlInput.setOnEditorActionListener(this);
}
/**
* Saves relevant state before {@link #onPause()}
* <p>
* See {@link super#onSaveInstanceState(Bundle)}
*/
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
//Log_OC.e(TAG, "onSaveInstanceState init" );
super.onSaveInstanceState(outState);
/// global state
outState.putLong(KEY_WAITING_FOR_OP_ID, mWaitingForOpId);
outState.putBoolean(KEY_IS_SSL_CONN, mServerInfo.mIsSslConn);
outState.putString(KEY_HOST_URL_TEXT, mServerInfo.mBaseUrl);
if (mServerInfo.mVersion != null) {
outState.putString(KEY_OC_VERSION, mServerInfo.mVersion.getVersion());
}
outState.putString(KEY_SERVER_AUTH_METHOD, mServerInfo.mAuthMethod.name());
/// authentication
outState.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG, mIsFirstAuthAttempt);
/// AsyncTask (User and password)
if (mAsyncTask != null) {
mAsyncTask.cancel(true);
outState.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS, true);
} else {
outState.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS, false);
}
mAsyncTask = null;
}
@Override
public void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// AsyncTask
boolean inProgress = savedInstanceState.getBoolean(KEY_ASYNC_TASK_IN_PROGRESS);
if (inProgress) {
String username = savedInstanceState.getString(KEY_USERNAME);
String password = savedInstanceState.getString(KEY_PASSWORD);
OwnCloudCredentials credentials = OwnCloudCredentialsFactory.newBasicCredentials(username, password);
accessRootFolder(credentials);
}
}
/**
* The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION request is
* caught here.
* <p>
* To make this possible, this activity needs to be qualified with android:launchMode = "singleTask" in the
* AndroidManifest.xml file.
*/
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log_OC.d(TAG, "onNewIntent()");
if (intent.getBooleanExtra(FirstRunActivity.EXTRA_EXIT, false)) {
super.finish();
}
onlyAdd = intent.getBooleanExtra(KEY_ONLY_ADD, false) || checkIfViaSSO(intent);
// Passcode
passCodeManager.onActivityResumed(this);
Uri data = intent.getData();
if (data != null && data.toString().startsWith(getString(R.string.login_data_own_scheme))) {
if (!MDMConfig.INSTANCE.multiAccountSupport(this) &&
accountManager.getAccounts().length == 1) {
DisplayUtils.showSnackMessage(this, R.string.no_mutliple_accounts_allowed);
finish();
return;
} else {
parseAndLoginFromWebView(data.toString());
}
}
if (intent.getBooleanExtra(EXTRA_USE_PROVIDER_AS_WEBLOGIN, false)) {
accountSetupWebviewBinding = AccountSetupWebviewBinding.inflate(getLayoutInflater());
setContentView(accountSetupWebviewBinding.getRoot());
initSimpleSignupLogin();
}
}
@SuppressFBWarnings("ANDROID_WEB_VIEW_JAVASCRIPT")
@SuppressLint("SetJavaScriptEnabled")
private void initSimpleSignupLogin() {
viewThemeUtils.platform.colorCircularProgressBar(accountSetupWebviewBinding.loginWebviewProgressBar, ColorRole.ON_PRIMARY_CONTAINER);
accountSetupWebviewBinding.loginWebview.setVisibility(View.GONE);
new WebViewUtil().setProxyKKPlus(accountSetupWebviewBinding.loginWebview);
accountSetupWebviewBinding.loginWebview.getSettings().setAllowFileAccess(false);
accountSetupWebviewBinding.loginWebview.getSettings().setJavaScriptEnabled(true);
accountSetupWebviewBinding.loginWebview.getSettings().setDomStorageEnabled(true);
accountSetupWebviewBinding.loginWebview.getSettings().setUserAgentString(MainApp.getUserAgent());
accountSetupWebviewBinding.loginWebview.getSettings().setSaveFormData(false);
accountSetupWebviewBinding.loginWebview.getSettings().setSavePassword(false);
Map<String, String> headers = new HashMap<>();
headers.put(RemoteOperation.OCS_API_HEADER, RemoteOperation.OCS_API_HEADER_VALUE);
new WebViewUtil().setProxyKKPlus(accountSetupWebviewBinding.loginWebview);
accountSetupWebviewBinding.loginWebview.loadUrl(getString(R.string.provider_registration_server), headers);
accountSetupWebviewBinding.loginFlowV2.loginFlowInfoV2.setVisibility(View.GONE);
setClient();
}
private boolean checkIfViaSSO(Intent intent) {
Bundle extras = intent.getExtras();
if (extras == null) {
return false;
} else {
String authTokenType = extras.getString("authTokenType");
return "SSO".equals(authTokenType);
}
}
/**
* The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION, and deferred
* in {@link #onNewIntent(Intent)}, is processed here.
*/
@Override
protected void onResume() {
super.onResume();
// bind to Operations Service
mOperationsServiceConnection = new OperationsServiceConnection();
if (!bindService(new Intent(this, OperationsService.class),
mOperationsServiceConnection,
Context.BIND_AUTO_CREATE)) {
DisplayUtils.showSnackMessage(accountSetupBinding.scroll, R.string.error_cant_bind_to_operations_service);
finish();
}
if (mOperationsServiceBinder != null) {
doOnResumeAndBound();
}
}
@Override
protected void onPause() {
if (mOperationsServiceBinder != null) {
mOperationsServiceBinder.removeOperationListener(this);
}
super.onPause();
}
@Override
protected void onDestroy() {
if (mOperationsServiceConnection != null) {
unbindService(mOperationsServiceConnection);
mOperationsServiceBinder = null;
}
Log_OC.d(TAG, "AuthenticatorActivity onDestroy called");
singleThreadExecutor.shutdown();
super.onDestroy();
}
@SuppressFBWarnings("NP")
private void checkOcServer() {
String uri;
if (accountSetupBinding != null &&
accountSetupBinding.hostUrlInput.getText() != null &&
!accountSetupBinding.hostUrlInput.getText().toString().isEmpty()) {
uri = accountSetupBinding.hostUrlInput.getText().toString().trim();
} else {
uri = mServerInfo.mBaseUrl;
}
mServerInfo = new GetServerInfoOperation.ServerInfo();
if (!uri.isEmpty()) {
if (accountSetupBinding != null) {
uri = AuthenticatorUrlUtils.INSTANCE.stripIndexPhpOrAppsFiles(uri);
accountSetupBinding.hostUrlInput.setText(uri);
}
try {
uri = AuthenticatorUrlUtils.INSTANCE.normalizeScheme(uri);
} catch (IllegalArgumentException ex) {
// Let the Nextcloud library check the error of the malformed URI
Log_OC.e(TAG, "Invalid URL", ex);
}
// Handle internationalized domain names
try {
uri = DisplayUtils.convertIdn(uri, true);
} catch (IllegalArgumentException ex) {
// Let the Nextcloud library check the error of the malformed URI
Log_OC.e(TAG, "Error converting internationalized domain name " + uri, ex);
}
if (accountSetupBinding != null) {
mServerStatusText = getResources().getString(R.string.auth_testing_connection);
mServerStatusIcon = R.drawable.progress_small;
showServerStatus();
}
// TODO maybe do this via async task
Intent getServerInfoIntent = new Intent();
getServerInfoIntent.setAction(OperationsService.ACTION_GET_SERVER_INFO);
getServerInfoIntent.putExtra(OperationsService.EXTRA_SERVER_URL,