AuthenticatorActivity.java 91 KB

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