AuthenticatorActivity.java 92 KB

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