AuthenticatorActivity.java 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121
  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.Rect;
  54. import android.graphics.drawable.Drawable;
  55. import android.net.Uri;
  56. import android.net.http.SslCertificate;
  57. import android.net.http.SslError;
  58. import android.os.Build;
  59. import android.os.Bundle;
  60. import android.os.Handler;
  61. import android.os.IBinder;
  62. import android.preference.PreferenceManager;
  63. import android.text.Editable;
  64. import android.text.InputType;
  65. import android.text.TextUtils;
  66. import android.text.TextWatcher;
  67. import android.util.AndroidRuntimeException;
  68. import android.view.KeyEvent;
  69. import android.view.MotionEvent;
  70. import android.view.View;
  71. import android.view.View.OnFocusChangeListener;
  72. import android.view.View.OnTouchListener;
  73. import android.view.inputmethod.EditorInfo;
  74. import android.webkit.CookieManager;
  75. import android.webkit.CookieSyncManager;
  76. import android.webkit.HttpAuthHandler;
  77. import android.webkit.SslErrorHandler;
  78. import android.webkit.WebResourceRequest;
  79. import android.webkit.WebResourceResponse;
  80. import android.webkit.WebView;
  81. import android.webkit.WebViewClient;
  82. import android.widget.EditText;
  83. import android.widget.ImageButton;
  84. import android.widget.ImageView;
  85. import android.widget.ProgressBar;
  86. import android.widget.TextView;
  87. import android.widget.TextView.OnEditorActionListener;
  88. import android.widget.Toast;
  89. import com.blikoon.qrcodescanner.QrCodeActivity;
  90. import com.google.android.material.snackbar.Snackbar;
  91. import com.nextcloud.client.account.UserAccountManager;
  92. import com.nextcloud.client.device.DeviceInfo;
  93. import com.nextcloud.client.di.Injectable;
  94. import com.nextcloud.client.onboarding.FirstRunActivity;
  95. import com.nextcloud.client.onboarding.OnboardingService;
  96. import com.nextcloud.client.preferences.AppPreferences;
  97. import com.owncloud.android.MainApp;
  98. import com.owncloud.android.R;
  99. import com.owncloud.android.lib.common.OwnCloudAccount;
  100. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  101. import com.owncloud.android.lib.common.OwnCloudCredentials;
  102. import com.owncloud.android.lib.common.OwnCloudCredentialsFactory;
  103. import com.owncloud.android.lib.common.UserInfo;
  104. import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;
  105. import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;
  106. import com.owncloud.android.lib.common.network.CertificateCombinedException;
  107. import com.owncloud.android.lib.common.network.NetworkUtils;
  108. import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
  109. import com.owncloud.android.lib.common.operations.RemoteOperation;
  110. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  111. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  112. import com.owncloud.android.lib.common.utils.Log_OC;
  113. import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  114. import com.owncloud.android.lib.resources.users.GetUserInfoRemoteOperation;
  115. import com.owncloud.android.operations.DetectAuthenticationMethodOperation.AuthenticationMethod;
  116. import com.owncloud.android.operations.GetServerInfoOperation;
  117. import com.owncloud.android.services.OperationsService;
  118. import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
  119. import com.owncloud.android.ui.activity.FileDisplayActivity;
  120. import com.owncloud.android.ui.dialog.CredentialsDialogFragment;
  121. import com.owncloud.android.ui.dialog.IndeterminateProgressDialog;
  122. import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
  123. import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;
  124. import com.owncloud.android.utils.DisplayUtils;
  125. import com.owncloud.android.utils.ErrorMessageAdapter;
  126. import com.owncloud.android.utils.PermissionUtil;
  127. import java.io.ByteArrayInputStream;
  128. import java.io.InputStream;
  129. import java.net.URLDecoder;
  130. import java.security.cert.Certificate;
  131. import java.security.cert.CertificateException;
  132. import java.security.cert.CertificateFactory;
  133. import java.security.cert.X509Certificate;
  134. import java.util.ArrayList;
  135. import java.util.HashMap;
  136. import java.util.Locale;
  137. import java.util.Map;
  138. import javax.inject.Inject;
  139. import androidx.annotation.NonNull;
  140. import androidx.annotation.Nullable;
  141. import androidx.fragment.app.DialogFragment;
  142. import androidx.fragment.app.Fragment;
  143. import androidx.fragment.app.FragmentManager;
  144. import androidx.fragment.app.FragmentTransaction;
  145. import de.cotech.hw.fido.WebViewFidoBridge;
  146. import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
  147. /**
  148. * This Activity is used to add an ownCloud account to the App
  149. */
  150. public class AuthenticatorActivity extends AccountAuthenticatorActivity
  151. implements OnRemoteOperationListener, OnFocusChangeListener, OnEditorActionListener, OnSslUntrustedCertListener,
  152. AuthenticatorAsyncTask.OnAuthenticatorTaskListener, Injectable {
  153. private static final String TAG = AuthenticatorActivity.class.getSimpleName();
  154. public static final String EXTRA_ACTION = "ACTION";
  155. public static final String EXTRA_ACCOUNT = "ACCOUNT";
  156. public static final String EXTRA_USE_PROVIDER_AS_WEBLOGIN = "USE_PROVIDER_AS_WEBLOGIN";
  157. private static final String KEY_HOST_URL_TEXT = "HOST_URL_TEXT";
  158. private static final String KEY_OC_VERSION = "OC_VERSION";
  159. private static final String KEY_SERVER_VALID = "SERVER_VALID";
  160. private static final String KEY_SERVER_CHECKED = "SERVER_CHECKED";
  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_PASSWORD_EXPOSED = "PASSWORD_VISIBLE";
  165. private static final String KEY_AUTH_STATUS_TEXT = "AUTH_STATUS_TEXT";
  166. private static final String KEY_AUTH_STATUS_ICON = "AUTH_STATUS_ICON";
  167. private static final String KEY_SERVER_AUTH_METHOD = "SERVER_AUTH_METHOD";
  168. private static final String KEY_WAITING_FOR_OP_ID = "WAITING_FOR_OP_ID";
  169. private static final String KEY_AUTH_TOKEN = "AUTH_TOKEN";
  170. public static final byte ACTION_CREATE = 0;
  171. public static final byte ACTION_UPDATE_EXPIRED_TOKEN = 2; // detected by the app
  172. private static final String UNTRUSTED_CERT_DIALOG_TAG = "UNTRUSTED_CERT_DIALOG";
  173. private static final String WAIT_DIALOG_TAG = "WAIT_DIALOG";
  174. private static final String CREDENTIALS_DIALOG_TAG = "CREDENTIALS_DIALOG";
  175. private static final String KEY_AUTH_IS_FIRST_ATTEMPT_TAG = "KEY_AUTH_IS_FIRST_ATTEMPT";
  176. private static final String KEY_USERNAME = "USERNAME";
  177. private static final String KEY_PASSWORD = "PASSWORD";
  178. private static final String KEY_ASYNC_TASK_IN_PROGRESS = "AUTH_IN_PROGRESS";
  179. public static final String WEB_LOGIN = "/index.php/login/flow";
  180. public static final String PROTOCOL_SUFFIX = "://";
  181. public static final String LOGIN_URL_DATA_KEY_VALUE_SEPARATOR = ":";
  182. public static final String HTTPS_PROTOCOL = "https://";
  183. public static final String HTTP_PROTOCOL = "http://";
  184. public static final int NO_ICON = 0;
  185. public static final String EMPTY_STRING = "";
  186. private static final int REQUEST_CODE_QR_SCAN = 101;
  187. public static final int REQUEST_CODE_FIRST_RUN = 102;
  188. /// parameters from EXTRAs in starter Intent
  189. private byte mAction;
  190. private Account mAccount;
  191. /// activity-level references / state
  192. private final Handler mHandler = new Handler();
  193. private ServiceConnection mOperationsServiceConnection;
  194. private OperationsServiceBinder mOperationsServiceBinder;
  195. private AccountManager mAccountMgr;
  196. /// Server PRE-Fragment elements
  197. private EditText mHostUrlInput;
  198. private View mRefreshButton;
  199. private TextView mServerStatusView;
  200. private ImageView scanQR;
  201. private TextWatcher mHostUrlInputWatcher;
  202. private String mServerStatusText = EMPTY_STRING;
  203. private int mServerStatusIcon;
  204. private boolean mServerIsChecked;
  205. private boolean mServerIsValid;
  206. private GetServerInfoOperation.ServerInfo mServerInfo = new GetServerInfoOperation.ServerInfo();
  207. /// Authentication PRE-Fragment elements
  208. private EditText mUsernameInput;
  209. private EditText mPasswordInput;
  210. private View mOkButton;
  211. private TextView mAuthStatusView;
  212. private ImageButton mTestServerButton;
  213. private WebView mLoginWebView;
  214. private WebViewFidoBridge webViewFidoBridge;
  215. private String mAuthStatusText = EMPTY_STRING;
  216. private int mAuthStatusIcon;
  217. private String mAuthToken = EMPTY_STRING;
  218. private AuthenticatorAsyncTask mAsyncTask;
  219. private boolean mIsFirstAuthAttempt;
  220. /// Identifier of operation in progress which result shouldn't be lost
  221. private long mWaitingForOpId = Long.MAX_VALUE;
  222. private boolean webViewLoginMethod;
  223. private String webViewUser;
  224. private String webViewPassword;
  225. private boolean forceOldLoginMethod;
  226. @Inject UserAccountManager accountManager;
  227. @Inject AppPreferences preferences;
  228. @Inject OnboardingService onboarding;
  229. @Inject DeviceInfo deviceInfo;
  230. /**
  231. * {@inheritDoc}
  232. *
  233. * IMPORTANT ENTRY POINT 1: activity is shown to the user
  234. */
  235. @Override
  236. protected void onCreate(Bundle savedInstanceState) {
  237. //Log_OC.e(TAG, "onCreate init");
  238. super.onCreate(savedInstanceState);
  239. Uri data = getIntent().getData();
  240. boolean directLogin = data != null && data.toString().startsWith(getString(R.string.login_data_own_scheme));
  241. if (savedInstanceState == null && !directLogin) {
  242. onboarding.launchFirstRunIfNeeded(this);
  243. }
  244. // delete cookies for webView
  245. deleteCookies();
  246. // Workaround, for fixing a problem with Android Library Support v7 19
  247. //getWindow().requestFeature(Window.FEATURE_NO_TITLE);
  248. if (getSupportActionBar() != null) {
  249. getSupportActionBar().hide();
  250. getSupportActionBar().setDisplayHomeAsUpEnabled(false);
  251. getSupportActionBar().setDisplayShowHomeEnabled(false);
  252. getSupportActionBar().setDisplayShowTitleEnabled(false);
  253. }
  254. mIsFirstAuthAttempt = true;
  255. /// init activity state
  256. mAccountMgr = AccountManager.get(this);
  257. /// get input values
  258. mAction = getIntent().getByteExtra(EXTRA_ACTION, ACTION_CREATE);
  259. Bundle extras = getIntent().getExtras();
  260. if (extras != null) {
  261. mAccount = extras.getParcelable(EXTRA_ACCOUNT);
  262. }
  263. if (savedInstanceState != null) {
  264. mWaitingForOpId = savedInstanceState.getLong(KEY_WAITING_FOR_OP_ID);
  265. mIsFirstAuthAttempt = savedInstanceState.getBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG);
  266. }
  267. String webloginUrl = null;
  268. boolean showLegacyLogin;
  269. if (getIntent().getBooleanExtra(EXTRA_USE_PROVIDER_AS_WEBLOGIN, false)) {
  270. webViewLoginMethod = true;
  271. webloginUrl = getString(R.string.provider_registration_server);
  272. showLegacyLogin = false;
  273. } else {
  274. webViewLoginMethod = !TextUtils.isEmpty(getResources().getString(R.string.webview_login_url));
  275. showLegacyLogin = true;
  276. }
  277. if (webViewLoginMethod) {
  278. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  279. }
  280. /// load user interface
  281. if (!webViewLoginMethod) {
  282. setContentView(R.layout.account_setup);
  283. /// initialize general UI elements
  284. initOverallUi();
  285. findViewById(R.id.centeredRefreshButton).setOnClickListener(v -> checkOcServer());
  286. findViewById(R.id.embeddedRefreshButton).setOnClickListener(v -> checkOcServer());
  287. /// initialize block to be moved to single Fragment to check server and get info about it
  288. /// initialize block to be moved to single Fragment to retrieve and validate credentials
  289. initAuthorizationPreFragment(savedInstanceState);
  290. } else {
  291. setContentView(R.layout.account_setup_webview);
  292. mLoginWebView = findViewById(R.id.login_webview);
  293. initWebViewLogin(webloginUrl, showLegacyLogin, false);
  294. }
  295. initServerPreFragment(savedInstanceState);
  296. }
  297. private void deleteCookies() {
  298. try {
  299. CookieSyncManager.createInstance(this);
  300. CookieManager cookieManager = CookieManager.getInstance();
  301. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  302. cookieManager.removeAllCookies(null);
  303. } else {
  304. cookieManager.removeAllCookie();
  305. }
  306. } catch (AndroidRuntimeException e) {
  307. Log_OC.e(TAG, e.getMessage());
  308. }
  309. }
  310. private static String getWebLoginUserAgent() {
  311. return Build.MANUFACTURER.substring(0, 1).toUpperCase(Locale.getDefault()) +
  312. Build.MANUFACTURER.substring(1).toLowerCase(Locale.getDefault()) + " " + Build.MODEL + " (Android)";
  313. }
  314. @SuppressLint("SetJavaScriptEnabled")
  315. private void initWebViewLogin(String baseURL, boolean showLegacyLogin, boolean useGenericUserAgent) {
  316. mLoginWebView.setVisibility(View.GONE);
  317. final ProgressBar progressBar = findViewById(R.id.login_webview_progress_bar);
  318. mLoginWebView.getSettings().setAllowFileAccess(false);
  319. mLoginWebView.getSettings().setJavaScriptEnabled(true);
  320. mLoginWebView.getSettings().setDomStorageEnabled(true);
  321. if (useGenericUserAgent) {
  322. mLoginWebView.getSettings().setUserAgentString(MainApp.getUserAgent());
  323. } else {
  324. mLoginWebView.getSettings().setUserAgentString(getWebLoginUserAgent());
  325. }
  326. mLoginWebView.getSettings().setSaveFormData(false);
  327. mLoginWebView.getSettings().setSavePassword(false);
  328. webViewFidoBridge = WebViewFidoBridge.createInstanceForWebView(this, mLoginWebView);
  329. Map<String, String> headers = new HashMap<>();
  330. headers.put(RemoteOperation.OCS_API_HEADER, RemoteOperation.OCS_API_HEADER_VALUE);
  331. String url;
  332. if (baseURL != null && !baseURL.isEmpty()) {
  333. url = baseURL;
  334. } else {
  335. url = getResources().getString(R.string.webview_login_url);
  336. }
  337. mLoginWebView.loadUrl(url, headers);
  338. setClient(progressBar);
  339. // show snackbar after 60s to switch back to old login method
  340. if (showLegacyLogin) {
  341. final String finalBaseURL = baseURL;
  342. new Handler().postDelayed(() -> DisplayUtils.createSnackbar(mLoginWebView,
  343. R.string.fallback_weblogin_text,
  344. Snackbar.LENGTH_INDEFINITE)
  345. .setActionTextColor(getResources().getColor(R.color.white))
  346. .setAction(R.string.fallback_weblogin_back, v -> {
  347. mLoginWebView.setVisibility(View.INVISIBLE);
  348. webViewLoginMethod = false;
  349. setContentView(R.layout.account_setup);
  350. // initialize general UI elements
  351. initOverallUi();
  352. mPasswordInput.setVisibility(View.VISIBLE);
  353. mUsernameInput.setVisibility(View.VISIBLE);
  354. mUsernameInput.requestFocus();
  355. mAuthStatusView.setVisibility(View.INVISIBLE);
  356. mServerStatusView.setVisibility(View.INVISIBLE);
  357. mTestServerButton.setVisibility(View.INVISIBLE);
  358. forceOldLoginMethod = true;
  359. mOkButton.setVisibility(View.VISIBLE);
  360. initServerPreFragment(null);
  361. if (finalBaseURL != null) {
  362. mHostUrlInput.setText(finalBaseURL.replace(WEB_LOGIN, ""));
  363. } else {
  364. mHostUrlInput.setText(finalBaseURL);
  365. }
  366. checkOcServer();
  367. }).show(), 60 * 1000);
  368. }
  369. }
  370. @Override
  371. public boolean onKeyDown(int keyCode, KeyEvent event) {
  372. if (mLoginWebView != null && event.getAction() == KeyEvent.ACTION_DOWN) {
  373. switch (keyCode) {
  374. case KeyEvent.KEYCODE_BACK:
  375. if (mLoginWebView.canGoBack()) {
  376. mLoginWebView.goBack();
  377. } else {
  378. finish();
  379. }
  380. return true;
  381. }
  382. }
  383. return super.onKeyDown(keyCode, event);
  384. }
  385. private void setClient(ProgressBar progressBar) {
  386. mLoginWebView.setWebViewClient(new WebViewClient() {
  387. @Override
  388. public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
  389. webViewFidoBridge.delegateShouldInterceptRequest(view, request);
  390. return super.shouldInterceptRequest(view, request);
  391. }
  392. @Override
  393. public void onPageStarted(WebView view, String url, Bitmap favicon) {
  394. super.onPageStarted(view, url, favicon);
  395. webViewFidoBridge.delegateOnPageStarted(view, url, favicon);
  396. }
  397. @Override
  398. public boolean shouldOverrideUrlLoading(WebView view, String url) {
  399. if (url.startsWith(getString(R.string.login_data_own_scheme) + PROTOCOL_SUFFIX + "login/")) {
  400. parseAndLoginFromWebView(url);
  401. return true;
  402. }
  403. return false;
  404. }
  405. @Override
  406. public void onPageFinished(WebView view, String url) {
  407. super.onPageFinished(view, url);
  408. progressBar.setVisibility(View.GONE);
  409. mLoginWebView.setVisibility(View.VISIBLE);
  410. }
  411. @Override
  412. public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
  413. X509Certificate cert = getX509CertificateFromError(error);
  414. try {
  415. if (cert != null && NetworkUtils.isCertInKnownServersStore(cert, getApplicationContext())) {
  416. handler.proceed();
  417. } else {
  418. showUntrustedCertDialog(cert, error, handler);
  419. }
  420. } catch (Exception e) {
  421. Log_OC.e(TAG, "Cert could not be verified");
  422. }
  423. }
  424. public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
  425. progressBar.setVisibility(View.GONE);
  426. mLoginWebView.setVisibility(View.VISIBLE);
  427. InputStream resources = getResources().openRawResource(R.raw.custom_error);
  428. String customError = DisplayUtils.getData(resources);
  429. if (!customError.isEmpty()) {
  430. mLoginWebView.loadData(customError, "text/html; charset=UTF-8", null);
  431. }
  432. }
  433. });
  434. }
  435. private void parseAndLoginFromWebView(String dataString) {
  436. String prefix = getString(R.string.login_data_own_scheme) + PROTOCOL_SUFFIX + "login/";
  437. LoginUrlInfo loginUrlInfo = parseLoginDataUrl(prefix, dataString);
  438. if (loginUrlInfo != null) {
  439. try {
  440. if (mHostUrlInput != null) {
  441. mHostUrlInput.setText("");
  442. }
  443. mServerInfo.mBaseUrl = AuthenticatorUrlUtils.normalizeUrlSuffix(loginUrlInfo.serverAddress);
  444. webViewUser = loginUrlInfo.username;
  445. webViewPassword = loginUrlInfo.password;
  446. } catch (Exception e) {
  447. mServerStatusIcon = R.drawable.ic_alert;
  448. mServerStatusText = "QR Code could not be read!";
  449. showServerStatus();
  450. }
  451. checkOcServer();
  452. }
  453. }
  454. private void populateLoginFields(String dataString) throws IllegalArgumentException {
  455. // check if it is cloud://login/
  456. if (dataString.startsWith(getString(R.string.login_data_own_scheme) + PROTOCOL_SUFFIX + "login/")) {
  457. String prefix = getString(R.string.login_data_own_scheme) + PROTOCOL_SUFFIX + "login/";
  458. LoginUrlInfo loginUrlInfo = parseLoginDataUrl(prefix, dataString);
  459. if (loginUrlInfo != null) {
  460. mHostUrlInput.setText(loginUrlInfo.serverAddress);
  461. mUsernameInput.setText(loginUrlInfo.username);
  462. mPasswordInput.setText(loginUrlInfo.password);
  463. if (loginUrlInfo.serverAddress != null && !mServerIsChecked) {
  464. onUrlInputFocusLost();
  465. }
  466. }
  467. }
  468. }
  469. /**
  470. * parses a URI string and returns a login data object with the information from the URI string.
  471. *
  472. * @param prefix URI beginning, e.g. cloud://login/
  473. * @param dataString the complete URI
  474. * @return login data
  475. * @throws IllegalArgumentException when
  476. */
  477. public static LoginUrlInfo parseLoginDataUrl(String prefix, String dataString) throws IllegalArgumentException {
  478. if (dataString.length() < prefix.length()) {
  479. throw new IllegalArgumentException("Invalid login URL detected");
  480. }
  481. // format is basically xxx://login/server:xxx&user:xxx&password while all variables are optional
  482. String data = dataString.substring(prefix.length());
  483. // parse data
  484. String[] values = data.split("&");
  485. if (values.length < 1 || values.length > 3) {
  486. // error illegal number of URL elements detected
  487. throw new IllegalArgumentException("Illegal number of login URL elements detected: " + values.length);
  488. }
  489. LoginUrlInfo loginUrlInfo = new LoginUrlInfo();
  490. for (String value : values) {
  491. if (value.startsWith("user" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR)) {
  492. loginUrlInfo.username = URLDecoder.decode(
  493. value.substring(("user" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR).length()));
  494. } else if (value.startsWith("password" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR)) {
  495. loginUrlInfo.password = URLDecoder.decode(
  496. value.substring(("password" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR).length()));
  497. } else if (value.startsWith("server" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR)) {
  498. loginUrlInfo.serverAddress = URLDecoder.decode(
  499. value.substring(("server" + LOGIN_URL_DATA_KEY_VALUE_SEPARATOR).length()));
  500. }
  501. }
  502. return loginUrlInfo;
  503. }
  504. /**
  505. * Configures elements in the user interface under direct control of the Activity.
  506. */
  507. private void initOverallUi() {
  508. mHostUrlInput = findViewById(R.id.hostUrlInput);
  509. mPasswordInput = findViewById(R.id.account_password);
  510. mUsernameInput = findViewById(R.id.account_username);
  511. mAuthStatusView = findViewById(R.id.auth_status_text);
  512. mServerStatusView = findViewById(R.id.server_status_text);
  513. mTestServerButton = findViewById(R.id.testServerButton);
  514. mOkButton = findViewById(R.id.buttonOK);
  515. mOkButton.setOnClickListener(v -> onOkClick());
  516. scanQR = findViewById(R.id.scanQR);
  517. if (deviceInfo.hasCamera(this)) {
  518. scanQR.setOnClickListener(v -> onScan());
  519. } else {
  520. scanQR.setVisibility(View.GONE);
  521. }
  522. setupInstructionMessage();
  523. mTestServerButton.setVisibility(mAction == ACTION_CREATE ? View.VISIBLE : View.GONE);
  524. }
  525. private void setupInstructionMessage() {
  526. TextView instructionsView = findViewById(R.id.instructions_message);
  527. if (mAction == ACTION_UPDATE_EXPIRED_TOKEN) {
  528. instructionsView.setVisibility(View.VISIBLE);
  529. String instructionsMessageText = getString(R.string.auth_expired_basic_auth_toast);
  530. instructionsView.setText(instructionsMessageText);
  531. } else {
  532. instructionsView.setVisibility(View.GONE);
  533. }
  534. }
  535. public void onTestServerConnectionClick(View v) {
  536. checkOcServer();
  537. }
  538. /**
  539. * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
  540. */
  541. private void initServerPreFragment(Bundle savedInstanceState) {
  542. /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
  543. boolean isUrlInputAllowed = getResources().getBoolean(R.bool.show_server_url_input);
  544. if (savedInstanceState == null) {
  545. if (mAccount != null) {
  546. String baseUrl = mAccountMgr.getUserData(mAccount, Constants.KEY_OC_BASE_URL);
  547. if (TextUtils.isEmpty(baseUrl)) {
  548. mServerInfo.mBaseUrl = "";
  549. } else {
  550. mServerInfo.mBaseUrl = baseUrl;
  551. }
  552. // TODO do next in a setter for mBaseUrl
  553. mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith(HTTPS_PROTOCOL);
  554. mServerInfo.mVersion = accountManager.getServerVersion(mAccount);
  555. } else {
  556. if (!webViewLoginMethod) {
  557. mServerInfo.mBaseUrl = getString(R.string.server_url).trim();
  558. } else {
  559. mServerInfo.mBaseUrl = getString(R.string.webview_login_url).trim();
  560. }
  561. mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith(HTTPS_PROTOCOL);
  562. }
  563. } else {
  564. mServerStatusText = savedInstanceState.getString(KEY_SERVER_STATUS_TEXT);
  565. mServerStatusIcon = savedInstanceState.getInt(KEY_SERVER_STATUS_ICON);
  566. mServerIsValid = savedInstanceState.getBoolean(KEY_SERVER_VALID);
  567. mServerIsChecked = savedInstanceState.getBoolean(KEY_SERVER_CHECKED);
  568. // TODO parcelable
  569. mServerInfo.mIsSslConn = savedInstanceState.getBoolean(KEY_IS_SSL_CONN);
  570. mServerInfo.mBaseUrl = savedInstanceState.getString(KEY_HOST_URL_TEXT);
  571. String ocVersion = savedInstanceState.getString(KEY_OC_VERSION);
  572. if (ocVersion != null) {
  573. mServerInfo.mVersion = new OwnCloudVersion(ocVersion);
  574. }
  575. mServerInfo.mAuthMethod = AuthenticationMethod.valueOf(
  576. savedInstanceState.getString(KEY_SERVER_AUTH_METHOD));
  577. }
  578. if (!webViewLoginMethod) {
  579. /// step 2 - set properties of UI elements (text, visibility, enabled...)
  580. mHostUrlInput = findViewById(R.id.hostUrlInput);
  581. // Convert IDN to Unicode
  582. mHostUrlInput.setText(DisplayUtils.convertIdn(mServerInfo.mBaseUrl, false));
  583. if (mAction != ACTION_CREATE) {
  584. /// lock things that should not change
  585. mHostUrlInput.setEnabled(false);
  586. mHostUrlInput.setFocusable(false);
  587. }
  588. if (isUrlInputAllowed) {
  589. mRefreshButton = findViewById(R.id.embeddedRefreshButton);
  590. } else {
  591. findViewById(R.id.hostUrlFrame).setVisibility(View.GONE);
  592. mRefreshButton = findViewById(R.id.centeredRefreshButton);
  593. }
  594. showRefreshButton(mServerIsChecked && !mServerIsValid &&
  595. mWaitingForOpId > Integer.MAX_VALUE);
  596. mServerStatusView = findViewById(R.id.server_status_text);
  597. showServerStatus();
  598. /// step 3 - bind some listeners and options
  599. mHostUrlInput.setImeOptions(EditorInfo.IME_ACTION_NEXT);
  600. mHostUrlInput.setOnEditorActionListener(this);
  601. /// step 4 - create listeners that will be bound at onResume
  602. mHostUrlInputWatcher = new TextWatcher() {
  603. @Override
  604. public void afterTextChanged(Editable s) {
  605. if (mOkButton.isEnabled() &&
  606. !mServerInfo.mBaseUrl.equals(
  607. AuthenticatorUrlUtils.normalizeUrl(s.toString(), mServerInfo.mIsSslConn))) {
  608. mOkButton.setEnabled(false);
  609. }
  610. }
  611. @Override
  612. public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  613. // not used at the moment
  614. }
  615. @Override
  616. public void onTextChanged(CharSequence s, int start, int before, int count) {
  617. if (mAuthStatusIcon != 0) {
  618. Log_OC.d(TAG, "onTextChanged: hiding authentication status");
  619. mAuthStatusIcon = 0;
  620. mAuthStatusText = EMPTY_STRING;
  621. showAuthStatus();
  622. }
  623. }
  624. };
  625. }
  626. }
  627. /**
  628. * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
  629. */
  630. private void initAuthorizationPreFragment(Bundle savedInstanceState) {
  631. /// step 0 - get UI elements in layout
  632. mUsernameInput = findViewById(R.id.account_username);
  633. mPasswordInput = findViewById(R.id.account_password);
  634. mAuthStatusView = findViewById(R.id.auth_status_text);
  635. /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
  636. String presetUserName = null;
  637. boolean isPasswordExposed = false;
  638. if (savedInstanceState == null) {
  639. if (mAccount != null) {
  640. presetUserName = com.owncloud.android.lib.common.accounts.AccountUtils.getUsernameForAccount(mAccount);
  641. }
  642. } else {
  643. isPasswordExposed = savedInstanceState.getBoolean(KEY_PASSWORD_EXPOSED, false);
  644. mAuthStatusText = savedInstanceState.getString(KEY_AUTH_STATUS_TEXT);
  645. mAuthStatusIcon = savedInstanceState.getInt(KEY_AUTH_STATUS_ICON);
  646. mAuthToken = savedInstanceState.getString(KEY_AUTH_TOKEN);
  647. }
  648. /// step 2 - set properties of UI elements (text, visibility, enabled...)
  649. if (presetUserName != null) {
  650. mUsernameInput.setText(presetUserName);
  651. }
  652. if (mAction != ACTION_CREATE) {
  653. mUsernameInput.setEnabled(false);
  654. mUsernameInput.setFocusable(false);
  655. }
  656. mPasswordInput.setText(EMPTY_STRING); // clean password to avoid social hacking
  657. if (isPasswordExposed) {
  658. showPassword();
  659. }
  660. showAuthStatus();
  661. mOkButton.setEnabled(mServerIsValid);
  662. /// step 3 - bind listeners
  663. // bindings for password input field
  664. mPasswordInput.setOnFocusChangeListener(this);
  665. mPasswordInput.setImeOptions(EditorInfo.IME_ACTION_DONE);
  666. mPasswordInput.setOnEditorActionListener(this);
  667. mPasswordInput.setOnTouchListener(new RightDrawableOnTouchListener() {
  668. @Override
  669. public boolean onDrawableTouch(final MotionEvent event) {
  670. if (event.getAction() == MotionEvent.ACTION_UP) {
  671. AuthenticatorActivity.this.onViewPasswordClick();
  672. }
  673. return true;
  674. }
  675. });
  676. }
  677. /**
  678. * Saves relevant state before {@link #onPause()}
  679. *
  680. * See {@link super#onSaveInstanceState(Bundle)}
  681. */
  682. @Override
  683. protected void onSaveInstanceState(Bundle outState) {
  684. //Log_OC.e(TAG, "onSaveInstanceState init" );
  685. super.onSaveInstanceState(outState);
  686. /// global state
  687. outState.putLong(KEY_WAITING_FOR_OP_ID, mWaitingForOpId);
  688. if (!webViewLoginMethod) {
  689. /// Server PRE-fragment state
  690. outState.putString(KEY_SERVER_STATUS_TEXT, mServerStatusText);
  691. outState.putInt(KEY_SERVER_STATUS_ICON, mServerStatusIcon);
  692. outState.putBoolean(KEY_SERVER_CHECKED, mServerIsChecked);
  693. outState.putBoolean(KEY_SERVER_VALID, mServerIsValid);
  694. /// Authentication PRE-fragment state
  695. outState.putBoolean(KEY_PASSWORD_EXPOSED, isPasswordVisible());
  696. outState.putInt(KEY_AUTH_STATUS_ICON, mAuthStatusIcon);
  697. outState.putString(KEY_AUTH_STATUS_TEXT, mAuthStatusText);
  698. outState.putString(KEY_AUTH_TOKEN, mAuthToken);
  699. }
  700. outState.putBoolean(KEY_IS_SSL_CONN, mServerInfo.mIsSslConn);
  701. outState.putString(KEY_HOST_URL_TEXT, mServerInfo.mBaseUrl);
  702. if (mServerInfo.mVersion != null) {
  703. outState.putString(KEY_OC_VERSION, mServerInfo.mVersion.getVersion());
  704. }
  705. outState.putString(KEY_SERVER_AUTH_METHOD, mServerInfo.mAuthMethod.name());
  706. /// authentication
  707. outState.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG, mIsFirstAuthAttempt);
  708. /// AsyncTask (User and password)
  709. if (!webViewLoginMethod) {
  710. outState.putString(KEY_USERNAME, mUsernameInput.getText().toString().trim());
  711. outState.putString(KEY_PASSWORD, mPasswordInput.getText().toString());
  712. }
  713. if (mAsyncTask != null) {
  714. mAsyncTask.cancel(true);
  715. outState.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS, true);
  716. } else {
  717. outState.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS, false);
  718. }
  719. mAsyncTask = null;
  720. //Log_OC.e(TAG, "onSaveInstanceState end" );
  721. }
  722. @Override
  723. public void onRestoreInstanceState(Bundle savedInstanceState) {
  724. super.onRestoreInstanceState(savedInstanceState);
  725. mServerIsChecked = savedInstanceState.getBoolean(KEY_SERVER_CHECKED, false);
  726. // AsyncTask
  727. boolean inProgress = savedInstanceState.getBoolean(KEY_ASYNC_TASK_IN_PROGRESS);
  728. if (inProgress) {
  729. String username = savedInstanceState.getString(KEY_USERNAME);
  730. String password = savedInstanceState.getString(KEY_PASSWORD);
  731. OwnCloudCredentials credentials = OwnCloudCredentialsFactory.newBasicCredentials(username, password);
  732. accessRootFolder(credentials);
  733. }
  734. }
  735. /**
  736. * The redirection triggered by the OAuth authentication server as response to the
  737. * GET AUTHORIZATION request is caught here.
  738. *
  739. * To make this possible, this activity needs to be qualified with android:launchMode =
  740. * "singleTask" in the AndroidManifest.xml file.
  741. */
  742. @Override
  743. protected void onNewIntent(Intent intent) {
  744. super.onNewIntent(intent);
  745. Log_OC.d(TAG, "onNewIntent()");
  746. if (intent.getBooleanExtra(FirstRunActivity.EXTRA_EXIT, false)) {
  747. super.finish();
  748. }
  749. // Passcode
  750. PassCodeManager passCodeManager = new PassCodeManager(preferences);
  751. passCodeManager.onActivityStarted(this);
  752. Uri data = intent.getData();
  753. if (data != null && data.toString().startsWith(getString(R.string.login_data_own_scheme))) {
  754. if (!getResources().getBoolean(R.bool.multiaccount_support) &&
  755. accountManager.getAccounts().length == 1) {
  756. Toast.makeText(this, R.string.no_mutliple_accounts_allowed, Toast.LENGTH_LONG).show();
  757. finish();
  758. return;
  759. } else {
  760. parseAndLoginFromWebView(data.toString());
  761. }
  762. }
  763. if (intent.getBooleanExtra(EXTRA_USE_PROVIDER_AS_WEBLOGIN, false)) {
  764. webViewLoginMethod = true;
  765. setContentView(R.layout.account_setup_webview);
  766. mLoginWebView = findViewById(R.id.login_webview);
  767. initWebViewLogin(getString(R.string.provider_registration_server), false, true);
  768. }
  769. }
  770. /**
  771. * The redirection triggered by the OAuth authentication server as response to the
  772. * GET AUTHORIZATION, and deferred in {@link #onNewIntent(Intent)}, is processed here.
  773. */
  774. @Override
  775. protected void onResume() {
  776. super.onResume();
  777. if (!webViewLoginMethod) {
  778. // bound here to avoid spurious changes triggered by Android on device rotations
  779. mHostUrlInput.setOnFocusChangeListener(this);
  780. mHostUrlInput.addTextChangedListener(mHostUrlInputWatcher);
  781. String dataString = getIntent().getDataString();
  782. if (dataString != null) {
  783. try {
  784. if (!getResources().getBoolean(R.bool.multiaccount_support) &&
  785. accountManager.getAccounts().length == 1) {
  786. Toast.makeText(this, R.string.no_mutliple_accounts_allowed, Toast.LENGTH_LONG).show();
  787. finish();
  788. return;
  789. } else {
  790. populateLoginFields(dataString);
  791. }
  792. } catch (IllegalArgumentException e) {
  793. DisplayUtils.showSnackMessage(findViewById(R.id.scroll), R.string.auth_illegal_login_used);
  794. Log_OC.e(TAG, "Illegal login data URL used, no Login pre-fill!", e);
  795. }
  796. }
  797. }
  798. // bind to Operations Service
  799. mOperationsServiceConnection = new OperationsServiceConnection();
  800. if (!bindService(new Intent(this, OperationsService.class),
  801. mOperationsServiceConnection,
  802. Context.BIND_AUTO_CREATE)) {
  803. DisplayUtils.showSnackMessage(findViewById(R.id.scroll), R.string.error_cant_bind_to_operations_service);
  804. finish();
  805. }
  806. if (mOperationsServiceBinder != null) {
  807. doOnResumeAndBound();
  808. }
  809. }
  810. @Override
  811. protected void onPause() {
  812. if (mOperationsServiceBinder != null) {
  813. mOperationsServiceBinder.removeOperationListener(this);
  814. }
  815. if (!webViewLoginMethod) {
  816. mHostUrlInput.removeTextChangedListener(mHostUrlInputWatcher);
  817. mHostUrlInput.setOnFocusChangeListener(null);
  818. }
  819. super.onPause();
  820. }
  821. @Override
  822. protected void onDestroy() {
  823. mHostUrlInputWatcher = null;
  824. if (mOperationsServiceConnection != null) {
  825. unbindService(mOperationsServiceConnection);
  826. mOperationsServiceBinder = null;
  827. }
  828. if (webViewLoginMethod) {
  829. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
  830. }
  831. super.onDestroy();
  832. }
  833. /**
  834. * Handles the change of focus on the text inputs for the server URL and the password
  835. */
  836. public void onFocusChange(View view, boolean hasFocus) {
  837. if (view.getId() == R.id.hostUrlInput) {
  838. if (!hasFocus) {
  839. onUrlInputFocusLost();
  840. } else {
  841. showRefreshButton(false);
  842. }
  843. } else if (view.getId() == R.id.account_password) {
  844. onPasswordFocusChanged(hasFocus);
  845. }
  846. }
  847. /**
  848. * Handles changes in focus on the text input for the server URL.
  849. *
  850. * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
  851. * other field. The operation to check the existence of the server in the entered URL is
  852. * started.
  853. *
  854. * When hasFocus: user 'comes back' to write again the server URL.
  855. */
  856. private void onUrlInputFocusLost() {
  857. if (!mServerInfo.mBaseUrl.equals(
  858. AuthenticatorUrlUtils.normalizeUrl(mHostUrlInput.getText().toString(), mServerInfo.mIsSslConn))) {
  859. // check server again only if the user changed something in the field
  860. checkOcServer();
  861. } else {
  862. mOkButton.setEnabled(mServerIsValid);
  863. showRefreshButton(!mServerIsValid);
  864. }
  865. }
  866. private void checkOcServer() {
  867. String uri;
  868. if (mHostUrlInput != null && !mHostUrlInput.getText().toString().isEmpty()) {
  869. uri = mHostUrlInput.getText().toString().trim();
  870. mOkButton.setEnabled(false);
  871. showRefreshButton(false);
  872. } else {
  873. uri = mServerInfo.mBaseUrl;
  874. }
  875. mServerIsValid = false;
  876. mServerIsChecked = false;
  877. mServerInfo = new GetServerInfoOperation.ServerInfo();
  878. if (uri.length() != 0) {
  879. if (mHostUrlInput != null) {
  880. uri = AuthenticatorUrlUtils.stripIndexPhpOrAppsFiles(uri);
  881. mHostUrlInput.setText(uri);
  882. }
  883. // Handle internationalized domain names
  884. try {
  885. uri = DisplayUtils.convertIdn(uri, true);
  886. } catch (IllegalArgumentException ex) {
  887. // Let Owncloud library check the error of the malformed URI
  888. Log_OC.e(TAG, "Error converting internationalized domain name " + uri, ex);
  889. }
  890. if (mHostUrlInput != null) {
  891. mServerStatusText = getResources().getString(R.string.auth_testing_connection);
  892. mServerStatusIcon = R.drawable.progress_small;
  893. showServerStatus();
  894. }
  895. Intent getServerInfoIntent = new Intent();
  896. getServerInfoIntent.setAction(OperationsService.ACTION_GET_SERVER_INFO);
  897. getServerInfoIntent.putExtra(OperationsService.EXTRA_SERVER_URL,
  898. AuthenticatorUrlUtils.normalizeUrlSuffix(uri));
  899. if (mOperationsServiceBinder != null) {
  900. mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getServerInfoIntent);
  901. } else {
  902. Log_OC.e(TAG, "Server check tried with OperationService unbound!");
  903. }
  904. } else {
  905. mServerStatusText = EMPTY_STRING;
  906. mServerStatusIcon = 0;
  907. if (!webViewLoginMethod) {
  908. showServerStatus();
  909. }
  910. }
  911. }
  912. /**
  913. * Handles changes in focus on the text input for the password (basic authorization).
  914. *
  915. * When (hasFocus), the button to toggle password visibility is shown.
  916. *
  917. * When (!hasFocus), the button is made invisible and the password is hidden.
  918. *
  919. * @param hasFocus 'True' if focus is received, 'false' if is lost
  920. */
  921. private void onPasswordFocusChanged(boolean hasFocus) {
  922. if (hasFocus) {
  923. showViewPasswordButton();
  924. } else {
  925. hidePassword();
  926. hidePasswordButton();
  927. }
  928. }
  929. private void showViewPasswordButton() {
  930. int drawable = R.drawable.ic_view;
  931. if (isPasswordVisible()) {
  932. drawable = R.drawable.ic_hide;
  933. }
  934. mPasswordInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable, 0);
  935. }
  936. private boolean isPasswordVisible() {
  937. return ((mPasswordInput.getInputType() & InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) ==
  938. InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
  939. }
  940. private void hidePasswordButton() {
  941. mPasswordInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
  942. }
  943. private void showPassword() {
  944. mPasswordInput.setInputType(
  945. InputType.TYPE_CLASS_TEXT |
  946. InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD |
  947. InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
  948. );
  949. showViewPasswordButton();
  950. }
  951. private void hidePassword() {
  952. mPasswordInput.setInputType(
  953. InputType.TYPE_CLASS_TEXT |
  954. InputType.TYPE_TEXT_VARIATION_PASSWORD |
  955. InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
  956. );
  957. showViewPasswordButton();
  958. }
  959. /**
  960. * Checks the credentials of the user in the root of the ownCloud server
  961. * before creating a new local account.
  962. *
  963. * For basic authorization, a check of existence of the root folder is
  964. * performed.
  965. *
  966. * For OAuth, starts the flow to get an access token; the credentials test
  967. * is postponed until it is available.
  968. *
  969. * IMPORTANT ENTRY POINT 4
  970. */
  971. public void onOkClick() {
  972. // this check should be unnecessary
  973. if (mServerInfo.mVersion == null ||
  974. !mServerInfo.mVersion.isVersionValid() ||
  975. TextUtils.isEmpty(mServerInfo.mBaseUrl)) {
  976. mServerStatusIcon = R.drawable.ic_alert;
  977. mServerStatusText = getResources().getString(R.string.auth_wtf_reenter_URL);
  978. showServerStatus();
  979. mOkButton.setEnabled(false);
  980. return;
  981. }
  982. checkBasicAuthorization(null, null);
  983. }
  984. /**
  985. * Tests the credentials entered by the user performing a check of existence on
  986. * the root folder of the ownCloud server.
  987. */
  988. private void checkBasicAuthorization(@Nullable String webViewUsername, @Nullable String webViewPassword) {
  989. /// get basic credentials entered by user
  990. String username;
  991. String password;
  992. if (!webViewLoginMethod) {
  993. username = mUsernameInput.getText().toString().trim();
  994. password = mPasswordInput.getText().toString();
  995. } else {
  996. username = webViewUsername;
  997. password = webViewPassword;
  998. }
  999. /// be gentle with the user
  1000. IndeterminateProgressDialog dialog = IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login,
  1001. true);
  1002. FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
  1003. ft.add(dialog, WAIT_DIALOG_TAG);
  1004. ft.commitAllowingStateLoss();
  1005. /// validate credentials accessing the root folder
  1006. OwnCloudCredentials credentials = OwnCloudCredentialsFactory.newBasicCredentials(username, password);
  1007. accessRootFolder(credentials);
  1008. }
  1009. private void accessRootFolder(OwnCloudCredentials credentials) {
  1010. mAsyncTask = new AuthenticatorAsyncTask(this);
  1011. Object[] params = {mServerInfo.mBaseUrl, credentials};
  1012. mAsyncTask.execute(params);
  1013. }
  1014. /**
  1015. * Callback method invoked when a RemoteOperation executed by this Activity finishes.
  1016. *
  1017. * Dispatches the operation flow to the right method.
  1018. */
  1019. @Override
  1020. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  1021. if (operation instanceof GetServerInfoOperation) {
  1022. if (operation.hashCode() == mWaitingForOpId) {
  1023. onGetServerInfoFinish(result);
  1024. } // else nothing ; only the last check operation is considered;
  1025. // multiple can be started if the user amends a URL quickly
  1026. } else if (operation instanceof GetUserInfoRemoteOperation) {
  1027. onGetUserNameFinish(result);
  1028. }
  1029. }
  1030. private void onGetUserNameFinish(RemoteOperationResult result) {
  1031. mWaitingForOpId = Long.MAX_VALUE;
  1032. if (result.isSuccess()) {
  1033. boolean success = false;
  1034. String username;
  1035. if (result.getData().get(0) instanceof UserInfo) {
  1036. username = ((UserInfo) result.getData().get(0)).getDisplayName();
  1037. } else {
  1038. username = (String) result.getData().get(0);
  1039. }
  1040. if (mAction == ACTION_CREATE) {
  1041. if (!webViewLoginMethod) {
  1042. mUsernameInput.setText(username);
  1043. }
  1044. success = createAccount(result);
  1045. } else {
  1046. if (!webViewLoginMethod && !mUsernameInput.getText().toString().trim().equals(username)) {
  1047. // fail - not a new account, but an existing one; disallow
  1048. result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_THE_SAME);
  1049. mAuthToken = EMPTY_STRING;
  1050. updateAuthStatusIconAndText(result);
  1051. showAuthStatus();
  1052. Log_OC.d(TAG, result.getLogMessage());
  1053. } else {
  1054. try {
  1055. updateAccountAuthentication();
  1056. success = true;
  1057. } catch (AccountNotFoundException e) {
  1058. Log_OC.e(TAG, "Account " + mAccount + " was removed!", e);
  1059. DisplayUtils.showSnackMessage(findViewById(R.id.scroll), R.string.auth_account_does_not_exist);
  1060. finish();
  1061. }
  1062. }
  1063. }
  1064. if (success) {
  1065. finish();
  1066. }
  1067. } else {
  1068. if (!webViewLoginMethod) {
  1069. int statusText = result.getCode() == ResultCode.MAINTENANCE_MODE ? R.string.maintenance_mode : R.string.auth_fail_get_user_name;
  1070. updateStatusIconFailUserName(statusText);
  1071. showAuthStatus();
  1072. }
  1073. Log_OC.e(TAG, "Access to user name failed: " + result.getLogMessage());
  1074. }
  1075. }
  1076. /**
  1077. * Processes the result of the server check performed when the user finishes the enter of the
  1078. * server URL.
  1079. *
  1080. * @param result Result of the check.
  1081. */
  1082. private void onGetServerInfoFinish(RemoteOperationResult result) {
  1083. /// update activity state
  1084. mServerIsChecked = true;
  1085. mWaitingForOpId = Long.MAX_VALUE;
  1086. // update server status, but don't show it yet
  1087. if (!webViewLoginMethod) {
  1088. updateServerStatusIconAndText(result);
  1089. }
  1090. if (result.isSuccess()) {
  1091. /// SUCCESS means:
  1092. // 1. connection succeeded, and we know if it's SSL or not
  1093. // 2. server is installed
  1094. // 3. we got the server version
  1095. // 4. we got the authentication method required by the server
  1096. mServerInfo = (GetServerInfoOperation.ServerInfo) (result.getData().get(0));
  1097. // show outdated warning
  1098. if (getResources().getBoolean(R.bool.show_outdated_server_warning) &&
  1099. MainApp.OUTDATED_SERVER_VERSION.isSameMajorVersion(mServerInfo.mVersion) &&
  1100. !mServerInfo.hasExtendedSupport) {
  1101. DisplayUtils.showServerOutdatedSnackbar(this, Snackbar.LENGTH_INDEFINITE);
  1102. }
  1103. webViewLoginMethod = mServerInfo.mVersion.isWebLoginSupported() && !forceOldLoginMethod;
  1104. if (webViewUser != null && !webViewUser.isEmpty() &&
  1105. webViewPassword != null && !webViewPassword.isEmpty()) {
  1106. checkBasicAuthorization(webViewUser, webViewPassword);
  1107. } else if (webViewLoginMethod) {
  1108. // hide old login
  1109. setOldLoginVisibility(View.GONE);
  1110. setContentView(R.layout.account_setup_webview);
  1111. mLoginWebView = findViewById(R.id.login_webview);
  1112. initWebViewLogin(mServerInfo.mBaseUrl + WEB_LOGIN, true, false);
  1113. } else {
  1114. // show old login
  1115. setOldLoginVisibility(View.VISIBLE);
  1116. }
  1117. if (!authSupported(mServerInfo.mAuthMethod)) {
  1118. if (!webViewLoginMethod) {
  1119. // overrides updateServerStatusIconAndText()
  1120. updateServerStatusIconNoRegularAuth();
  1121. }
  1122. mServerIsValid = false;
  1123. } else {
  1124. mServerIsValid = true;
  1125. }
  1126. } else {
  1127. mServerIsValid = false;
  1128. }
  1129. // refresh UI
  1130. if (!webViewLoginMethod) {
  1131. showRefreshButton(!mServerIsValid);
  1132. showServerStatus();
  1133. mOkButton.setEnabled(mServerIsValid);
  1134. }
  1135. if (!mServerIsValid) {
  1136. // hide old login
  1137. setOldLoginVisibility(View.GONE);
  1138. }
  1139. /// very special case (TODO: move to a common place for all the remote operations)
  1140. if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
  1141. showUntrustedCertDialog(result);
  1142. }
  1143. }
  1144. private void setOldLoginVisibility(int visible) {
  1145. mOkButton.setVisibility(visible);
  1146. mUsernameInput.setVisibility(visible);
  1147. mPasswordInput.setVisibility(visible);
  1148. if (View.VISIBLE == visible) {
  1149. scanQR.setVisibility(View.GONE);
  1150. } else {
  1151. scanQR.setVisibility(View.VISIBLE);
  1152. }
  1153. }
  1154. private boolean authSupported(AuthenticationMethod authMethod) {
  1155. return AuthenticationMethod.BASIC_HTTP_AUTH.equals(authMethod);
  1156. }
  1157. /**
  1158. * Chooses the right icon and text to show to the user for the received operation result.
  1159. *
  1160. * @param result Result of a remote operation performed in this activity
  1161. */
  1162. private void updateServerStatusIconAndText(RemoteOperationResult result) {
  1163. mServerStatusIcon = R.drawable.ic_alert; // the most common case in the switch below
  1164. switch (result.getCode()) {
  1165. case OK_SSL:
  1166. mServerStatusIcon = R.drawable.ic_lock_white;
  1167. mServerStatusText = getResources().getString(R.string.auth_secure_connection);
  1168. break;
  1169. case OK_NO_SSL:
  1170. case OK:
  1171. if (mHostUrlInput.getText().toString().trim().toLowerCase(Locale.ROOT).startsWith(HTTP_PROTOCOL)) {
  1172. mServerStatusText = getResources().getString(R.string.auth_connection_established);
  1173. mServerStatusIcon = R.drawable.ic_ok;
  1174. } else {
  1175. mServerStatusText = getResources().getString(R.string.auth_nossl_plain_ok_title);
  1176. mServerStatusIcon = R.drawable.ic_lock_open_white;
  1177. }
  1178. break;
  1179. case NO_NETWORK_CONNECTION:
  1180. mServerStatusIcon = R.drawable.no_network;
  1181. mServerStatusText = getResources().getString(R.string.auth_no_net_conn_title);
  1182. break;
  1183. case SSL_RECOVERABLE_PEER_UNVERIFIED:
  1184. mServerStatusText = getResources().getString(R.string.auth_ssl_unverified_server_title);
  1185. break;
  1186. case BAD_OC_VERSION:
  1187. mServerStatusText = getResources().getString(R.string.auth_bad_oc_version_title);
  1188. break;
  1189. case WRONG_CONNECTION:
  1190. mServerStatusText = getResources().getString(R.string.auth_wrong_connection_title);
  1191. break;
  1192. case TIMEOUT:
  1193. mServerStatusText = getResources().getString(R.string.auth_timeout_title);
  1194. break;
  1195. case INCORRECT_ADDRESS:
  1196. mServerStatusText = getResources().getString(R.string.auth_incorrect_address_title);
  1197. break;
  1198. case SSL_ERROR:
  1199. mServerStatusText = getResources().getString(R.string.auth_ssl_general_error_title);
  1200. break;
  1201. case UNAUTHORIZED:
  1202. mServerStatusText = getResources().getString(R.string.auth_unauthorized);
  1203. break;
  1204. case HOST_NOT_AVAILABLE:
  1205. mServerStatusText = getResources().getString(R.string.auth_unknown_host_title);
  1206. break;
  1207. case INSTANCE_NOT_CONFIGURED:
  1208. mServerStatusText = getResources().getString(R.string.auth_not_configured_title);
  1209. break;
  1210. case FILE_NOT_FOUND:
  1211. mServerStatusText = getResources().getString(R.string.auth_incorrect_path_title);
  1212. break;
  1213. case OAUTH2_ERROR:
  1214. mServerStatusText = getResources().getString(R.string.auth_oauth_error);
  1215. break;
  1216. case OAUTH2_ERROR_ACCESS_DENIED:
  1217. mServerStatusText = getResources().getString(R.string.auth_oauth_error_access_denied);
  1218. break;
  1219. case UNHANDLED_HTTP_CODE:
  1220. mServerStatusText = getResources().getString(R.string.auth_unknown_error_http_title);
  1221. break;
  1222. case UNKNOWN_ERROR:
  1223. if (result.getException() != null &&
  1224. !TextUtils.isEmpty(result.getException().getMessage())) {
  1225. mServerStatusText = getResources().getString(
  1226. R.string.auth_unknown_error_exception_title,
  1227. result.getException().getMessage()
  1228. );
  1229. } else {
  1230. mServerStatusText = getResources().getString(R.string.auth_unknown_error_title);
  1231. }
  1232. break;
  1233. case OK_REDIRECT_TO_NON_SECURE_CONNECTION:
  1234. mServerStatusIcon = R.drawable.ic_lock_open_white;
  1235. mServerStatusText = getResources().getString(R.string.auth_redirect_non_secure_connection_title);
  1236. break;
  1237. case MAINTENANCE_MODE:
  1238. mServerStatusText = getResources().getString(R.string.maintenance_mode);
  1239. break;
  1240. case UNTRUSTED_DOMAIN:
  1241. mServerStatusText = getResources().getString(R.string.untrusted_domain);
  1242. break;
  1243. default:
  1244. mServerStatusText = EMPTY_STRING;
  1245. mServerStatusIcon = 0;
  1246. break;
  1247. }
  1248. }
  1249. /**
  1250. * Chooses the right icon and text to show to the user for the received operation result.
  1251. *
  1252. * @param result Result of a remote operation performed in this activity
  1253. */
  1254. private void updateAuthStatusIconAndText(RemoteOperationResult result) {
  1255. mAuthStatusIcon = R.drawable.ic_alert; // the most common case in the switch below
  1256. switch (result.getCode()) {
  1257. case OK_SSL:
  1258. mAuthStatusIcon = R.drawable.ic_lock_white;
  1259. mAuthStatusText = getResources().getString(R.string.auth_secure_connection);
  1260. break;
  1261. case OK_NO_SSL:
  1262. case OK:
  1263. if (mHostUrlInput.getText().toString().trim().toLowerCase(Locale.ROOT).startsWith(HTTP_PROTOCOL)) {
  1264. mAuthStatusText = getResources().getString(R.string.auth_connection_established);
  1265. mAuthStatusIcon = R.drawable.ic_ok;
  1266. } else {
  1267. mAuthStatusText = getResources().getString(R.string.auth_nossl_plain_ok_title);
  1268. mAuthStatusIcon = R.drawable.ic_lock_open_white;
  1269. }
  1270. break;
  1271. case NO_NETWORK_CONNECTION:
  1272. mAuthStatusIcon = R.drawable.no_network;
  1273. mAuthStatusText = getResources().getString(R.string.auth_no_net_conn_title);
  1274. break;
  1275. case SSL_RECOVERABLE_PEER_UNVERIFIED:
  1276. mAuthStatusText = getResources().getString(R.string.auth_ssl_unverified_server_title);
  1277. break;
  1278. case TIMEOUT:
  1279. mAuthStatusText = getResources().getString(R.string.auth_timeout_title);
  1280. break;
  1281. case HOST_NOT_AVAILABLE:
  1282. mAuthStatusText = getResources().getString(R.string.auth_unknown_host_title);
  1283. break;
  1284. case UNHANDLED_HTTP_CODE:
  1285. default:
  1286. mAuthStatusText = ErrorMessageAdapter.getErrorCauseMessage(result, null, getResources());
  1287. }
  1288. }
  1289. private void updateStatusIconFailUserName(int failedStatusText) {
  1290. mAuthStatusIcon = R.drawable.ic_alert;
  1291. mAuthStatusText = getResources().getString(failedStatusText);
  1292. }
  1293. private void updateServerStatusIconNoRegularAuth() {
  1294. mServerStatusIcon = R.drawable.ic_alert;
  1295. mServerStatusText = getResources().getString(R.string.auth_can_not_auth_against_server);
  1296. }
  1297. /**
  1298. * Processes the result of the access check performed to try the user credentials.
  1299. *
  1300. * Creates a new account through the AccountManager.
  1301. *
  1302. * @param result Result of the operation.
  1303. */
  1304. @Override
  1305. public void onAuthenticatorTaskCallback(RemoteOperationResult result) {
  1306. mWaitingForOpId = Long.MAX_VALUE;
  1307. dismissDialog(WAIT_DIALOG_TAG);
  1308. mAsyncTask = null;
  1309. if (result.isSuccess()) {
  1310. Log_OC.d(TAG, "Successful access - time to save the account");
  1311. boolean success = false;
  1312. if (mAction == ACTION_CREATE) {
  1313. success = createAccount(result);
  1314. } else {
  1315. try {
  1316. updateAccountAuthentication();
  1317. success = true;
  1318. } catch (AccountNotFoundException e) {
  1319. Log_OC.e(TAG, "Account " + mAccount + " was removed!", e);
  1320. DisplayUtils.showSnackMessage(findViewById(R.id.scroll), R.string.auth_account_does_not_exist);
  1321. finish();
  1322. }
  1323. }
  1324. // Reset webView
  1325. webViewPassword = null;
  1326. webViewUser = null;
  1327. forceOldLoginMethod = false;
  1328. deleteCookies();
  1329. if (success) {
  1330. finish();
  1331. accountManager.setCurrentOwnCloudAccount(mAccount.name);
  1332. Intent i = new Intent(this, FileDisplayActivity.class);
  1333. i.setAction(FileDisplayActivity.RESTART);
  1334. i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  1335. startActivity(i);
  1336. } else {
  1337. // init webView again
  1338. if (mLoginWebView != null) {
  1339. mLoginWebView.setVisibility(View.GONE);
  1340. }
  1341. setContentView(R.layout.account_setup);
  1342. initOverallUi();
  1343. EditText serverAddressField = findViewById(R.id.hostUrlInput);
  1344. serverAddressField.setText(mServerInfo.mBaseUrl);
  1345. findViewById(R.id.server_status_text).setVisibility(View.GONE);
  1346. mAuthStatusView = findViewById(R.id.auth_status_text);
  1347. showAuthStatus();
  1348. }
  1349. } else if (result.isServerFail() || result.isException()) {
  1350. /// server errors or exceptions in authorization take to requiring a new check of
  1351. /// the server
  1352. mServerIsChecked = true;
  1353. mServerIsValid = false;
  1354. mServerInfo = new GetServerInfoOperation.ServerInfo();
  1355. // update status icon and text
  1356. updateServerStatusIconAndText(result);
  1357. showServerStatus();
  1358. mAuthStatusIcon = 0;
  1359. mAuthStatusText = EMPTY_STRING;
  1360. if (!webViewLoginMethod) {
  1361. showAuthStatus();
  1362. // update input controls state
  1363. showRefreshButton(true);
  1364. mOkButton.setEnabled(false);
  1365. }
  1366. // very special case (TODO: move to a common place for all the remote operations)
  1367. if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
  1368. showUntrustedCertDialog(result);
  1369. }
  1370. } else { // authorization fail due to client side - probably wrong credentials
  1371. if (webViewLoginMethod) {
  1372. mLoginWebView = findViewById(R.id.login_webview);
  1373. if (mLoginWebView != null) {
  1374. initWebViewLogin(mServerInfo.mBaseUrl + WEB_LOGIN, true, false);
  1375. DisplayUtils.showSnackMessage(this, mLoginWebView, R.string.auth_access_failed,
  1376. result.getLogMessage());
  1377. } else {
  1378. DisplayUtils.showSnackMessage(this, R.string.auth_access_failed, result.getLogMessage());
  1379. // init webView again
  1380. if (mLoginWebView != null) {
  1381. mLoginWebView.setVisibility(View.GONE);
  1382. }
  1383. setContentView(R.layout.account_setup);
  1384. initOverallUi();
  1385. EditText serverAddressField = findViewById(R.id.hostUrlInput);
  1386. serverAddressField.setText(mServerInfo.mBaseUrl);
  1387. findViewById(R.id.server_status_text).setVisibility(View.GONE);
  1388. mAuthStatusView = findViewById(R.id.auth_status_text);
  1389. showAuthStatus();
  1390. }
  1391. } else {
  1392. updateAuthStatusIconAndText(result);
  1393. showAuthStatus();
  1394. }
  1395. // reset webview
  1396. webViewPassword = null;
  1397. webViewUser = null;
  1398. deleteCookies();
  1399. Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
  1400. }
  1401. }
  1402. /**
  1403. * Updates the authentication token.
  1404. *
  1405. * Sets the proper response so that the AccountAuthenticator that started this activity
  1406. * saves a new authorization token for mAccount.
  1407. *
  1408. * Kills the session kept by OwnCloudClientManager so that a new one will created with
  1409. * the new credentials when needed.
  1410. */
  1411. private void updateAccountAuthentication() throws AccountNotFoundException {
  1412. Bundle response = new Bundle();
  1413. response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
  1414. response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);
  1415. if (webViewLoginMethod) {
  1416. response.putString(AccountManager.KEY_AUTHTOKEN, webViewPassword);
  1417. mAccountMgr.setPassword(mAccount, webViewPassword);
  1418. } else {
  1419. response.putString(AccountManager.KEY_AUTHTOKEN, mPasswordInput.getText().toString());
  1420. mAccountMgr.setPassword(mAccount, mPasswordInput.getText().toString());
  1421. }
  1422. // remove managed clients for this account to enforce creation with fresh credentials
  1423. OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount, this);
  1424. OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(ocAccount);
  1425. setAccountAuthenticatorResult(response);
  1426. final Intent intent = new Intent();
  1427. intent.putExtras(response);
  1428. setResult(RESULT_OK, intent);
  1429. }
  1430. /**
  1431. * Creates a new account through the Account Authenticator that started this activity.
  1432. *
  1433. * This makes the account permanent.
  1434. *
  1435. * TODO Decide how to name the OAuth accounts
  1436. */
  1437. @SuppressFBWarnings("DMI")
  1438. @SuppressLint("TrulyRandom")
  1439. protected boolean createAccount(RemoteOperationResult authResult) {
  1440. String accountType = MainApp.getAccountType(this);
  1441. // create and save new ownCloud account
  1442. String lastPermanentLocation = authResult.getLastPermanentLocation();
  1443. if (lastPermanentLocation != null) {
  1444. mServerInfo.mBaseUrl = AuthenticatorUrlUtils.trimWebdavSuffix(lastPermanentLocation);
  1445. }
  1446. Uri uri = Uri.parse(mServerInfo.mBaseUrl);
  1447. // used for authenticate on every login/network connection, determined by first login (weblogin/old login)
  1448. // can be anything: email, name, name with whitespaces
  1449. String loginName;
  1450. if (!webViewLoginMethod) {
  1451. loginName = mUsernameInput.getText().toString().trim();
  1452. } else {
  1453. loginName = webViewUser;
  1454. }
  1455. String accountName = com.owncloud.android.lib.common.accounts.AccountUtils.buildAccountName(uri, loginName);
  1456. Account newAccount = new Account(accountName, accountType);
  1457. if (accountManager.exists(newAccount)) {
  1458. // fail - not a new account, but an existing one; disallow
  1459. RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW);
  1460. updateAuthStatusIconAndText(result);
  1461. showAuthStatus();
  1462. Log_OC.d(TAG, result.getLogMessage());
  1463. return false;
  1464. } else {
  1465. mAccount = newAccount;
  1466. if (webViewLoginMethod) {
  1467. mAccountMgr.addAccountExplicitly(mAccount, webViewPassword, null);
  1468. } else {
  1469. mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);
  1470. }
  1471. /// add the new account as default in preferences, if there is none already
  1472. Account defaultAccount = accountManager.getCurrentAccount();
  1473. if (defaultAccount == null) {
  1474. SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
  1475. editor.putString("select_oc_account", accountName);
  1476. editor.apply();
  1477. }
  1478. /// prepare result to return to the Authenticator
  1479. // TODO check again what the Authenticator makes with it; probably has the same
  1480. // effect as addAccountExplicitly, but it's not well done
  1481. final Intent intent = new Intent();
  1482. intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType);
  1483. intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
  1484. intent.putExtra(AccountManager.KEY_USERDATA, loginName);
  1485. /// add user data to the new account; TODO probably can be done in the last parameter
  1486. // addAccountExplicitly, or in KEY_USERDATA
  1487. mAccountMgr.setUserData(mAccount, Constants.KEY_OC_VERSION, mServerInfo.mVersion.getVersion());
  1488. mAccountMgr.setUserData(mAccount, Constants.KEY_OC_BASE_URL, mServerInfo.mBaseUrl);
  1489. ArrayList<Object> authResultData = authResult.getData();
  1490. if (authResultData == null || authResultData.size() == 0) {
  1491. Log_OC.e(this, "Could not read user data!");
  1492. return false;
  1493. }
  1494. UserInfo userInfo = (UserInfo) authResultData.get(0);
  1495. mAccountMgr.setUserData(mAccount, Constants.KEY_DISPLAY_NAME, userInfo.getDisplayName());
  1496. mAccountMgr.setUserData(mAccount, Constants.KEY_USER_ID, userInfo.getId());
  1497. mAccountMgr.setUserData(mAccount, Constants.KEY_OC_ACCOUNT_VERSION,
  1498. Integer.toString(UserAccountManager.ACCOUNT_VERSION_WITH_PROPER_ID));
  1499. setAccountAuthenticatorResult(intent.getExtras());
  1500. setResult(RESULT_OK, intent);
  1501. return true;
  1502. }
  1503. }
  1504. public void onScan() {
  1505. if (PermissionUtil.checkSelfPermission(this, Manifest.permission.CAMERA)) {
  1506. startQRScanner();
  1507. } else {
  1508. PermissionUtil.requestCameraPermission(this);
  1509. }
  1510. }
  1511. private void startQRScanner() {
  1512. Intent i = new Intent(this, QrCodeActivity.class);
  1513. startActivityForResult(i, REQUEST_CODE_QR_SCAN);
  1514. }
  1515. @Override
  1516. public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[],
  1517. @NonNull int[] grantResults) {
  1518. switch (requestCode) {
  1519. case PermissionUtil.PERMISSIONS_CAMERA: {
  1520. // If request is cancelled, result arrays are empty.
  1521. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  1522. // permission was granted
  1523. startQRScanner();
  1524. } else {
  1525. // permission denied
  1526. return;
  1527. }
  1528. return;
  1529. }
  1530. default:
  1531. super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  1532. }
  1533. }
  1534. /**
  1535. /**
  1536. * Updates the content and visibility state of the icon and text associated
  1537. * to the last check on the ownCloud server.
  1538. */
  1539. private void showServerStatus() {
  1540. if (mServerStatusIcon == NO_ICON && EMPTY_STRING.equals(mServerStatusText)) {
  1541. mServerStatusView.setVisibility(View.INVISIBLE);
  1542. } else {
  1543. mServerStatusView.setText(mServerStatusText);
  1544. mServerStatusView.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon, 0, 0, 0);
  1545. mServerStatusView.setVisibility(View.VISIBLE);
  1546. }
  1547. }
  1548. /**
  1549. * Updates the content and visibility state of the icon and text associated
  1550. * to the interactions with the OAuth authorization server.
  1551. */
  1552. private void showAuthStatus() {
  1553. if (mAuthStatusIcon == NO_ICON && EMPTY_STRING.equals(mAuthStatusText)) {
  1554. mAuthStatusView.setVisibility(View.INVISIBLE);
  1555. } else {
  1556. mAuthStatusView.setText(mAuthStatusText);
  1557. mAuthStatusView.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon, 0, 0, 0);
  1558. mAuthStatusView.setVisibility(View.VISIBLE);
  1559. }
  1560. }
  1561. private void showRefreshButton(boolean show) {
  1562. if (webViewLoginMethod && mRefreshButton != null) {
  1563. if (show) {
  1564. mRefreshButton.setVisibility(View.VISIBLE);
  1565. } else {
  1566. mRefreshButton.setVisibility(View.GONE);
  1567. }
  1568. }
  1569. }
  1570. /**
  1571. * Called when the eye icon in the password field is clicked.
  1572. *
  1573. * Toggles the visibility of the password in the field.
  1574. */
  1575. public void onViewPasswordClick() {
  1576. int selectionStart = mPasswordInput.getSelectionStart();
  1577. int selectionEnd = mPasswordInput.getSelectionEnd();
  1578. if (isPasswordVisible()) {
  1579. hidePassword();
  1580. } else {
  1581. showPassword();
  1582. }
  1583. mPasswordInput.setSelection(selectionStart, selectionEnd);
  1584. }
  1585. /**
  1586. * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
  1587. *
  1588. * Used to trigger the authentication check when the user presses 'enter' after writing the
  1589. * password, or to throw the server test when the only field on screen is the URL input field.
  1590. */
  1591. @Override
  1592. public boolean onEditorAction(TextView inputField, int actionId, KeyEvent event) {
  1593. if (actionId == EditorInfo.IME_ACTION_DONE && inputField != null &&
  1594. inputField.equals(mPasswordInput)) {
  1595. if (mOkButton.isEnabled()) {
  1596. mOkButton.performClick();
  1597. }
  1598. } else if ((actionId == EditorInfo.IME_ACTION_NEXT || actionId == EditorInfo.IME_NULL)
  1599. && inputField != null && inputField.equals(mHostUrlInput)) {
  1600. checkOcServer();
  1601. }
  1602. return false; // always return false to grant that the software keyboard is hidden anyway
  1603. }
  1604. private abstract static class RightDrawableOnTouchListener implements OnTouchListener {
  1605. private static final int RIGHT_DRAWABLE_COMPOUND_DRAWABLES_LENGTH = 2;
  1606. private int fuzz = 75;
  1607. /**
  1608. * {@inheritDoc}
  1609. */
  1610. @Override
  1611. public boolean onTouch(View view, MotionEvent event) {
  1612. Drawable rightDrawable = null;
  1613. if (view instanceof TextView) {
  1614. Drawable[] drawables = ((TextView) view).getCompoundDrawables();
  1615. if (drawables.length > RIGHT_DRAWABLE_COMPOUND_DRAWABLES_LENGTH) {
  1616. rightDrawable = drawables[2];
  1617. }
  1618. }
  1619. if (rightDrawable != null) {
  1620. final int x = (int) event.getX();
  1621. final int y = (int) event.getY();
  1622. final Rect bounds = rightDrawable.getBounds();
  1623. if (x >= (view.getRight() - bounds.width() - fuzz) &&
  1624. x <= (view.getRight() - view.getPaddingRight() + fuzz) &&
  1625. y >= (view.getPaddingTop() - fuzz) &&
  1626. y <= (view.getHeight() - view.getPaddingBottom()) + fuzz) {
  1627. return onDrawableTouch(event);
  1628. }
  1629. }
  1630. return false;
  1631. }
  1632. public abstract boolean onDrawableTouch(final MotionEvent event);
  1633. }
  1634. /**
  1635. * Show untrusted cert dialog
  1636. */
  1637. public void showUntrustedCertDialog(X509Certificate x509Certificate, SslError error, SslErrorHandler handler) {
  1638. // Show a dialog with the certificate info
  1639. SslUntrustedCertDialog dialog;
  1640. if (x509Certificate == null) {
  1641. dialog = SslUntrustedCertDialog.newInstanceForEmptySslError(error, handler);
  1642. } else {
  1643. dialog = SslUntrustedCertDialog.newInstanceForFullSslError(x509Certificate, error, handler);
  1644. }
  1645. FragmentManager fm = getSupportFragmentManager();
  1646. FragmentTransaction ft = fm.beginTransaction();
  1647. ft.addToBackStack(null);
  1648. dialog.show(ft, UNTRUSTED_CERT_DIALOG_TAG);
  1649. }
  1650. /**
  1651. * Show untrusted cert dialog
  1652. */
  1653. private void showUntrustedCertDialog(RemoteOperationResult result) {
  1654. // Show a dialog with the certificate info
  1655. SslUntrustedCertDialog dialog = SslUntrustedCertDialog.
  1656. newInstanceForFullSslError((CertificateCombinedException) result.getException());
  1657. FragmentManager fm = getSupportFragmentManager();
  1658. FragmentTransaction ft = fm.beginTransaction();
  1659. ft.addToBackStack(null);
  1660. dialog.show(ft, UNTRUSTED_CERT_DIALOG_TAG);
  1661. }
  1662. private void doOnResumeAndBound() {
  1663. //Log_OC.e(TAG, "registering to listen for operation callbacks" );
  1664. mOperationsServiceBinder.addOperationListener(this, mHandler);
  1665. if (mWaitingForOpId <= Integer.MAX_VALUE) {
  1666. mOperationsServiceBinder.dispatchResultIfFinished((int) mWaitingForOpId, this);
  1667. }
  1668. if (!webViewLoginMethod && !TextUtils.isEmpty(mHostUrlInput.getText()) && !mServerIsChecked) {
  1669. checkOcServer();
  1670. }
  1671. }
  1672. private void dismissDialog(String dialogTag) {
  1673. Fragment frag = getSupportFragmentManager().findFragmentByTag(dialogTag);
  1674. if (frag instanceof DialogFragment) {
  1675. DialogFragment dialog = (DialogFragment) frag;
  1676. try {
  1677. dialog.dismiss();
  1678. } catch (IllegalStateException e) {
  1679. Log_OC.e(TAG, e.getMessage());
  1680. dialog.dismissAllowingStateLoss();
  1681. }
  1682. }
  1683. }
  1684. /**
  1685. * Implements callback methods for service binding.
  1686. */
  1687. private class OperationsServiceConnection implements ServiceConnection {
  1688. @Override
  1689. public void onServiceConnected(ComponentName component, IBinder service) {
  1690. if (component.equals(
  1691. new ComponentName(AuthenticatorActivity.this, OperationsService.class)
  1692. )) {
  1693. mOperationsServiceBinder = (OperationsServiceBinder) service;
  1694. Uri data = getIntent().getData();
  1695. if (data != null && data.toString().startsWith(getString(R.string.login_data_own_scheme))) {
  1696. String prefix = getString(R.string.login_data_own_scheme) + PROTOCOL_SUFFIX + "login/";
  1697. LoginUrlInfo loginUrlInfo = parseLoginDataUrl(prefix, data.toString());
  1698. if (loginUrlInfo != null) {
  1699. try {
  1700. mServerInfo.mBaseUrl = AuthenticatorUrlUtils.normalizeUrlSuffix(loginUrlInfo.serverAddress);
  1701. webViewUser = loginUrlInfo.username;
  1702. webViewPassword = loginUrlInfo.password;
  1703. doOnResumeAndBound();
  1704. } catch (Exception e) {
  1705. mServerStatusIcon = R.drawable.ic_alert;
  1706. mServerStatusText = "QR Code could not be read!";
  1707. showServerStatus();
  1708. }
  1709. }
  1710. } else {
  1711. doOnResumeAndBound();
  1712. }
  1713. }
  1714. }
  1715. @Override
  1716. public void onServiceDisconnected(ComponentName component) {
  1717. if (component.equals(
  1718. new ComponentName(AuthenticatorActivity.this, OperationsService.class)
  1719. )) {
  1720. Log_OC.e(TAG, "Operations service crashed");
  1721. mOperationsServiceBinder = null;
  1722. }
  1723. }
  1724. }
  1725. /**
  1726. * Create and show dialog for request authentication to the user
  1727. *
  1728. * @param webView Web view to embed into the authentication dialog.
  1729. * @param handler Object responsible for catching and recovering HTTP authentication fails.
  1730. */
  1731. public void createAuthenticationDialog(WebView webView, HttpAuthHandler handler) {
  1732. // Show a dialog with the certificate info
  1733. CredentialsDialogFragment dialog = CredentialsDialogFragment.newInstanceForCredentials(webView, handler);
  1734. FragmentManager fm = getSupportFragmentManager();
  1735. FragmentTransaction ft = fm.beginTransaction();
  1736. ft.addToBackStack(null);
  1737. dialog.setCancelable(false);
  1738. dialog.show(ft, CREDENTIALS_DIALOG_TAG);
  1739. if (!mIsFirstAuthAttempt) {
  1740. DisplayUtils.showSnackMessage(this, R.string.saml_authentication_wrong_pass);
  1741. } else {
  1742. mIsFirstAuthAttempt = false;
  1743. }
  1744. }
  1745. /**
  1746. * For retrieving the clicking on authentication cancel button.
  1747. */
  1748. public void doNegativeAuthenticationDialogClick() {
  1749. mIsFirstAuthAttempt = true;
  1750. }
  1751. @Override
  1752. protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
  1753. super.onActivityResult(requestCode, resultCode, data);
  1754. if (requestCode == REQUEST_CODE_QR_SCAN) {
  1755. if (data == null) {
  1756. return;
  1757. }
  1758. String result = data.getStringExtra("com.blikoon.qrcodescanner.got_qr_scan_relult");
  1759. if (result == null || !result.startsWith(getString(R.string.login_data_own_scheme))) {
  1760. mServerStatusIcon = R.drawable.ic_alert;
  1761. mServerStatusText = "QR Code could not be read!";
  1762. showServerStatus();
  1763. return;
  1764. }
  1765. if (!getResources().getBoolean(R.bool.multiaccount_support) &&
  1766. accountManager.getAccounts().length == 1) {
  1767. Toast.makeText(this, R.string.no_mutliple_accounts_allowed, Toast.LENGTH_LONG).show();
  1768. } else {
  1769. parseAndLoginFromWebView(result);
  1770. }
  1771. }
  1772. }
  1773. /**
  1774. * Obtain the X509Certificate from SslError
  1775. *
  1776. * @param error SslError
  1777. * @return X509Certificate from error
  1778. */
  1779. public static X509Certificate getX509CertificateFromError(SslError error) {
  1780. Bundle bundle = SslCertificate.saveState(error.getCertificate());
  1781. X509Certificate x509Certificate;
  1782. byte[] bytes = bundle.getByteArray("x509-certificate");
  1783. if (bytes == null) {
  1784. x509Certificate = null;
  1785. } else {
  1786. try {
  1787. CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
  1788. Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(bytes));
  1789. x509Certificate = (X509Certificate) cert;
  1790. } catch (CertificateException e) {
  1791. x509Certificate = null;
  1792. }
  1793. }
  1794. return x509Certificate;
  1795. }
  1796. /**
  1797. * Called from SslValidatorDialog when a new server certificate was correctly saved.
  1798. */
  1799. public void onSavedCertificate() {
  1800. checkOcServer();
  1801. }
  1802. /**
  1803. * Called from SslValidatorDialog when a new server certificate could not be saved when the user requested it.
  1804. */
  1805. @Override
  1806. public void onFailedSavingCertificate() {
  1807. DisplayUtils.showSnackMessage(this, R.string.ssl_validator_not_saved);
  1808. }
  1809. }