AuthenticatorActivity.java 92 KB

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