AuthenticatorActivity.java 93 KB

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