AuthenticatorActivity.java 85 KB

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