AuthenticatorActivity.java 81 KB

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