AuthenticatorActivity.java 91 KB

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