AuthenticatorActivity.java 84 KB

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