AuthenticatorActivity.java 93 KB

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