AuthenticatorActivity.java 83 KB

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