AuthenticatorActivity.java 81 KB

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