AuthenticatorActivity.java 81 KB

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