AuthenticatorActivity.java 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555
  1. /*
  2. * ownCloud Android client application
  3. *
  4. * @author Bartek Przybylski
  5. * @author David A. Velasco
  6. * @author masensio
  7. * @author Mario Danic
  8. * Copyright (C) 2012 Bartek Przybylski
  9. * Copyright (C) 2015 ownCloud Inc.
  10. * Copyright (C) 2017 Mario Danic
  11. *
  12. * This program is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License version 2,
  14. * as published by the Free Software Foundation.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU General Public License
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. *
  24. * All changes by Mario Danic are distributed under the following terms:
  25. *
  26. * This program is free software: you can redistribute it and/or modify
  27. * it under the terms of the GNU Affero General Public License as published by
  28. * the Free Software Foundation, either version 3 of the License, or
  29. * at your option) any later version.
  30. *
  31. * This program is distributed in the hope that it will be useful,
  32. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  33. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  34. * GNU Affero General Public License for more details.
  35. *
  36. * You should have received a copy of the GNU Affero General Public License
  37. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  38. *
  39. */
  40. package com.owncloud.android.authentication;
  41. import android.Manifest;
  42. import android.accounts.Account;
  43. import android.accounts.AccountManager;
  44. import android.annotation.SuppressLint;
  45. import android.content.ComponentName;
  46. import android.content.Context;
  47. import android.content.Intent;
  48. import android.content.ServiceConnection;
  49. import android.content.SharedPreferences;
  50. import android.content.pm.ActivityInfo;
  51. import android.content.pm.PackageManager;
  52. import android.graphics.Bitmap;
  53. import android.graphics.Color;
  54. import android.net.Uri;
  55. import android.net.http.SslCertificate;
  56. import android.net.http.SslError;
  57. import android.os.Build;
  58. import android.os.Bundle;
  59. import android.os.Handler;
  60. import android.os.IBinder;
  61. import android.preference.PreferenceManager;
  62. import android.text.TextUtils;
  63. import android.util.AndroidRuntimeException;
  64. import android.view.KeyEvent;
  65. import android.view.View;
  66. import android.view.inputmethod.EditorInfo;
  67. import android.webkit.CookieManager;
  68. import android.webkit.CookieSyncManager;
  69. import android.webkit.SslErrorHandler;
  70. import android.webkit.WebResourceRequest;
  71. import android.webkit.WebResourceResponse;
  72. import android.webkit.WebView;
  73. import android.webkit.WebViewClient;
  74. import android.widget.TextView;
  75. import android.widget.TextView.OnEditorActionListener;
  76. import android.widget.Toast;
  77. import com.blikoon.qrcodescanner.QrCodeActivity;
  78. import com.google.android.material.snackbar.Snackbar;
  79. import com.nextcloud.client.account.User;
  80. import com.nextcloud.client.account.UserAccountManager;
  81. import com.nextcloud.client.device.DeviceInfo;
  82. import com.nextcloud.client.di.Injectable;
  83. import com.nextcloud.client.onboarding.FirstRunActivity;
  84. import com.nextcloud.client.onboarding.OnboardingService;
  85. import com.nextcloud.client.preferences.AppPreferences;
  86. import com.owncloud.android.MainApp;
  87. import com.owncloud.android.R;
  88. import com.owncloud.android.databinding.AccountSetupBinding;
  89. import com.owncloud.android.databinding.AccountSetupWebviewBinding;
  90. import com.owncloud.android.lib.common.OwnCloudAccount;
  91. import com.owncloud.android.lib.common.OwnCloudClient;
  92. import com.owncloud.android.lib.common.OwnCloudClientFactory;
  93. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  94. import com.owncloud.android.lib.common.OwnCloudCredentials;
  95. import com.owncloud.android.lib.common.OwnCloudCredentialsFactory;
  96. import com.owncloud.android.lib.common.UserInfo;
  97. import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;
  98. import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;
  99. import com.owncloud.android.lib.common.network.CertificateCombinedException;
  100. import com.owncloud.android.lib.common.network.NetworkUtils;
  101. import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
  102. import com.owncloud.android.lib.common.operations.RemoteOperation;
  103. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  104. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  105. import com.owncloud.android.lib.common.utils.Log_OC;
  106. import com.owncloud.android.lib.resources.status.GetCapabilitiesRemoteOperation;
  107. import com.owncloud.android.lib.resources.status.OCCapability;
  108. import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  109. import com.owncloud.android.lib.resources.users.GetUserInfoRemoteOperation;
  110. import com.owncloud.android.operations.DetectAuthenticationMethodOperation.AuthenticationMethod;
  111. import com.owncloud.android.operations.GetServerInfoOperation;
  112. import com.owncloud.android.providers.DocumentsStorageProvider;
  113. import com.owncloud.android.services.OperationsService;
  114. import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
  115. import com.owncloud.android.ui.activity.FileDisplayActivity;
  116. import com.owncloud.android.ui.dialog.IndeterminateProgressDialog;
  117. import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
  118. import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;
  119. import com.owncloud.android.utils.DisplayUtils;
  120. import com.owncloud.android.utils.ErrorMessageAdapter;
  121. import com.owncloud.android.utils.PermissionUtil;
  122. import com.owncloud.android.utils.theme.ThemeDrawableUtils;
  123. import com.owncloud.android.utils.theme.ThemeToolbarUtils;
  124. import java.io.ByteArrayInputStream;
  125. import java.io.InputStream;
  126. import java.net.URLDecoder;
  127. import java.security.cert.Certificate;
  128. import java.security.cert.CertificateException;
  129. import java.security.cert.CertificateFactory;
  130. import java.security.cert.X509Certificate;
  131. import java.util.HashMap;
  132. import java.util.Locale;
  133. import java.util.Map;
  134. import javax.inject.Inject;
  135. import androidx.annotation.ColorInt;
  136. import androidx.annotation.NonNull;
  137. import androidx.annotation.Nullable;
  138. import androidx.annotation.VisibleForTesting;
  139. import androidx.fragment.app.DialogFragment;
  140. import androidx.fragment.app.Fragment;
  141. import androidx.fragment.app.FragmentManager;
  142. import androidx.fragment.app.FragmentTransaction;
  143. import de.cotech.hw.fido.WebViewFidoBridge;
  144. import de.cotech.hw.fido.ui.FidoDialogOptions;
  145. import de.cotech.hw.fido2.WebViewWebauthnBridge;
  146. import de.cotech.hw.fido2.ui.WebauthnDialogOptions;
  147. import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
  148. /**
  149. * This Activity is used to add an ownCloud account to the App
  150. */
  151. public class AuthenticatorActivity extends AccountAuthenticatorActivity
  152. implements OnRemoteOperationListener, OnEditorActionListener, OnSslUntrustedCertListener,
  153. AuthenticatorAsyncTask.OnAuthenticatorTaskListener, Injectable {
  154. private static final String TAG = AuthenticatorActivity.class.getSimpleName();
  155. public static final String EXTRA_ACTION = "ACTION";
  156. public static final String EXTRA_ACCOUNT = "ACCOUNT";
  157. public static final String EXTRA_USE_PROVIDER_AS_WEBLOGIN = "USE_PROVIDER_AS_WEBLOGIN";
  158. private static final String KEY_HOST_URL_TEXT = "HOST_URL_TEXT";
  159. private static final String KEY_OC_VERSION = "OC_VERSION";
  160. private static final String KEY_SERVER_STATUS_TEXT = "SERVER_STATUS_TEXT";
  161. private static final String KEY_SERVER_STATUS_ICON = "SERVER_STATUS_ICON";
  162. private static final String KEY_IS_SSL_CONN = "IS_SSL_CONN";
  163. private static final String KEY_AUTH_STATUS_TEXT = "AUTH_STATUS_TEXT";
  164. private static final String KEY_AUTH_STATUS_ICON = "AUTH_STATUS_ICON";
  165. private static final String KEY_SERVER_AUTH_METHOD = "SERVER_AUTH_METHOD";
  166. private static final String KEY_WAITING_FOR_OP_ID = "WAITING_FOR_OP_ID";
  167. private static final String KEY_ONLY_ADD = "onlyAdd";
  168. public static final byte ACTION_CREATE = 0;
  169. public static final byte ACTION_UPDATE_EXPIRED_TOKEN = 2; // detected by the app
  170. private static final String UNTRUSTED_CERT_DIALOG_TAG = "UNTRUSTED_CERT_DIALOG";
  171. private static final String WAIT_DIALOG_TAG = "WAIT_DIALOG";
  172. private static final String KEY_AUTH_IS_FIRST_ATTEMPT_TAG = "KEY_AUTH_IS_FIRST_ATTEMPT";
  173. private static final String KEY_USERNAME = "USERNAME";
  174. private static final String KEY_PASSWORD = "PASSWORD";
  175. private static final String KEY_ASYNC_TASK_IN_PROGRESS = "AUTH_IN_PROGRESS";
  176. public static final String WEB_LOGIN = "/index.php/login/flow";
  177. public static final String PROTOCOL_SUFFIX = "://";
  178. public static final String LOGIN_URL_DATA_KEY_VALUE_SEPARATOR = ":";
  179. public static final String HTTPS_PROTOCOL = "https://";
  180. public static final String HTTP_PROTOCOL = "http://";
  181. public static final int NO_ICON = 0;
  182. public static final String EMPTY_STRING = "";
  183. private static final int REQUEST_CODE_QR_SCAN = 101;
  184. public static final int REQUEST_CODE_FIRST_RUN = 102;
  185. /// parameters from EXTRAs in starter Intent
  186. private byte mAction;
  187. private Account mAccount;
  188. /// activity-level references / state
  189. private final Handler mHandler = new Handler();
  190. private ServiceConnection mOperationsServiceConnection;
  191. private OperationsServiceBinder mOperationsServiceBinder;
  192. private AccountManager mAccountMgr;
  193. /// Server PRE-Fragment elements
  194. private AccountSetupBinding accountSetupBinding;
  195. private AccountSetupWebviewBinding accountSetupWebviewBinding;
  196. private String mServerStatusText = EMPTY_STRING;
  197. private int mServerStatusIcon;
  198. private GetServerInfoOperation.ServerInfo mServerInfo = new GetServerInfoOperation.ServerInfo();
  199. /// Authentication PRE-Fragment elements
  200. private WebViewFidoBridge webViewFidoU2fBridge;
  201. private WebViewWebauthnBridge webViewWebauthnBridge;
  202. private String mAuthStatusText = EMPTY_STRING;
  203. private int mAuthStatusIcon;
  204. private AuthenticatorAsyncTask mAsyncTask;
  205. private boolean mIsFirstAuthAttempt;
  206. /// Identifier of operation in progress which result shouldn't be lost
  207. private long mWaitingForOpId = Long.MAX_VALUE;
  208. private boolean showWebViewLoginUrl;
  209. private String webViewUser;
  210. private String webViewPassword;
  211. @Inject UserAccountManager accountManager;
  212. @Inject AppPreferences preferences;
  213. @Inject OnboardingService onboarding;
  214. @Inject DeviceInfo deviceInfo;
  215. private boolean onlyAdd = false;
  216. @SuppressLint("ResourceAsColor") @ColorInt
  217. private int primaryColor = R.color.primary;
  218. private boolean strictMode = false;
  219. @VisibleForTesting
  220. public AccountSetupBinding getAccountSetupBinding() {
  221. return accountSetupBinding;
  222. }
  223. /**
  224. * {@inheritDoc}
  225. * <p>
  226. * IMPORTANT ENTRY POINT 1: activity is shown to the user
  227. */
  228. @Override
  229. protected void onCreate(Bundle savedInstanceState) {
  230. super.onCreate(savedInstanceState);
  231. Uri data = getIntent().getData();
  232. boolean directLogin = data != null && data.toString().startsWith(getString(R.string.login_data_own_scheme));
  233. if (savedInstanceState == null && !directLogin) {
  234. onboarding.launchFirstRunIfNeeded(this);
  235. }
  236. onlyAdd = getIntent().getBooleanExtra(KEY_ONLY_ADD, false) || checkIfViaSSO(getIntent());
  237. // delete cookies for webView
  238. deleteCookies();
  239. // Workaround, for fixing a problem with Android Library Support v7 19
  240. //getWindow().requestFeature(Window.FEATURE_NO_TITLE);
  241. if (getSupportActionBar() != null) {
  242. getSupportActionBar().hide();
  243. getSupportActionBar().setDisplayHomeAsUpEnabled(false);
  244. getSupportActionBar().setDisplayShowHomeEnabled(false);
  245. getSupportActionBar().setDisplayShowTitleEnabled(false);
  246. }
  247. mIsFirstAuthAttempt = true;
  248. /// init activity state
  249. mAccountMgr = AccountManager.get(this);
  250. /// get input values
  251. mAction = getIntent().getByteExtra(EXTRA_ACTION, ACTION_CREATE);
  252. Bundle extras = getIntent().getExtras();
  253. if (extras != null) {
  254. mAccount = extras.getParcelable(EXTRA_ACCOUNT);
  255. }
  256. if (savedInstanceState != null) {
  257. mWaitingForOpId = savedInstanceState.getLong(KEY_WAITING_FOR_OP_ID);
  258. mIsFirstAuthAttempt = savedInstanceState.getBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG);
  259. }
  260. String webloginUrl = null;
  261. boolean webViewLoginMethod;
  262. if (getIntent().getBooleanExtra(EXTRA_USE_PROVIDER_AS_WEBLOGIN, false)) {
  263. webViewLoginMethod = true;
  264. webloginUrl = getString(R.string.provider_registration_server);
  265. } else {
  266. webViewLoginMethod = !TextUtils.isEmpty(getResources().getString(R.string.webview_login_url));
  267. showWebViewLoginUrl = getResources().getBoolean(R.bool.show_server_url_input);
  268. }
  269. /// load user interface
  270. if (webViewLoginMethod) {
  271. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  272. accountSetupWebviewBinding = AccountSetupWebviewBinding.inflate(getLayoutInflater());
  273. setContentView(accountSetupWebviewBinding.getRoot());
  274. initWebViewLogin(webloginUrl, false);
  275. } else {
  276. accountSetupBinding = AccountSetupBinding.inflate(getLayoutInflater());
  277. setContentView(accountSetupBinding.getRoot());
  278. /// initialize general UI elements
  279. initOverallUi();
  280. /// initialize block to be moved to single Fragment to check server and get info about it
  281. /// initialize block to be moved to single Fragment to retrieve and validate credentials
  282. initAuthorizationPreFragment(savedInstanceState);
  283. }
  284. initServerPreFragment(savedInstanceState);
  285. }
  286. private void deleteCookies() {
  287. try {
  288. CookieSyncManager.createInstance(this);
  289. CookieManager.getInstance().removeAllCookies(null);
  290. } catch (AndroidRuntimeException e) {
  291. Log_OC.e(TAG, e.getMessage());
  292. }
  293. }
  294. private static String getWebLoginUserAgent() {
  295. return Build.MANUFACTURER.substring(0, 1).toUpperCase(Locale.getDefault()) +
  296. Build.MANUFACTURER.substring(1).toLowerCase(Locale.getDefault()) + " " + Build.MODEL + " (Android)";
  297. }
  298. @SuppressFBWarnings("ANDROID_WEB_VIEW_JAVASCRIPT")
  299. @SuppressLint("SetJavaScriptEnabled")
  300. private void initWebViewLogin(String baseURL, boolean useGenericUserAgent) {
  301. accountSetupWebviewBinding.loginWebview.setVisibility(View.GONE);
  302. accountSetupWebviewBinding.loginWebview.getSettings().setAllowFileAccess(false);
  303. accountSetupWebviewBinding.loginWebview.getSettings().setJavaScriptEnabled(true);
  304. accountSetupWebviewBinding.loginWebview.getSettings().setDomStorageEnabled(true);
  305. if (useGenericUserAgent) {
  306. accountSetupWebviewBinding.loginWebview.getSettings().setUserAgentString(MainApp.getUserAgent());
  307. } else {
  308. accountSetupWebviewBinding.loginWebview.getSettings().setUserAgentString(getWebLoginUserAgent());
  309. }
  310. accountSetupWebviewBinding.loginWebview.getSettings().setSaveFormData(false);
  311. accountSetupWebviewBinding.loginWebview.getSettings().setSavePassword(false);
  312. FidoDialogOptions.Builder dialogOptionsBuilder = FidoDialogOptions.builder();
  313. dialogOptionsBuilder.setShowSdkLogo(true);
  314. dialogOptionsBuilder.setTheme(R.style.FidoDialog);
  315. webViewFidoU2fBridge = WebViewFidoBridge.createInstanceForWebView(
  316. this, accountSetupWebviewBinding.loginWebview, dialogOptionsBuilder);
  317. WebauthnDialogOptions.Builder webauthnOptionsBuilder = WebauthnDialogOptions.builder();
  318. webauthnOptionsBuilder.setShowSdkLogo(true);
  319. webauthnOptionsBuilder.setAllowSkipPin(true);
  320. webauthnOptionsBuilder.setTheme(R.style.FidoDialog);
  321. webViewWebauthnBridge = WebViewWebauthnBridge.createInstanceForWebView(
  322. this, accountSetupWebviewBinding.loginWebview, webauthnOptionsBuilder);
  323. Map<String, String> headers = new HashMap<>();
  324. headers.put(RemoteOperation.OCS_API_HEADER, RemoteOperation.OCS_API_HEADER_VALUE);
  325. String url;
  326. if (baseURL != null && !baseURL.isEmpty()) {
  327. url = baseURL;
  328. } else {
  329. url = getResources().getString(R.string.webview_login_url);
  330. }
  331. if (url.startsWith(HTTPS_PROTOCOL)) {
  332. strictMode = true;
  333. }
  334. accountSetupWebviewBinding.loginWebview.loadUrl(url, headers);
  335. setClient();
  336. }
  337. @Override
  338. public boolean onKeyDown(int keyCode, KeyEvent event) {
  339. if (accountSetupWebviewBinding != null && event.getAction() == KeyEvent.ACTION_DOWN &&
  340. keyCode == KeyEvent.KEYCODE_BACK) {
  341. if (accountSetupWebviewBinding.loginWebview.canGoBack()) {
  342. accountSetupWebviewBinding.loginWebview.goBack();
  343. } else {
  344. finish();
  345. }
  346. return true;
  347. }
  348. return super.onKeyDown(keyCode, event);
  349. }
  350. private void setClient() {
  351. accountSetupWebviewBinding.loginWebview.setWebViewClient(new WebViewClient() {
  352. @Override
  353. public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
  354. webViewFidoU2fBridge.delegateShouldInterceptRequest(view, request);
  355. webViewWebauthnBridge.delegateShouldInterceptRequest(view, request);
  356. return super.shouldInterceptRequest(view, request);
  357. }
  358. @Override
  359. public void onPageStarted(WebView view, String url, Bitmap favicon) {
  360. super.onPageStarted(view, url, favicon);
  361. webViewFidoU2fBridge.delegateOnPageStarted(view, url, favicon);
  362. webViewWebauthnBridge.delegateOnPageStarted(view, url, favicon);
  363. }
  364. @Override
  365. public boolean shouldOverrideUrlLoading(WebView view, String url) {
  366. if (url.startsWith(getString(R.string.login_data_own_scheme) + PROTOCOL_SUFFIX + "login/")) {
  367. parseAndLoginFromWebView(url);
  368. return true;
  369. }
  370. if (strictMode && url.startsWith(HTTP_PROTOCOL)) {
  371. Snackbar.make(view, R.string.strict_mode, Snackbar.LENGTH_LONG).show();
  372. return true;
  373. }
  374. return false;
  375. }
  376. @Override
  377. public void onPageFinished(WebView view, String url) {
  378. super.onPageFinished(view, url);
  379. accountSetupWebviewBinding.loginWebviewProgressBar.setVisibility(View.GONE);
  380. accountSetupWebviewBinding.loginWebview.setVisibility(View.VISIBLE);
  381. ThemeToolbarUtils.colorStatusBar(AuthenticatorActivity.this, primaryColor);
  382. getWindow().setNavigationBarColor(primaryColor);
  383. }
  384. @Override
  385. public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
  386. X509Certificate cert = getX509CertificateFromError(error);
  387. try {
  388. if (cert != null && NetworkUtils.isCertInKnownServersStore(cert, getApplicationContext())) {
  389. handler.proceed();
  390. } else {
  391. showUntrustedCertDialog(cert, error, handler);
  392. }
  393. } catch (Exception e) {
  394. Log_OC.e(TAG, "Cert could not be verified");
  395. }
  396. }
  397. public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
  398. accountSetupWebviewBinding.loginWebviewProgressBar.setVisibility(View.GONE);
  399. accountSetupWebviewBinding.loginWebview.setVisibility(View.VISIBLE);
  400. InputStream resources = getResources().openRawResource(R.raw.custom_error);
  401. String customError = DisplayUtils.getData(resources);
  402. if (!customError.isEmpty()) {
  403. accountSetupWebviewBinding.loginWebview.loadData(customError, "text/html; charset=UTF-8", null);
  404. }
  405. }
  406. });
  407. }
  408. private void parseAndLoginFromWebView(String dataString) {
  409. try {
  410. String prefix = getString(R.string.login_data_own_scheme) + PROTOCOL_SUFFIX + "login/";
  411. LoginUrlInfo loginUrlInfo = parseLoginDataUrl(prefix, dataString);
  412. if (accountSetupBinding != null) {
  413. accountSetupBinding.hostUrlInput.setText("");
  414. }
  415. mServerInfo.mBaseUrl = AuthenticatorUrlUtils.normalizeUrlSuffix(loginUrlInfo.serverAddress);
  416. webViewUser = loginUrlInfo.username;
  417. webViewPassword = loginUrlInfo.password;
  418. } catch (Exception e) {
  419. mServerStatusIcon = R.drawable.ic_alert;
  420. mServerStatusText = getString(R.string.qr_could_not_be_read);
  421. showServerStatus();
  422. }
  423. checkOcServer();
  424. }
  425. /**
  426. * parses a URI string and returns a login data object with the information from the URI string.
  427. *
  428. * @param prefix URI beginning, e.g. cloud://login/
  429. * @param dataString the complete URI
  430. * @return login data
  431. * @throws IllegalArgumentException when
  432. */
  433. public static LoginUrlInfo parseLoginDataUrl(String prefix, String dataString) throws IllegalArgumentException {
  434. if (dataString.length() < prefix.length()) {
  435. throw new IllegalArgumentException("Invalid login URL detected");
  436. }
  437. // format is basically xxx://login/server:xxx&user:xxx&password while all variables are optional
  438. String data = dataString.substring(prefix.length());
  439. // parse data
  440. String[] values = data.split("&");
  441. if (values.length < 1 || values.length > 3) {
  442. // error illegal number of URL elements detected
  443. throw new IllegalArgumentException("Illegal number of login URL elements detected: " + values.length);
  444. }
  445. LoginUrlInfo loginUrlInfo = new LoginUrlInfo();
  446. for (String value : values) {
  447. if (value.startsWith("user" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR)) {
  448. loginUrlInfo.username = URLDecoder.decode(
  449. value.substring(("user" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR).length()));
  450. } else if (value.startsWith("password" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR)) {
  451. loginUrlInfo.password = URLDecoder.decode(
  452. value.substring(("password" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR).length()));
  453. } else if (value.startsWith("server" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR)) {
  454. loginUrlInfo.serverAddress = URLDecoder.decode(
  455. value.substring(("server" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR).length()));
  456. }
  457. }
  458. return loginUrlInfo;
  459. }
  460. /**
  461. * Configures elements in the user interface under direct control of the Activity.
  462. */
  463. private void initOverallUi() {
  464. accountSetupBinding.hostUrlContainer.setEndIconOnClickListener(v -> checkOcServer());
  465. accountSetupBinding.hostUrlInputHelperText.setText(
  466. String.format(getString(R.string.login_url_helper_text), getString(R.string.app_name)));
  467. if (deviceInfo.hasCamera(this)) {
  468. accountSetupBinding.scanQr.setOnClickListener(v -> onScan());
  469. ThemeDrawableUtils.tintDrawable(accountSetupBinding.scanQr.getDrawable(),
  470. getResources().getColor(R.color.login_text_color));
  471. } else {
  472. accountSetupBinding.scanQr.setVisibility(View.GONE);
  473. }
  474. }
  475. /**
  476. * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
  477. */
  478. private void initServerPreFragment(Bundle savedInstanceState) {
  479. // step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
  480. if (savedInstanceState == null) {
  481. if (mAccount != null) {
  482. String baseUrl = mAccountMgr.getUserData(mAccount, Constants.KEY_OC_BASE_URL);
  483. if (TextUtils.isEmpty(baseUrl)) {
  484. mServerInfo.mBaseUrl = "";
  485. } else {
  486. mServerInfo.mBaseUrl = baseUrl;
  487. }
  488. // TODO do next in a setter for mBaseUrl
  489. mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith(HTTPS_PROTOCOL);
  490. mServerInfo.mVersion = accountManager.getServerVersion(mAccount);
  491. } else {
  492. mServerInfo.mBaseUrl = getString(R.string.webview_login_url).trim();
  493. mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith(HTTPS_PROTOCOL);
  494. }
  495. } else {
  496. mServerStatusText = savedInstanceState.getString(KEY_SERVER_STATUS_TEXT);
  497. mServerStatusIcon = savedInstanceState.getInt(KEY_SERVER_STATUS_ICON);
  498. // TODO parcelable
  499. mServerInfo.mIsSslConn = savedInstanceState.getBoolean(KEY_IS_SSL_CONN);
  500. mServerInfo.mBaseUrl = savedInstanceState.getString(KEY_HOST_URL_TEXT);
  501. String ocVersion = savedInstanceState.getString(KEY_OC_VERSION);
  502. if (ocVersion != null) {
  503. mServerInfo.mVersion = new OwnCloudVersion(ocVersion);
  504. }
  505. mServerInfo.mAuthMethod = AuthenticationMethod.valueOf(
  506. savedInstanceState.getString(KEY_SERVER_AUTH_METHOD));
  507. }
  508. }
  509. /**
  510. * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
  511. */
  512. private void initAuthorizationPreFragment(Bundle savedInstanceState) {
  513. /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
  514. if (savedInstanceState != null) {
  515. mAuthStatusText = savedInstanceState.getString(KEY_AUTH_STATUS_TEXT);
  516. mAuthStatusIcon = savedInstanceState.getInt(KEY_AUTH_STATUS_ICON);
  517. }
  518. /// step 2 - set properties of UI elements (text, visibility, enabled...)
  519. showAuthStatus();
  520. accountSetupBinding.hostUrlInput.setImeOptions(EditorInfo.IME_ACTION_NEXT);
  521. accountSetupBinding.hostUrlInput.setOnEditorActionListener(this);
  522. }
  523. /**
  524. * Saves relevant state before {@link #onPause()}
  525. * <p>
  526. * See {@link super#onSaveInstanceState(Bundle)}
  527. */
  528. @Override
  529. protected void onSaveInstanceState(@NonNull Bundle outState) {
  530. //Log_OC.e(TAG, "onSaveInstanceState init" );
  531. super.onSaveInstanceState(outState);
  532. /// global state
  533. outState.putLong(KEY_WAITING_FOR_OP_ID, mWaitingForOpId);
  534. outState.putBoolean(KEY_IS_SSL_CONN, mServerInfo.mIsSslConn);
  535. outState.putString(KEY_HOST_URL_TEXT, mServerInfo.mBaseUrl);
  536. if (mServerInfo.mVersion != null) {
  537. outState.putString(KEY_OC_VERSION, mServerInfo.mVersion.getVersion());
  538. }
  539. outState.putString(KEY_SERVER_AUTH_METHOD, mServerInfo.mAuthMethod.name());
  540. /// authentication
  541. outState.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG, mIsFirstAuthAttempt);
  542. /// AsyncTask (User and password)
  543. if (mAsyncTask != null) {
  544. mAsyncTask.cancel(true);
  545. outState.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS, true);
  546. } else {
  547. outState.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS, false);
  548. }
  549. mAsyncTask = null;
  550. }
  551. @Override
  552. public void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
  553. super.onRestoreInstanceState(savedInstanceState);
  554. // AsyncTask
  555. boolean inProgress = savedInstanceState.getBoolean(KEY_ASYNC_TASK_IN_PROGRESS);
  556. if (inProgress) {
  557. String username = savedInstanceState.getString(KEY_USERNAME);
  558. String password = savedInstanceState.getString(KEY_PASSWORD);
  559. OwnCloudCredentials credentials = OwnCloudCredentialsFactory.newBasicCredentials(username, password);
  560. accessRootFolder(credentials);
  561. }
  562. }
  563. /**
  564. * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION request is
  565. * caught here.
  566. * <p>
  567. * To make this possible, this activity needs to be qualified with android:launchMode = "singleTask" in the
  568. * AndroidManifest.xml file.
  569. */
  570. @Override
  571. protected void onNewIntent(Intent intent) {
  572. super.onNewIntent(intent);
  573. Log_OC.d(TAG, "onNewIntent()");
  574. if (intent.getBooleanExtra(FirstRunActivity.EXTRA_EXIT, false)) {
  575. super.finish();
  576. }
  577. onlyAdd = intent.getBooleanExtra(KEY_ONLY_ADD, false) || checkIfViaSSO(intent);
  578. // Passcode
  579. PassCodeManager passCodeManager = new PassCodeManager(preferences);
  580. passCodeManager.onActivityStarted(this);
  581. Uri data = intent.getData();
  582. if (data != null && data.toString().startsWith(getString(R.string.login_data_own_scheme))) {
  583. if (!getResources().getBoolean(R.bool.multiaccount_support) &&
  584. accountManager.getAccounts().length == 1) {
  585. Toast.makeText(this, R.string.no_mutliple_accounts_allowed, Toast.LENGTH_LONG).show();
  586. finish();
  587. return;
  588. } else {
  589. parseAndLoginFromWebView(data.toString());
  590. }
  591. }
  592. if (intent.getBooleanExtra(EXTRA_USE_PROVIDER_AS_WEBLOGIN, false)) {
  593. accountSetupWebviewBinding = AccountSetupWebviewBinding.inflate(getLayoutInflater());
  594. setContentView(accountSetupWebviewBinding.getRoot());
  595. initWebViewLogin(getString(R.string.provider_registration_server), true);
  596. }
  597. }
  598. private boolean checkIfViaSSO(Intent intent) {
  599. Bundle extras = intent.getExtras();
  600. if (extras == null) {
  601. return false;
  602. } else {
  603. String authTokenType = extras.getString("authTokenType");
  604. return "SSO".equals(authTokenType);
  605. }
  606. }
  607. /**
  608. * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION, and deferred
  609. * in {@link #onNewIntent(Intent)}, is processed here.
  610. */
  611. @Override
  612. protected void onResume() {
  613. super.onResume();
  614. // bind to Operations Service
  615. mOperationsServiceConnection = new OperationsServiceConnection();
  616. if (!bindService(new Intent(this, OperationsService.class),
  617. mOperationsServiceConnection,
  618. Context.BIND_AUTO_CREATE)) {
  619. DisplayUtils.showSnackMessage(accountSetupBinding.scroll, R.string.error_cant_bind_to_operations_service);
  620. finish();
  621. }
  622. if (mOperationsServiceBinder != null) {
  623. doOnResumeAndBound();
  624. }
  625. }
  626. @Override
  627. protected void onPause() {
  628. if (mOperationsServiceBinder != null) {
  629. mOperationsServiceBinder.removeOperationListener(this);
  630. }
  631. super.onPause();
  632. }
  633. @Override
  634. protected void onDestroy() {
  635. if (mOperationsServiceConnection != null) {
  636. unbindService(mOperationsServiceConnection);
  637. mOperationsServiceBinder = null;
  638. }
  639. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
  640. super.onDestroy();
  641. }
  642. private void checkOcServer() {
  643. String uri;
  644. if (accountSetupBinding != null && accountSetupBinding.hostUrlInput.getText() != null &&
  645. !accountSetupBinding.hostUrlInput.getText().toString().isEmpty()) {
  646. uri = accountSetupBinding.hostUrlInput.getText().toString().trim();
  647. } else {
  648. uri = mServerInfo.mBaseUrl;
  649. }
  650. mServerInfo = new GetServerInfoOperation.ServerInfo();
  651. if (uri.length() != 0) {
  652. if (accountSetupBinding != null) {
  653. uri = AuthenticatorUrlUtils.stripIndexPhpOrAppsFiles(uri);
  654. accountSetupBinding.hostUrlInput.setText(uri);
  655. }
  656. try {
  657. uri = AuthenticatorUrlUtils.normalizeScheme(uri);
  658. } catch (IllegalArgumentException ex) {
  659. // Let the Nextcloud library check the error of the malformed URI
  660. Log_OC.e(TAG, "Invalid URL", ex);
  661. }
  662. // Handle internationalized domain names
  663. try {
  664. uri = DisplayUtils.convertIdn(uri, true);
  665. } catch (IllegalArgumentException ex) {
  666. // Let the Nextcloud library check the error of the malformed URI
  667. Log_OC.e(TAG, "Error converting internationalized domain name " + uri, ex);
  668. }
  669. if (accountSetupBinding != null) {
  670. mServerStatusText = getResources().getString(R.string.auth_testing_connection);
  671. mServerStatusIcon = R.drawable.progress_small;
  672. showServerStatus();
  673. }
  674. // TODO maybe do this via async task
  675. Intent getServerInfoIntent = new Intent();
  676. getServerInfoIntent.setAction(OperationsService.ACTION_GET_SERVER_INFO);
  677. getServerInfoIntent.putExtra(OperationsService.EXTRA_SERVER_URL,
  678. AuthenticatorUrlUtils.normalizeUrlSuffix(uri));
  679. if (mOperationsServiceBinder != null) {
  680. mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getServerInfoIntent);
  681. } else {
  682. Log_OC.e(TAG, "Server check tried with OperationService unbound!");
  683. }
  684. }
  685. }
  686. /**
  687. * Tests the credentials entered by the user performing a check of existence on the root folder of the ownCloud
  688. * server.
  689. */
  690. private void checkBasicAuthorization(@Nullable String webViewUsername, @Nullable String webViewPassword) {
  691. // be gentle with the user
  692. IndeterminateProgressDialog dialog = IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login,
  693. true);
  694. FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
  695. ft.add(dialog, WAIT_DIALOG_TAG);
  696. ft.commitAllowingStateLoss();
  697. // validate credentials accessing the root folder
  698. OwnCloudCredentials credentials = OwnCloudCredentialsFactory.newBasicCredentials(webViewUsername,
  699. webViewPassword);
  700. accessRootFolder(credentials);
  701. }
  702. private void accessRootFolder(OwnCloudCredentials credentials) {
  703. mAsyncTask = new AuthenticatorAsyncTask(this);
  704. Object[] params = {mServerInfo.mBaseUrl, credentials};
  705. mAsyncTask.execute(params);
  706. }
  707. /**
  708. * Callback method invoked when a RemoteOperation executed by this Activity finishes.
  709. * <p>
  710. * Dispatches the operation flow to the right method.
  711. */
  712. @Override
  713. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  714. if (operation instanceof GetServerInfoOperation) {
  715. if (operation.hashCode() == mWaitingForOpId) {
  716. onGetServerInfoFinish(result);
  717. } // else nothing ; only the last check operation is considered;
  718. // multiple can be started if the user amends a URL quickly
  719. } else if (operation instanceof GetUserInfoRemoteOperation) {
  720. onGetUserNameFinish(result);
  721. }
  722. }
  723. private void onGetUserNameFinish(RemoteOperationResult<UserInfo> result) {
  724. mWaitingForOpId = Long.MAX_VALUE;
  725. if (result.isSuccess()) {
  726. boolean success = false;
  727. if (mAction == ACTION_CREATE) {
  728. success = createAccount(result);
  729. } else {
  730. try {
  731. updateAccountAuthentication();
  732. success = true;
  733. } catch (AccountNotFoundException e) {
  734. Log_OC.e(TAG, "Account " + mAccount + " was removed!", e);
  735. DisplayUtils.showSnackMessage(accountSetupBinding.scroll, R.string.auth_account_does_not_exist);
  736. finish();
  737. }
  738. }
  739. if (success) {
  740. finish();
  741. }
  742. } else {
  743. // TODO check
  744. int statusText = result.getCode() == ResultCode.MAINTENANCE_MODE ? R.string.maintenance_mode : R.string.auth_fail_get_user_name;
  745. updateStatusIconFailUserName(statusText);
  746. showAuthStatus();
  747. Log_OC.e(TAG, "Access to user name failed: " + result.getLogMessage());
  748. }
  749. }
  750. /**
  751. * Processes the result of the server check performed when the user finishes the enter of the server URL.
  752. *
  753. * @param result Result of the check.
  754. */
  755. private void onGetServerInfoFinish(RemoteOperationResult result) {
  756. /// update activity state
  757. mWaitingForOpId = Long.MAX_VALUE;
  758. if (result.isSuccess()) {
  759. /// SUCCESS means:
  760. // 1. connection succeeded, and we know if it's SSL or not
  761. // 2. server is installed
  762. // 3. we got the server version
  763. // 4. we got the authentication method required by the server
  764. mServerInfo = (GetServerInfoOperation.ServerInfo) (result.getData().get(0));
  765. // show outdated warning
  766. if (getResources().getBoolean(R.bool.show_outdated_server_warning) &&
  767. MainApp.OUTDATED_SERVER_VERSION.isSameMajorVersion(mServerInfo.mVersion) &&
  768. !mServerInfo.hasExtendedSupport) {
  769. DisplayUtils.showServerOutdatedSnackbar(this, Snackbar.LENGTH_INDEFINITE);
  770. }
  771. if (webViewUser != null && !webViewUser.isEmpty() &&
  772. webViewPassword != null && !webViewPassword.isEmpty()) {
  773. checkBasicAuthorization(webViewUser, webViewPassword);
  774. } else {
  775. new Thread(() -> {
  776. OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(mServerInfo.mBaseUrl),
  777. this,
  778. true);
  779. RemoteOperationResult remoteOperationResult = new GetCapabilitiesRemoteOperation().execute(client);
  780. if (remoteOperationResult.isSuccess() &&
  781. remoteOperationResult.getData() != null &&
  782. remoteOperationResult.getData().size() > 0) {
  783. OCCapability capability = (OCCapability) remoteOperationResult.getData().get(0);
  784. try {
  785. primaryColor = Color.parseColor(capability.getServerColor());
  786. } catch (Exception e) {
  787. // falls back to primary color
  788. }
  789. }
  790. }).start();
  791. accountSetupWebviewBinding = AccountSetupWebviewBinding.inflate(getLayoutInflater());
  792. setContentView(accountSetupWebviewBinding.getRoot());
  793. initWebViewLogin(mServerInfo.mBaseUrl + WEB_LOGIN, false);
  794. }
  795. } else {
  796. updateServerStatusIconAndText(result);
  797. showServerStatus();
  798. }
  799. // very special case (TODO: move to a common place for all the remote operations)
  800. if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
  801. showUntrustedCertDialog(result);
  802. }
  803. }
  804. /**
  805. * Chooses the right icon and text to show to the user for the received operation result.
  806. *
  807. * @param result Result of a remote operation performed in this activity
  808. */
  809. private void updateServerStatusIconAndText(RemoteOperationResult result) {
  810. mServerStatusIcon = R.drawable.ic_alert; // the most common case in the switch below
  811. switch (result.getCode()) {
  812. case OK_SSL:
  813. mServerStatusIcon = R.drawable.ic_lock_white;
  814. mServerStatusText = getResources().getString(R.string.auth_secure_connection);
  815. break;
  816. case OK_NO_SSL:
  817. case OK:
  818. if (accountSetupBinding.hostUrlInput.getText() != null &&
  819. accountSetupBinding.hostUrlInput
  820. .getText()
  821. .toString()
  822. .trim()
  823. .toLowerCase(Locale.ROOT)
  824. .startsWith(HTTP_PROTOCOL)) {
  825. mServerStatusText = getResources().getString(R.string.auth_connection_established);
  826. mServerStatusIcon = R.drawable.ic_ok;
  827. } else {
  828. mServerStatusText = getResources().getString(R.string.auth_nossl_plain_ok_title);
  829. mServerStatusIcon = R.drawable.ic_lock_open_white;
  830. }
  831. break;
  832. case NO_NETWORK_CONNECTION:
  833. mServerStatusIcon = R.drawable.no_network;
  834. mServerStatusText = getResources().getString(R.string.auth_no_net_conn_title);
  835. break;
  836. case SSL_RECOVERABLE_PEER_UNVERIFIED:
  837. mServerStatusText = getResources().getString(R.string.auth_ssl_unverified_server_title);
  838. break;
  839. case BAD_OC_VERSION:
  840. mServerStatusText = getResources().getString(R.string.auth_bad_oc_version_title);
  841. break;
  842. case WRONG_CONNECTION:
  843. mServerStatusText = getResources().getString(R.string.auth_wrong_connection_title);
  844. break;
  845. case TIMEOUT:
  846. mServerStatusText = getResources().getString(R.string.auth_timeout_title);
  847. break;
  848. case INCORRECT_ADDRESS:
  849. mServerStatusText = getResources().getString(R.string.auth_incorrect_address_title);
  850. break;
  851. case SSL_ERROR:
  852. mServerStatusText = getResources().getString(R.string.auth_ssl_general_error_title);
  853. break;
  854. case UNAUTHORIZED:
  855. mServerStatusText = getResources().getString(R.string.auth_unauthorized);
  856. break;
  857. case HOST_NOT_AVAILABLE:
  858. mServerStatusText = getResources().getString(R.string.auth_unknown_host_title);
  859. break;
  860. case INSTANCE_NOT_CONFIGURED:
  861. mServerStatusText = getResources().getString(R.string.auth_not_configured_title);
  862. break;
  863. case FILE_NOT_FOUND:
  864. mServerStatusText = getResources().getString(R.string.auth_incorrect_path_title);
  865. break;
  866. case OAUTH2_ERROR:
  867. mServerStatusText = getResources().getString(R.string.auth_oauth_error);
  868. break;
  869. case OAUTH2_ERROR_ACCESS_DENIED:
  870. mServerStatusText = getResources().getString(R.string.auth_oauth_error_access_denied);
  871. break;
  872. case UNHANDLED_HTTP_CODE:
  873. mServerStatusText = getResources().getString(R.string.auth_unknown_error_http_title);
  874. break;
  875. case UNKNOWN_ERROR:
  876. if (result.getException() != null &&
  877. !TextUtils.isEmpty(result.getException().getMessage())) {
  878. mServerStatusText = getResources().getString(
  879. R.string.auth_unknown_error_exception_title,
  880. result.getException().getMessage()
  881. );
  882. } else {
  883. mServerStatusText = getResources().getString(R.string.auth_unknown_error_title);
  884. }
  885. break;
  886. case OK_REDIRECT_TO_NON_SECURE_CONNECTION:
  887. mServerStatusIcon = R.drawable.ic_lock_open_white;
  888. mServerStatusText = getResources().getString(R.string.auth_redirect_non_secure_connection_title);
  889. break;
  890. case MAINTENANCE_MODE:
  891. mServerStatusText = getResources().getString(R.string.maintenance_mode);
  892. break;
  893. case UNTRUSTED_DOMAIN:
  894. mServerStatusText = getResources().getString(R.string.untrusted_domain);
  895. break;
  896. default:
  897. mServerStatusText = EMPTY_STRING;
  898. mServerStatusIcon = 0;
  899. break;
  900. }
  901. }
  902. /**
  903. * Chooses the right icon and text to show to the user for the received operation result.
  904. *
  905. * @param result Result of a remote operation performed in this activity
  906. */
  907. private void updateAuthStatusIconAndText(RemoteOperationResult result) {
  908. mAuthStatusIcon = R.drawable.ic_alert; // the most common case in the switch below
  909. switch (result.getCode()) {
  910. case OK_SSL:
  911. mAuthStatusIcon = R.drawable.ic_lock_white;
  912. mAuthStatusText = getResources().getString(R.string.auth_secure_connection);
  913. break;
  914. case OK_NO_SSL:
  915. case OK:
  916. if (showWebViewLoginUrl) {
  917. if (accountSetupBinding.hostUrlInput.getText() != null &&
  918. accountSetupBinding.hostUrlInput
  919. .getText()
  920. .toString()
  921. .trim()
  922. .toLowerCase(Locale.ROOT)
  923. .startsWith(HTTP_PROTOCOL)) {
  924. mAuthStatusText = getResources().getString(R.string.auth_connection_established);
  925. mAuthStatusIcon = R.drawable.ic_ok;
  926. } else {
  927. mAuthStatusText = getResources().getString(R.string.auth_nossl_plain_ok_title);
  928. mAuthStatusIcon = R.drawable.ic_lock_open_white;
  929. }
  930. }
  931. break;
  932. case NO_NETWORK_CONNECTION:
  933. mAuthStatusIcon = R.drawable.no_network;
  934. mAuthStatusText = getResources().getString(R.string.auth_no_net_conn_title);
  935. break;
  936. case SSL_RECOVERABLE_PEER_UNVERIFIED:
  937. mAuthStatusText = getResources().getString(R.string.auth_ssl_unverified_server_title);
  938. break;
  939. case TIMEOUT:
  940. mAuthStatusText = getResources().getString(R.string.auth_timeout_title);
  941. break;
  942. case HOST_NOT_AVAILABLE:
  943. mAuthStatusText = getResources().getString(R.string.auth_unknown_host_title);
  944. break;
  945. case ACCOUNT_NOT_NEW:
  946. mAuthStatusText = getString(R.string.auth_account_not_new);
  947. if (!showWebViewLoginUrl) {
  948. DisplayUtils.showErrorAndFinishActivity(this, mAuthStatusText);
  949. }
  950. break;
  951. case UNHANDLED_HTTP_CODE:
  952. default:
  953. mAuthStatusText = ErrorMessageAdapter.getErrorCauseMessage(result, null, getResources());
  954. if (!showWebViewLoginUrl) {
  955. DisplayUtils.showErrorAndFinishActivity(this, mAuthStatusText);
  956. }
  957. }
  958. }
  959. private void updateStatusIconFailUserName(int failedStatusText) {
  960. mAuthStatusIcon = R.drawable.ic_alert;
  961. mAuthStatusText = getResources().getString(failedStatusText);
  962. }
  963. /**
  964. * Processes the result of the access check performed to try the user credentials.
  965. * <p>
  966. * Creates a new account through the AccountManager.
  967. *
  968. * @param result Result of the operation.
  969. */
  970. @Override
  971. public void onAuthenticatorTaskCallback(RemoteOperationResult<UserInfo> result) {
  972. mWaitingForOpId = Long.MAX_VALUE;
  973. dismissWaitingDialog();
  974. mAsyncTask = null;
  975. if (result.isSuccess()) {
  976. Log_OC.d(TAG, "Successful access - time to save the account");
  977. boolean success = false;
  978. if (mAction == ACTION_CREATE) {
  979. success = createAccount(result);
  980. } else {
  981. try {
  982. updateAccountAuthentication();
  983. success = true;
  984. } catch (AccountNotFoundException e) {
  985. Log_OC.e(TAG, "Account " + mAccount + " was removed!", e);
  986. DisplayUtils.showSnackMessage(accountSetupBinding.scroll, R.string.auth_account_does_not_exist);
  987. finish();
  988. }
  989. }
  990. // Reset webView
  991. webViewPassword = null;
  992. webViewUser = null;
  993. deleteCookies();
  994. if (success) {
  995. accountManager.setCurrentOwnCloudAccount(mAccount.name);
  996. if (onlyAdd) {
  997. finish();
  998. } else {
  999. Intent i = new Intent(this, FileDisplayActivity.class);
  1000. i.setAction(FileDisplayActivity.RESTART);
  1001. i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  1002. startActivity(i);
  1003. }
  1004. } else {
  1005. // init webView again
  1006. if (accountSetupWebviewBinding != null) {
  1007. accountSetupWebviewBinding.loginWebview.setVisibility(View.GONE);
  1008. }
  1009. accountSetupBinding = AccountSetupBinding.inflate(getLayoutInflater());
  1010. setContentView(accountSetupBinding.getRoot());
  1011. initOverallUi();
  1012. accountSetupBinding.hostUrlInput.setText(mServerInfo.mBaseUrl);
  1013. accountSetupBinding.serverStatusText.setVisibility(View.GONE);
  1014. showAuthStatus();
  1015. }
  1016. } else if (result.isServerFail() || result.isException()) {
  1017. /// server errors or exceptions in authorization take to requiring a new check of the server
  1018. mServerInfo = new GetServerInfoOperation.ServerInfo();
  1019. // update status icon and text
  1020. updateServerStatusIconAndText(result);
  1021. showServerStatus();
  1022. mAuthStatusIcon = 0;
  1023. mAuthStatusText = EMPTY_STRING;
  1024. // very special case (TODO: move to a common place for all the remote operations)
  1025. if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
  1026. showUntrustedCertDialog(result);
  1027. }
  1028. } else { // authorization fail due to client side - probably wrong credentials
  1029. if (accountSetupWebviewBinding != null) {
  1030. initWebViewLogin(mServerInfo.mBaseUrl + WEB_LOGIN, false);
  1031. DisplayUtils.showSnackMessage(this,
  1032. accountSetupWebviewBinding.loginWebview, R.string.auth_access_failed,
  1033. result.getLogMessage());
  1034. } else {
  1035. DisplayUtils.showSnackMessage(this, R.string.auth_access_failed, result.getLogMessage());
  1036. // init webView again
  1037. updateAuthStatusIconAndText(result);
  1038. }
  1039. // reset webview
  1040. webViewPassword = null;
  1041. webViewUser = null;
  1042. deleteCookies();
  1043. Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
  1044. }
  1045. }
  1046. /**
  1047. * Updates the authentication token.
  1048. * <p>
  1049. * Sets the proper response so that the AccountAuthenticator that started this activity saves a new authorization
  1050. * token for mAccount.
  1051. * <p>
  1052. * Kills the session kept by OwnCloudClientManager so that a new one will created with the new credentials when
  1053. * needed.
  1054. */
  1055. private void updateAccountAuthentication() throws AccountNotFoundException {
  1056. Bundle response = new Bundle();
  1057. response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
  1058. response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);
  1059. response.putString(AccountManager.KEY_AUTHTOKEN, webViewPassword);
  1060. mAccountMgr.setPassword(mAccount, webViewPassword);
  1061. // remove managed clients for this account to enforce creation with fresh credentials
  1062. OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount, this);
  1063. OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(ocAccount);
  1064. setAccountAuthenticatorResult(response);
  1065. Intent intent = new Intent();
  1066. intent.putExtras(response);
  1067. setResult(RESULT_OK, intent);
  1068. }
  1069. /**
  1070. * Creates a new account through the Account Authenticator that started this activity.
  1071. * <p>
  1072. * This makes the account permanent.
  1073. * <p>
  1074. * TODO Decide how to name the OAuth accounts
  1075. */
  1076. @SuppressFBWarnings("DMI")
  1077. @SuppressLint("TrulyRandom")
  1078. protected boolean createAccount(RemoteOperationResult<UserInfo> authResult) {
  1079. String accountType = MainApp.getAccountType(this);
  1080. // create and save new ownCloud account
  1081. String lastPermanentLocation = authResult.getLastPermanentLocation();
  1082. if (lastPermanentLocation != null) {
  1083. mServerInfo.mBaseUrl = AuthenticatorUrlUtils.trimWebdavSuffix(lastPermanentLocation);
  1084. }
  1085. Uri uri = Uri.parse(mServerInfo.mBaseUrl);
  1086. // used for authenticate on every login/network connection, determined by first login (weblogin/old login)
  1087. // can be anything: email, name, name with whitespaces
  1088. String loginName = webViewUser;
  1089. String accountName = com.owncloud.android.lib.common.accounts.AccountUtils.buildAccountName(uri, loginName);
  1090. Account newAccount = new Account(accountName, accountType);
  1091. if (accountManager.exists(newAccount)) {
  1092. // fail - not a new account, but an existing one; disallow
  1093. RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW);
  1094. updateAuthStatusIconAndText(result);
  1095. showAuthStatus();
  1096. Log_OC.d(TAG, result.getLogMessage());
  1097. return false;
  1098. } else {
  1099. UserInfo userInfo = authResult.getResultData();
  1100. if (userInfo == null) {
  1101. Log_OC.e(this, "Could not read user data!");
  1102. return false;
  1103. }
  1104. mAccount = newAccount;
  1105. mAccountMgr.addAccountExplicitly(mAccount, webViewPassword, null);
  1106. // add the new account as default in preferences, if there is none already
  1107. User defaultAccount = accountManager.getUser();
  1108. if (defaultAccount.isAnonymous()) {
  1109. SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
  1110. editor.putString("select_oc_account", accountName);
  1111. editor.apply();
  1112. }
  1113. /// prepare result to return to the Authenticator
  1114. // TODO check again what the Authenticator makes with it; probably has the same
  1115. // effect as addAccountExplicitly, but it's not well done
  1116. final Intent intent = new Intent();
  1117. intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType);
  1118. intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
  1119. intent.putExtra(AccountManager.KEY_USERDATA, loginName);
  1120. /// add user data to the new account; TODO probably can be done in the last parameter
  1121. // addAccountExplicitly, or in KEY_USERDATA
  1122. mAccountMgr.setUserData(mAccount, Constants.KEY_OC_VERSION, mServerInfo.mVersion.getVersion());
  1123. mAccountMgr.setUserData(mAccount, Constants.KEY_OC_BASE_URL, mServerInfo.mBaseUrl);
  1124. mAccountMgr.setUserData(mAccount, Constants.KEY_DISPLAY_NAME, userInfo.getDisplayName());
  1125. mAccountMgr.setUserData(mAccount, Constants.KEY_USER_ID, userInfo.getId());
  1126. mAccountMgr.setUserData(mAccount,
  1127. Constants.KEY_OC_ACCOUNT_VERSION,
  1128. Integer.toString(UserAccountManager.ACCOUNT_VERSION_WITH_PROPER_ID));
  1129. setAccountAuthenticatorResult(intent.getExtras());
  1130. setResult(RESULT_OK, intent);
  1131. // notify Document Provider
  1132. DocumentsStorageProvider.notifyRootsChanged(this);
  1133. return true;
  1134. }
  1135. }
  1136. public void onScan() {
  1137. if (PermissionUtil.checkSelfPermission(this, Manifest.permission.CAMERA)) {
  1138. startQRScanner();
  1139. } else {
  1140. PermissionUtil.requestCameraPermission(this);
  1141. }
  1142. }
  1143. private void startQRScanner() {
  1144. Intent intent = new Intent(this, QrCodeActivity.class);
  1145. startActivityForResult(intent, REQUEST_CODE_QR_SCAN);
  1146. }
  1147. @Override
  1148. public void onRequestPermissionsResult(int requestCode,
  1149. @NonNull String[] permissions,
  1150. @NonNull int[] grantResults) {
  1151. if (requestCode == PermissionUtil.PERMISSIONS_CAMERA) {// If request is cancelled, result arrays are empty.
  1152. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  1153. // permission was granted
  1154. startQRScanner();
  1155. }
  1156. } else {
  1157. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  1158. }
  1159. }
  1160. /**
  1161. * /** Updates the content and visibility state of the icon and text associated to the last check on the ownCloud
  1162. * server.
  1163. */
  1164. private void showServerStatus() {
  1165. if (mServerStatusIcon == NO_ICON && EMPTY_STRING.equals(mServerStatusText)) {
  1166. accountSetupBinding.serverStatusText.setVisibility(View.INVISIBLE);
  1167. } else {
  1168. accountSetupBinding.serverStatusText.setText(mServerStatusText);
  1169. accountSetupBinding.serverStatusText.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon, 0, 0, 0);
  1170. accountSetupBinding.serverStatusText.setVisibility(View.VISIBLE);
  1171. }
  1172. }
  1173. /**
  1174. * Updates the content and visibility state of the icon and text associated to the interactions with the OAuth
  1175. * authorization server.
  1176. */
  1177. private void showAuthStatus() {
  1178. if (accountSetupBinding != null) {
  1179. if (mAuthStatusIcon == NO_ICON && EMPTY_STRING.equals(mAuthStatusText)) {
  1180. accountSetupBinding.authStatusText.setVisibility(View.INVISIBLE);
  1181. } else {
  1182. accountSetupBinding.authStatusText.setText(mAuthStatusText);
  1183. accountSetupBinding.authStatusText.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon, 0, 0, 0);
  1184. accountSetupBinding.authStatusText.setVisibility(View.VISIBLE);
  1185. }
  1186. }
  1187. }
  1188. /**
  1189. * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
  1190. * <p>
  1191. * Used to trigger the authentication check when the user presses 'enter' after writing the password, or to throw
  1192. * the server test when the only field on screen is the URL input field.
  1193. */
  1194. @Override
  1195. public boolean onEditorAction(TextView inputField, int actionId, KeyEvent event) {
  1196. if ((actionId == EditorInfo.IME_ACTION_NEXT || actionId == EditorInfo.IME_NULL)
  1197. && inputField != null && inputField.equals(accountSetupBinding.hostUrlInput)) {
  1198. checkOcServer();
  1199. }
  1200. return false; // always return false to grant that the software keyboard is hidden anyway
  1201. }
  1202. /**
  1203. * Show untrusted cert dialog
  1204. */
  1205. public void showUntrustedCertDialog(X509Certificate x509Certificate, SslError error, SslErrorHandler handler) {
  1206. // Show a dialog with the certificate info
  1207. SslUntrustedCertDialog dialog;
  1208. if (x509Certificate == null) {
  1209. dialog = SslUntrustedCertDialog.newInstanceForEmptySslError(error, handler);
  1210. } else {
  1211. dialog = SslUntrustedCertDialog.newInstanceForFullSslError(x509Certificate, error, handler);
  1212. }
  1213. FragmentManager fm = getSupportFragmentManager();
  1214. FragmentTransaction ft = fm.beginTransaction();
  1215. ft.addToBackStack(null);
  1216. dialog.show(ft, UNTRUSTED_CERT_DIALOG_TAG);
  1217. }
  1218. /**
  1219. * Show untrusted cert dialog
  1220. */
  1221. private void showUntrustedCertDialog(RemoteOperationResult result) {
  1222. // Show a dialog with the certificate info
  1223. SslUntrustedCertDialog dialog = SslUntrustedCertDialog.
  1224. newInstanceForFullSslError((CertificateCombinedException) result.getException());
  1225. FragmentManager fm = getSupportFragmentManager();
  1226. FragmentTransaction ft = fm.beginTransaction();
  1227. ft.addToBackStack(null);
  1228. dialog.show(ft, UNTRUSTED_CERT_DIALOG_TAG);
  1229. }
  1230. private void doOnResumeAndBound() {
  1231. mOperationsServiceBinder.addOperationListener(this, mHandler);
  1232. if (mWaitingForOpId <= Integer.MAX_VALUE) {
  1233. mOperationsServiceBinder.dispatchResultIfFinished((int) mWaitingForOpId, this);
  1234. }
  1235. }
  1236. private void dismissWaitingDialog() {
  1237. Fragment frag = getSupportFragmentManager().findFragmentByTag(WAIT_DIALOG_TAG);
  1238. if (frag instanceof DialogFragment) {
  1239. DialogFragment dialog = (DialogFragment) frag;
  1240. try {
  1241. dialog.dismiss();
  1242. } catch (IllegalStateException e) {
  1243. Log_OC.e(TAG, e.getMessage());
  1244. dialog.dismissAllowingStateLoss();
  1245. }
  1246. }
  1247. }
  1248. /**
  1249. * Implements callback methods for service binding.
  1250. */
  1251. private class OperationsServiceConnection implements ServiceConnection {
  1252. @Override
  1253. public void onServiceConnected(ComponentName component, IBinder service) {
  1254. if (component.equals(
  1255. new ComponentName(AuthenticatorActivity.this, OperationsService.class)
  1256. )) {
  1257. mOperationsServiceBinder = (OperationsServiceBinder) service;
  1258. Uri data = getIntent().getData();
  1259. if (data != null && data.toString().startsWith(getString(R.string.login_data_own_scheme))) {
  1260. try {
  1261. String prefix = getString(R.string.login_data_own_scheme) + PROTOCOL_SUFFIX + "login/";
  1262. LoginUrlInfo loginUrlInfo = parseLoginDataUrl(prefix, data.toString());
  1263. mServerInfo.mBaseUrl = AuthenticatorUrlUtils.normalizeUrlSuffix(loginUrlInfo.serverAddress);
  1264. webViewUser = loginUrlInfo.username;
  1265. webViewPassword = loginUrlInfo.password;
  1266. doOnResumeAndBound();
  1267. checkOcServer();
  1268. } catch (Exception e) {
  1269. mServerStatusIcon = R.drawable.ic_alert;
  1270. mServerStatusText = getString(R.string.qr_could_not_be_read);
  1271. showServerStatus();
  1272. }
  1273. } else {
  1274. doOnResumeAndBound();
  1275. }
  1276. }
  1277. }
  1278. @Override
  1279. public void onServiceDisconnected(ComponentName component) {
  1280. if (component.equals(
  1281. new ComponentName(AuthenticatorActivity.this, OperationsService.class)
  1282. )) {
  1283. Log_OC.e(TAG, "Operations service crashed");
  1284. mOperationsServiceBinder = null;
  1285. }
  1286. }
  1287. }
  1288. @Override
  1289. protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
  1290. super.onActivityResult(requestCode, resultCode, data);
  1291. if (requestCode == REQUEST_CODE_QR_SCAN) {
  1292. if (data == null) {
  1293. return;
  1294. }
  1295. String result = data.getStringExtra("com.blikoon.qrcodescanner.got_qr_scan_relult");
  1296. if (result == null || !result.startsWith(getString(R.string.login_data_own_scheme))) {
  1297. mServerStatusIcon = R.drawable.ic_alert;
  1298. mServerStatusText = "QR Code could not be read!";
  1299. showServerStatus();
  1300. return;
  1301. }
  1302. if (!getResources().getBoolean(R.bool.multiaccount_support) &&
  1303. accountManager.getAccounts().length == 1) {
  1304. Toast.makeText(this, R.string.no_mutliple_accounts_allowed, Toast.LENGTH_LONG).show();
  1305. } else {
  1306. parseAndLoginFromWebView(result);
  1307. }
  1308. }
  1309. }
  1310. /**
  1311. * Obtain the X509Certificate from SslError
  1312. *
  1313. * @param error SslError
  1314. * @return X509Certificate from error
  1315. */
  1316. public static X509Certificate getX509CertificateFromError(SslError error) {
  1317. Bundle bundle = SslCertificate.saveState(error.getCertificate());
  1318. X509Certificate x509Certificate;
  1319. byte[] bytes = bundle.getByteArray("x509-certificate");
  1320. if (bytes == null) {
  1321. x509Certificate = null;
  1322. } else {
  1323. try {
  1324. CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
  1325. Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
  1326. x509Certificate = (X509Certificate) cert;
  1327. } catch (CertificateException e) {
  1328. x509Certificate = null;
  1329. }
  1330. }
  1331. return x509Certificate;
  1332. }
  1333. /**
  1334. * Called from SslValidatorDialog when a new server certificate was correctly saved.
  1335. */
  1336. public void onSavedCertificate() {
  1337. checkOcServer();
  1338. }
  1339. /**
  1340. * Called from SslValidatorDialog when a new server certificate could not be saved when the user requested it.
  1341. */
  1342. @Override
  1343. public void onFailedSavingCertificate() {
  1344. DisplayUtils.showSnackMessage(this, R.string.ssl_validator_not_saved);
  1345. }
  1346. }