AuthenticatorActivity.java 73 KB

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