AuthenticatorActivity.java 81 KB

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