AuthenticatorActivity.java 97 KB

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