AuthenticatorActivity.java 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553
  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) || checkIfViaSSO(getIntent());
  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) || checkIfViaSSO(intent);
  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. private boolean checkIfViaSSO(Intent intent) {
  598. Bundle extras = intent.getExtras();
  599. if (extras == null) {
  600. return false;
  601. } else {
  602. return extras.getParcelable("accountAuthenticatorResponse") != null;
  603. }
  604. }
  605. /**
  606. * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION, and deferred
  607. * in {@link #onNewIntent(Intent)}, is processed here.
  608. */
  609. @Override
  610. protected void onResume() {
  611. super.onResume();
  612. // bind to Operations Service
  613. mOperationsServiceConnection = new OperationsServiceConnection();
  614. if (!bindService(new Intent(this, OperationsService.class),
  615. mOperationsServiceConnection,
  616. Context.BIND_AUTO_CREATE)) {
  617. DisplayUtils.showSnackMessage(findViewById(R.id.scroll), R.string.error_cant_bind_to_operations_service);
  618. finish();
  619. }
  620. if (mOperationsServiceBinder != null) {
  621. doOnResumeAndBound();
  622. }
  623. }
  624. @Override
  625. protected void onPause() {
  626. if (mOperationsServiceBinder != null) {
  627. mOperationsServiceBinder.removeOperationListener(this);
  628. }
  629. super.onPause();
  630. }
  631. @Override
  632. protected void onDestroy() {
  633. if (mOperationsServiceConnection != null) {
  634. unbindService(mOperationsServiceConnection);
  635. mOperationsServiceBinder = null;
  636. }
  637. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
  638. super.onDestroy();
  639. }
  640. private void checkOcServer() {
  641. String uri;
  642. if (mHostUrlInput != null && !mHostUrlInput.getText().toString().isEmpty()) {
  643. uri = mHostUrlInput.getText().toString().trim();
  644. } else {
  645. uri = mServerInfo.mBaseUrl;
  646. }
  647. mServerInfo = new GetServerInfoOperation.ServerInfo();
  648. if (uri.length() != 0) {
  649. if (mHostUrlInput != null) {
  650. uri = AuthenticatorUrlUtils.stripIndexPhpOrAppsFiles(uri);
  651. mHostUrlInput.setText(uri);
  652. }
  653. // Handle internationalized domain names
  654. try {
  655. uri = DisplayUtils.convertIdn(uri, true);
  656. } catch (IllegalArgumentException ex) {
  657. // Let Owncloud library check the error of the malformed URI
  658. Log_OC.e(TAG, "Error converting internationalized domain name " + uri, ex);
  659. }
  660. if (mHostUrlInput != null) {
  661. mServerStatusText = getResources().getString(R.string.auth_testing_connection);
  662. mServerStatusIcon = R.drawable.progress_small;
  663. showServerStatus();
  664. }
  665. // TODO maybe do this via async task
  666. Intent getServerInfoIntent = new Intent();
  667. getServerInfoIntent.setAction(OperationsService.ACTION_GET_SERVER_INFO);
  668. getServerInfoIntent.putExtra(OperationsService.EXTRA_SERVER_URL,
  669. AuthenticatorUrlUtils.normalizeUrlSuffix(uri));
  670. if (mOperationsServiceBinder != null) {
  671. mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getServerInfoIntent);
  672. } else {
  673. Log_OC.e(TAG, "Server check tried with OperationService unbound!");
  674. }
  675. }
  676. }
  677. /**
  678. * Tests the credentials entered by the user performing a check of existence on the root folder of the ownCloud
  679. * server.
  680. */
  681. private void checkBasicAuthorization(@Nullable String webViewUsername, @Nullable String webViewPassword) {
  682. // be gentle with the user
  683. IndeterminateProgressDialog dialog = IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login,
  684. true);
  685. FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
  686. ft.add(dialog, WAIT_DIALOG_TAG);
  687. ft.commitAllowingStateLoss();
  688. // validate credentials accessing the root folder
  689. OwnCloudCredentials credentials = OwnCloudCredentialsFactory.newBasicCredentials(webViewUsername,
  690. webViewPassword);
  691. accessRootFolder(credentials);
  692. }
  693. private void accessRootFolder(OwnCloudCredentials credentials) {
  694. mAsyncTask = new AuthenticatorAsyncTask(this);
  695. Object[] params = {mServerInfo.mBaseUrl, credentials};
  696. mAsyncTask.execute(params);
  697. }
  698. /**
  699. * Callback method invoked when a RemoteOperation executed by this Activity finishes.
  700. * <p>
  701. * Dispatches the operation flow to the right method.
  702. */
  703. @Override
  704. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  705. if (operation instanceof GetServerInfoOperation) {
  706. if (operation.hashCode() == mWaitingForOpId) {
  707. onGetServerInfoFinish(result);
  708. } // else nothing ; only the last check operation is considered;
  709. // multiple can be started if the user amends a URL quickly
  710. } else if (operation instanceof GetUserInfoRemoteOperation) {
  711. onGetUserNameFinish(result);
  712. }
  713. }
  714. private void onGetUserNameFinish(RemoteOperationResult result) {
  715. mWaitingForOpId = Long.MAX_VALUE;
  716. if (result.isSuccess()) {
  717. boolean success = false;
  718. if (mAction == ACTION_CREATE) {
  719. success = createAccount(result);
  720. } else {
  721. try {
  722. updateAccountAuthentication();
  723. success = true;
  724. } catch (AccountNotFoundException e) {
  725. Log_OC.e(TAG, "Account " + mAccount + " was removed!", e);
  726. DisplayUtils.showSnackMessage(findViewById(R.id.scroll), R.string.auth_account_does_not_exist);
  727. finish();
  728. }
  729. }
  730. if (success) {
  731. finish();
  732. }
  733. } else {
  734. // TODO check
  735. int statusText = result.getCode() == ResultCode.MAINTENANCE_MODE ? R.string.maintenance_mode : R.string.auth_fail_get_user_name;
  736. updateStatusIconFailUserName(statusText);
  737. showAuthStatus();
  738. Log_OC.e(TAG, "Access to user name failed: " + result.getLogMessage());
  739. }
  740. }
  741. /**
  742. * Processes the result of the server check performed when the user finishes the enter of the server URL.
  743. *
  744. * @param result Result of the check.
  745. */
  746. private void onGetServerInfoFinish(RemoteOperationResult result) {
  747. /// update activity state
  748. mWaitingForOpId = Long.MAX_VALUE;
  749. if (result.isSuccess()) {
  750. /// SUCCESS means:
  751. // 1. connection succeeded, and we know if it's SSL or not
  752. // 2. server is installed
  753. // 3. we got the server version
  754. // 4. we got the authentication method required by the server
  755. mServerInfo = (GetServerInfoOperation.ServerInfo) (result.getData().get(0));
  756. // show outdated warning
  757. if (getResources().getBoolean(R.bool.show_outdated_server_warning) &&
  758. MainApp.OUTDATED_SERVER_VERSION.isSameMajorVersion(mServerInfo.mVersion) &&
  759. !mServerInfo.hasExtendedSupport) {
  760. DisplayUtils.showServerOutdatedSnackbar(this, Snackbar.LENGTH_INDEFINITE);
  761. }
  762. if (webViewUser != null && !webViewUser.isEmpty() &&
  763. webViewPassword != null && !webViewPassword.isEmpty()) {
  764. checkBasicAuthorization(webViewUser, webViewPassword);
  765. } else {
  766. new Thread(() -> {
  767. OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(mServerInfo.mBaseUrl),
  768. this,
  769. true);
  770. RemoteOperationResult remoteOperationResult = new GetCapabilitiesRemoteOperation().execute(client);
  771. if (remoteOperationResult.isSuccess() &&
  772. remoteOperationResult.getData() != null &&
  773. remoteOperationResult.getData().size() > 0) {
  774. OCCapability capability = (OCCapability) remoteOperationResult.getData().get(0);
  775. try {
  776. primaryColor = Color.parseColor(capability.getServerColor());
  777. } catch (Exception e) {
  778. // falls back to primary color
  779. }
  780. }
  781. }).start();
  782. setContentView(R.layout.account_setup_webview);
  783. mLoginWebView = findViewById(R.id.login_webview);
  784. initWebViewLogin(mServerInfo.mBaseUrl + WEB_LOGIN, false);
  785. }
  786. } else {
  787. updateServerStatusIconAndText(result);
  788. showServerStatus();
  789. }
  790. // very special case (TODO: move to a common place for all the remote operations)
  791. if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
  792. showUntrustedCertDialog(result);
  793. }
  794. }
  795. /**
  796. * Chooses the right icon and text to show to the user for the received operation result.
  797. *
  798. * @param result Result of a remote operation performed in this activity
  799. */
  800. private void updateServerStatusIconAndText(RemoteOperationResult result) {
  801. mServerStatusIcon = R.drawable.ic_alert; // the most common case in the switch below
  802. switch (result.getCode()) {
  803. case OK_SSL:
  804. mServerStatusIcon = R.drawable.ic_lock_white;
  805. mServerStatusText = getResources().getString(R.string.auth_secure_connection);
  806. break;
  807. case OK_NO_SSL:
  808. case OK:
  809. if (mHostUrlInput.getText().toString().trim().toLowerCase(Locale.ROOT).startsWith(HTTP_PROTOCOL)) {
  810. mServerStatusText = getResources().getString(R.string.auth_connection_established);
  811. mServerStatusIcon = R.drawable.ic_ok;
  812. } else {
  813. mServerStatusText = getResources().getString(R.string.auth_nossl_plain_ok_title);
  814. mServerStatusIcon = R.drawable.ic_lock_open_white;
  815. }
  816. break;
  817. case NO_NETWORK_CONNECTION:
  818. mServerStatusIcon = R.drawable.no_network;
  819. mServerStatusText = getResources().getString(R.string.auth_no_net_conn_title);
  820. break;
  821. case SSL_RECOVERABLE_PEER_UNVERIFIED:
  822. mServerStatusText = getResources().getString(R.string.auth_ssl_unverified_server_title);
  823. break;
  824. case BAD_OC_VERSION:
  825. mServerStatusText = getResources().getString(R.string.auth_bad_oc_version_title);
  826. break;
  827. case WRONG_CONNECTION:
  828. mServerStatusText = getResources().getString(R.string.auth_wrong_connection_title);
  829. break;
  830. case TIMEOUT:
  831. mServerStatusText = getResources().getString(R.string.auth_timeout_title);
  832. break;
  833. case INCORRECT_ADDRESS:
  834. mServerStatusText = getResources().getString(R.string.auth_incorrect_address_title);
  835. break;
  836. case SSL_ERROR:
  837. mServerStatusText = getResources().getString(R.string.auth_ssl_general_error_title);
  838. break;
  839. case UNAUTHORIZED:
  840. mServerStatusText = getResources().getString(R.string.auth_unauthorized);
  841. break;
  842. case HOST_NOT_AVAILABLE:
  843. mServerStatusText = getResources().getString(R.string.auth_unknown_host_title);
  844. break;
  845. case INSTANCE_NOT_CONFIGURED:
  846. mServerStatusText = getResources().getString(R.string.auth_not_configured_title);
  847. break;
  848. case FILE_NOT_FOUND:
  849. mServerStatusText = getResources().getString(R.string.auth_incorrect_path_title);
  850. break;
  851. case OAUTH2_ERROR:
  852. mServerStatusText = getResources().getString(R.string.auth_oauth_error);
  853. break;
  854. case OAUTH2_ERROR_ACCESS_DENIED:
  855. mServerStatusText = getResources().getString(R.string.auth_oauth_error_access_denied);
  856. break;
  857. case UNHANDLED_HTTP_CODE:
  858. mServerStatusText = getResources().getString(R.string.auth_unknown_error_http_title);
  859. break;
  860. case UNKNOWN_ERROR:
  861. if (result.getException() != null &&
  862. !TextUtils.isEmpty(result.getException().getMessage())) {
  863. mServerStatusText = getResources().getString(
  864. R.string.auth_unknown_error_exception_title,
  865. result.getException().getMessage()
  866. );
  867. } else {
  868. mServerStatusText = getResources().getString(R.string.auth_unknown_error_title);
  869. }
  870. break;
  871. case OK_REDIRECT_TO_NON_SECURE_CONNECTION:
  872. mServerStatusIcon = R.drawable.ic_lock_open_white;
  873. mServerStatusText = getResources().getString(R.string.auth_redirect_non_secure_connection_title);
  874. break;
  875. case MAINTENANCE_MODE:
  876. mServerStatusText = getResources().getString(R.string.maintenance_mode);
  877. break;
  878. case UNTRUSTED_DOMAIN:
  879. mServerStatusText = getResources().getString(R.string.untrusted_domain);
  880. break;
  881. default:
  882. mServerStatusText = EMPTY_STRING;
  883. mServerStatusIcon = 0;
  884. break;
  885. }
  886. }
  887. /**
  888. * Chooses the right icon and text to show to the user for the received operation result.
  889. *
  890. * @param result Result of a remote operation performed in this activity
  891. */
  892. private void updateAuthStatusIconAndText(RemoteOperationResult result) {
  893. mAuthStatusIcon = R.drawable.ic_alert; // the most common case in the switch below
  894. switch (result.getCode()) {
  895. case OK_SSL:
  896. mAuthStatusIcon = R.drawable.ic_lock_white;
  897. mAuthStatusText = getResources().getString(R.string.auth_secure_connection);
  898. break;
  899. case OK_NO_SSL:
  900. case OK:
  901. if (showWebViewLoginUrl) {
  902. if (mHostUrlInput.getText().toString().trim().toLowerCase(Locale.ROOT).startsWith(HTTP_PROTOCOL)) {
  903. mAuthStatusText = getResources().getString(R.string.auth_connection_established);
  904. mAuthStatusIcon = R.drawable.ic_ok;
  905. } else {
  906. mAuthStatusText = getResources().getString(R.string.auth_nossl_plain_ok_title);
  907. mAuthStatusIcon = R.drawable.ic_lock_open_white;
  908. }
  909. }
  910. break;
  911. case NO_NETWORK_CONNECTION:
  912. mAuthStatusIcon = R.drawable.no_network;
  913. mAuthStatusText = getResources().getString(R.string.auth_no_net_conn_title);
  914. break;
  915. case SSL_RECOVERABLE_PEER_UNVERIFIED:
  916. mAuthStatusText = getResources().getString(R.string.auth_ssl_unverified_server_title);
  917. break;
  918. case TIMEOUT:
  919. mAuthStatusText = getResources().getString(R.string.auth_timeout_title);
  920. break;
  921. case HOST_NOT_AVAILABLE:
  922. mAuthStatusText = getResources().getString(R.string.auth_unknown_host_title);
  923. break;
  924. case ACCOUNT_NOT_NEW:
  925. mAuthStatusText = getString(R.string.auth_account_not_new);
  926. if (!showWebViewLoginUrl) {
  927. DisplayUtils.showErrorAndFinishActivity(this, mAuthStatusText);
  928. }
  929. break;
  930. case UNHANDLED_HTTP_CODE:
  931. default:
  932. mAuthStatusText = ErrorMessageAdapter.getErrorCauseMessage(result, null, getResources());
  933. if (!showWebViewLoginUrl) {
  934. DisplayUtils.showErrorAndFinishActivity(this, mAuthStatusText);
  935. }
  936. }
  937. }
  938. private void updateStatusIconFailUserName(int failedStatusText) {
  939. mAuthStatusIcon = R.drawable.ic_alert;
  940. mAuthStatusText = getResources().getString(failedStatusText);
  941. }
  942. /**
  943. * Processes the result of the access check performed to try the user credentials.
  944. * <p>
  945. * Creates a new account through the AccountManager.
  946. *
  947. * @param result Result of the operation.
  948. */
  949. @Override
  950. public void onAuthenticatorTaskCallback(RemoteOperationResult result) {
  951. mWaitingForOpId = Long.MAX_VALUE;
  952. dismissWaitingDialog();
  953. mAsyncTask = null;
  954. if (result.isSuccess()) {
  955. Log_OC.d(TAG, "Successful access - time to save the account");
  956. boolean success = false;
  957. if (mAction == ACTION_CREATE) {
  958. success = createAccount(result);
  959. } else {
  960. try {
  961. updateAccountAuthentication();
  962. success = true;
  963. } catch (AccountNotFoundException e) {
  964. Log_OC.e(TAG, "Account " + mAccount + " was removed!", e);
  965. DisplayUtils.showSnackMessage(findViewById(R.id.scroll), R.string.auth_account_does_not_exist);
  966. finish();
  967. }
  968. }
  969. // Reset webView
  970. webViewPassword = null;
  971. webViewUser = null;
  972. deleteCookies();
  973. if (success) {
  974. accountManager.setCurrentOwnCloudAccount(mAccount.name);
  975. if (onlyAdd) {
  976. finish();
  977. } else {
  978. Intent i = new Intent(this, FileDisplayActivity.class);
  979. i.setAction(FileDisplayActivity.RESTART);
  980. i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  981. startActivity(i);
  982. }
  983. } else {
  984. // init webView again
  985. if (mLoginWebView != null) {
  986. mLoginWebView.setVisibility(View.GONE);
  987. }
  988. setContentView(R.layout.account_setup);
  989. initOverallUi();
  990. mAuthStatusView = findViewById(R.id.auth_status_text);
  991. mHostUrlInput.setText(mServerInfo.mBaseUrl);
  992. mServerStatusView.setVisibility(View.GONE);
  993. showAuthStatus();
  994. }
  995. } else if (result.isServerFail() || result.isException()) {
  996. /// server errors or exceptions in authorization take to requiring a new check of the server
  997. mServerInfo = new GetServerInfoOperation.ServerInfo();
  998. // update status icon and text
  999. updateServerStatusIconAndText(result);
  1000. showServerStatus();
  1001. mAuthStatusIcon = 0;
  1002. mAuthStatusText = EMPTY_STRING;
  1003. // very special case (TODO: move to a common place for all the remote operations)
  1004. if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
  1005. showUntrustedCertDialog(result);
  1006. }
  1007. } else { // authorization fail due to client side - probably wrong credentials
  1008. mLoginWebView = findViewById(R.id.login_webview);
  1009. if (mLoginWebView != null) {
  1010. initWebViewLogin(mServerInfo.mBaseUrl + WEB_LOGIN, false);
  1011. DisplayUtils.showSnackMessage(this, mLoginWebView, R.string.auth_access_failed,
  1012. result.getLogMessage());
  1013. } else {
  1014. DisplayUtils.showSnackMessage(this, R.string.auth_access_failed, result.getLogMessage());
  1015. // init webView again
  1016. mLoginWebView.setVisibility(View.GONE);
  1017. updateAuthStatusIconAndText(result);
  1018. }
  1019. // reset webview
  1020. webViewPassword = null;
  1021. webViewUser = null;
  1022. deleteCookies();
  1023. Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
  1024. }
  1025. }
  1026. /**
  1027. * Updates the authentication token.
  1028. * <p>
  1029. * Sets the proper response so that the AccountAuthenticator that started this activity saves a new authorization
  1030. * token for mAccount.
  1031. * <p>
  1032. * Kills the session kept by OwnCloudClientManager so that a new one will created with the new credentials when
  1033. * needed.
  1034. */
  1035. private void updateAccountAuthentication() throws AccountNotFoundException {
  1036. Bundle response = new Bundle();
  1037. response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
  1038. response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);
  1039. response.putString(AccountManager.KEY_AUTHTOKEN, webViewPassword);
  1040. mAccountMgr.setPassword(mAccount, webViewPassword);
  1041. // remove managed clients for this account to enforce creation with fresh credentials
  1042. OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount, this);
  1043. OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(ocAccount);
  1044. setAccountAuthenticatorResult(response);
  1045. Intent intent = new Intent();
  1046. intent.putExtras(response);
  1047. setResult(RESULT_OK, intent);
  1048. }
  1049. /**
  1050. * Creates a new account through the Account Authenticator that started this activity.
  1051. * <p>
  1052. * This makes the account permanent.
  1053. * <p>
  1054. * TODO Decide how to name the OAuth accounts
  1055. */
  1056. @SuppressFBWarnings("DMI")
  1057. @SuppressLint("TrulyRandom")
  1058. protected boolean createAccount(RemoteOperationResult authResult) {
  1059. String accountType = MainApp.getAccountType(this);
  1060. // create and save new ownCloud account
  1061. String lastPermanentLocation = authResult.getLastPermanentLocation();
  1062. if (lastPermanentLocation != null) {
  1063. mServerInfo.mBaseUrl = AuthenticatorUrlUtils.trimWebdavSuffix(lastPermanentLocation);
  1064. }
  1065. Uri uri = Uri.parse(mServerInfo.mBaseUrl);
  1066. // used for authenticate on every login/network connection, determined by first login (weblogin/old login)
  1067. // can be anything: email, name, name with whitespaces
  1068. String loginName = webViewUser;
  1069. String accountName = com.owncloud.android.lib.common.accounts.AccountUtils.buildAccountName(uri, loginName);
  1070. Account newAccount = new Account(accountName, accountType);
  1071. if (accountManager.exists(newAccount)) {
  1072. // fail - not a new account, but an existing one; disallow
  1073. RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW);
  1074. updateAuthStatusIconAndText(result);
  1075. showAuthStatus();
  1076. Log_OC.d(TAG, result.getLogMessage());
  1077. return false;
  1078. } else {
  1079. mAccount = newAccount;
  1080. mAccountMgr.addAccountExplicitly(mAccount, webViewPassword, null);
  1081. // add the new account as default in preferences, if there is none already
  1082. User defaultAccount = accountManager.getUser();
  1083. if (defaultAccount.isAnonymous()) {
  1084. SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
  1085. editor.putString("select_oc_account", accountName);
  1086. editor.apply();
  1087. }
  1088. /// prepare result to return to the Authenticator
  1089. // TODO check again what the Authenticator makes with it; probably has the same
  1090. // effect as addAccountExplicitly, but it's not well done
  1091. final Intent intent = new Intent();
  1092. intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType);
  1093. intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
  1094. intent.putExtra(AccountManager.KEY_USERDATA, loginName);
  1095. /// add user data to the new account; TODO probably can be done in the last parameter
  1096. // addAccountExplicitly, or in KEY_USERDATA
  1097. mAccountMgr.setUserData(mAccount, Constants.KEY_OC_VERSION, mServerInfo.mVersion.getVersion());
  1098. mAccountMgr.setUserData(mAccount, Constants.KEY_OC_BASE_URL, mServerInfo.mBaseUrl);
  1099. ArrayList<Object> authResultData = authResult.getData();
  1100. if (authResultData == null || authResultData.size() == 0) {
  1101. Log_OC.e(this, "Could not read user data!");
  1102. return false;
  1103. }
  1104. UserInfo userInfo = (UserInfo) authResultData.get(0);
  1105. mAccountMgr.setUserData(mAccount, Constants.KEY_DISPLAY_NAME, userInfo.getDisplayName());
  1106. mAccountMgr.setUserData(mAccount, Constants.KEY_USER_ID, userInfo.getId());
  1107. mAccountMgr.setUserData(mAccount,
  1108. Constants.KEY_OC_ACCOUNT_VERSION,
  1109. Integer.toString(UserAccountManager.ACCOUNT_VERSION_WITH_PROPER_ID));
  1110. setAccountAuthenticatorResult(intent.getExtras());
  1111. setResult(RESULT_OK, intent);
  1112. // notify Document Provider
  1113. if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
  1114. String authority = getResources().getString(R.string.document_provider_authority);
  1115. Uri rootsUri = DocumentsContract.buildRootsUri(authority);
  1116. getContentResolver().notifyChange(rootsUri, null);
  1117. }
  1118. return true;
  1119. }
  1120. }
  1121. public void onScan() {
  1122. if (PermissionUtil.checkSelfPermission(this, Manifest.permission.CAMERA)) {
  1123. startQRScanner();
  1124. } else {
  1125. PermissionUtil.requestCameraPermission(this);
  1126. }
  1127. }
  1128. private void startQRScanner() {
  1129. Intent intent = new Intent(this, QrCodeActivity.class);
  1130. startActivityForResult(intent, REQUEST_CODE_QR_SCAN);
  1131. }
  1132. @Override
  1133. public void onRequestPermissionsResult(int requestCode,
  1134. @NonNull String[] permissions,
  1135. @NonNull int[] grantResults) {
  1136. if (requestCode == PermissionUtil.PERMISSIONS_CAMERA) {// If request is cancelled, result arrays are empty.
  1137. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  1138. // permission was granted
  1139. startQRScanner();
  1140. }
  1141. } else {
  1142. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  1143. }
  1144. }
  1145. /**
  1146. * /** Updates the content and visibility state of the icon and text associated to the last check on the ownCloud
  1147. * server.
  1148. */
  1149. private void showServerStatus() {
  1150. if (mServerStatusIcon == NO_ICON && EMPTY_STRING.equals(mServerStatusText)) {
  1151. mServerStatusView.setVisibility(View.INVISIBLE);
  1152. } else {
  1153. mServerStatusView.setText(mServerStatusText);
  1154. mServerStatusView.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon, 0, 0, 0);
  1155. mServerStatusView.setVisibility(View.VISIBLE);
  1156. }
  1157. }
  1158. /**
  1159. * Updates the content and visibility state of the icon and text associated to the interactions with the OAuth
  1160. * authorization server.
  1161. */
  1162. private void showAuthStatus() {
  1163. if (mAuthStatusView != null) {
  1164. if (mAuthStatusIcon == NO_ICON && EMPTY_STRING.equals(mAuthStatusText)) {
  1165. mAuthStatusView.setVisibility(View.INVISIBLE);
  1166. } else {
  1167. mAuthStatusView.setText(mAuthStatusText);
  1168. mAuthStatusView.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon, 0, 0, 0);
  1169. mAuthStatusView.setVisibility(View.VISIBLE);
  1170. }
  1171. }
  1172. }
  1173. /**
  1174. * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
  1175. * <p>
  1176. * Used to trigger the authentication check when the user presses 'enter' after writing the password, or to throw
  1177. * the server test when the only field on screen is the URL input field.
  1178. */
  1179. @Override
  1180. public boolean onEditorAction(TextView inputField, int actionId, KeyEvent event) {
  1181. if ((actionId == EditorInfo.IME_ACTION_NEXT || actionId == EditorInfo.IME_NULL)
  1182. && inputField != null && inputField.equals(mHostUrlInput)) {
  1183. checkOcServer();
  1184. }
  1185. return false; // always return false to grant that the software keyboard is hidden anyway
  1186. }
  1187. /**
  1188. * Show untrusted cert dialog
  1189. */
  1190. public void showUntrustedCertDialog(X509Certificate x509Certificate, SslError error, SslErrorHandler handler) {
  1191. // Show a dialog with the certificate info
  1192. SslUntrustedCertDialog dialog;
  1193. if (x509Certificate == null) {
  1194. dialog = SslUntrustedCertDialog.newInstanceForEmptySslError(error, handler);
  1195. } else {
  1196. dialog = SslUntrustedCertDialog.newInstanceForFullSslError(x509Certificate, error, handler);
  1197. }
  1198. FragmentManager fm = getSupportFragmentManager();
  1199. FragmentTransaction ft = fm.beginTransaction();
  1200. ft.addToBackStack(null);
  1201. dialog.show(ft, UNTRUSTED_CERT_DIALOG_TAG);
  1202. }
  1203. /**
  1204. * Show untrusted cert dialog
  1205. */
  1206. private void showUntrustedCertDialog(RemoteOperationResult result) {
  1207. // Show a dialog with the certificate info
  1208. SslUntrustedCertDialog dialog = SslUntrustedCertDialog.
  1209. newInstanceForFullSslError((CertificateCombinedException) result.getException());
  1210. FragmentManager fm = getSupportFragmentManager();
  1211. FragmentTransaction ft = fm.beginTransaction();
  1212. ft.addToBackStack(null);
  1213. dialog.show(ft, UNTRUSTED_CERT_DIALOG_TAG);
  1214. }
  1215. private void doOnResumeAndBound() {
  1216. mOperationsServiceBinder.addOperationListener(this, mHandler);
  1217. if (mWaitingForOpId <= Integer.MAX_VALUE) {
  1218. mOperationsServiceBinder.dispatchResultIfFinished((int) mWaitingForOpId, this);
  1219. }
  1220. }
  1221. private void dismissWaitingDialog() {
  1222. Fragment frag = getSupportFragmentManager().findFragmentByTag(WAIT_DIALOG_TAG);
  1223. if (frag instanceof DialogFragment) {
  1224. DialogFragment dialog = (DialogFragment) frag;
  1225. try {
  1226. dialog.dismiss();
  1227. } catch (IllegalStateException e) {
  1228. Log_OC.e(TAG, e.getMessage());
  1229. dialog.dismissAllowingStateLoss();
  1230. }
  1231. }
  1232. }
  1233. /**
  1234. * Implements callback methods for service binding.
  1235. */
  1236. private class OperationsServiceConnection implements ServiceConnection {
  1237. @Override
  1238. public void onServiceConnected(ComponentName component, IBinder service) {
  1239. if (component.equals(
  1240. new ComponentName(AuthenticatorActivity.this, OperationsService.class)
  1241. )) {
  1242. mOperationsServiceBinder = (OperationsServiceBinder) service;
  1243. Uri data = getIntent().getData();
  1244. if (data != null && data.toString().startsWith(getString(R.string.login_data_own_scheme))) {
  1245. String prefix = getString(R.string.login_data_own_scheme) + PROTOCOL_SUFFIX + "login/";
  1246. LoginUrlInfo loginUrlInfo = parseLoginDataUrl(prefix, data.toString());
  1247. try {
  1248. mServerInfo.mBaseUrl = AuthenticatorUrlUtils.normalizeUrlSuffix(loginUrlInfo.serverAddress);
  1249. webViewUser = loginUrlInfo.username;
  1250. webViewPassword = loginUrlInfo.password;
  1251. doOnResumeAndBound();
  1252. checkOcServer();
  1253. } catch (Exception e) {
  1254. mServerStatusIcon = R.drawable.ic_alert;
  1255. mServerStatusText = getString(R.string.qr_could_not_be_read);
  1256. showServerStatus();
  1257. }
  1258. } else {
  1259. doOnResumeAndBound();
  1260. }
  1261. }
  1262. }
  1263. @Override
  1264. public void onServiceDisconnected(ComponentName component) {
  1265. if (component.equals(
  1266. new ComponentName(AuthenticatorActivity.this, OperationsService.class)
  1267. )) {
  1268. Log_OC.e(TAG, "Operations service crashed");
  1269. mOperationsServiceBinder = null;
  1270. }
  1271. }
  1272. }
  1273. /**
  1274. * For retrieving the clicking on authentication cancel button.
  1275. */
  1276. public void doNegativeAuthenticationDialogClick() {
  1277. mIsFirstAuthAttempt = true;
  1278. }
  1279. @Override
  1280. protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
  1281. super.onActivityResult(requestCode, resultCode, data);
  1282. if (requestCode == REQUEST_CODE_QR_SCAN) {
  1283. if (data == null) {
  1284. return;
  1285. }
  1286. String result = data.getStringExtra("com.blikoon.qrcodescanner.got_qr_scan_relult");
  1287. if (result == null || !result.startsWith(getString(R.string.login_data_own_scheme))) {
  1288. mServerStatusIcon = R.drawable.ic_alert;
  1289. mServerStatusText = "QR Code could not be read!";
  1290. showServerStatus();
  1291. return;
  1292. }
  1293. if (!getResources().getBoolean(R.bool.multiaccount_support) &&
  1294. accountManager.getAccounts().length == 1) {
  1295. Toast.makeText(this, R.string.no_mutliple_accounts_allowed, Toast.LENGTH_LONG).show();
  1296. } else {
  1297. parseAndLoginFromWebView(result);
  1298. }
  1299. }
  1300. }
  1301. /**
  1302. * Obtain the X509Certificate from SslError
  1303. *
  1304. * @param error SslError
  1305. * @return X509Certificate from error
  1306. */
  1307. public static X509Certificate getX509CertificateFromError(SslError error) {
  1308. Bundle bundle = SslCertificate.saveState(error.getCertificate());
  1309. X509Certificate x509Certificate;
  1310. byte[] bytes = bundle.getByteArray("x509-certificate");
  1311. if (bytes == null) {
  1312. x509Certificate = null;
  1313. } else {
  1314. try {
  1315. CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
  1316. Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
  1317. x509Certificate = (X509Certificate) cert;
  1318. } catch (CertificateException e) {
  1319. x509Certificate = null;
  1320. }
  1321. }
  1322. return x509Certificate;
  1323. }
  1324. /**
  1325. * Called from SslValidatorDialog when a new server certificate was correctly saved.
  1326. */
  1327. public void onSavedCertificate() {
  1328. checkOcServer();
  1329. }
  1330. /**
  1331. * Called from SslValidatorDialog when a new server certificate could not be saved when the user requested it.
  1332. */
  1333. @Override
  1334. public void onFailedSavingCertificate() {
  1335. DisplayUtils.showSnackMessage(this, R.string.ssl_validator_not_saved);
  1336. }
  1337. }