AuthenticatorActivity.java 63 KB

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