AuthenticatorActivity.java 82 KB

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