AuthenticatorActivity.java 64 KB

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