AuthenticatorActivity.java 90 KB

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