AuthenticatorActivity.java 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668
  1. /* ownCloud Android client application
  2. * Copyright (C) 2012 Bartek Przybylski
  3. * Copyright (C) 2012-2013 ownCloud Inc.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License version 2,
  7. * as published by the Free Software Foundation.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. *
  17. */
  18. package com.owncloud.android.authentication;
  19. import android.accounts.Account;
  20. import android.accounts.AccountManager;
  21. import android.app.AlertDialog;
  22. import android.app.Dialog;
  23. import android.app.ProgressDialog;
  24. import android.content.DialogInterface;
  25. import android.content.Intent;
  26. import android.content.SharedPreferences;
  27. import android.graphics.Rect;
  28. import android.graphics.drawable.Drawable;
  29. import android.net.Uri;
  30. import android.os.Bundle;
  31. import android.os.Handler;
  32. import android.preference.PreferenceManager;
  33. import android.support.v4.app.Fragment;
  34. import android.text.Editable;
  35. import android.text.InputType;
  36. import android.text.TextWatcher;
  37. import android.view.KeyEvent;
  38. import android.view.MotionEvent;
  39. import android.view.View;
  40. import android.view.View.OnFocusChangeListener;
  41. import android.view.View.OnTouchListener;
  42. import android.view.Window;
  43. import android.view.inputmethod.EditorInfo;
  44. import android.widget.Button;
  45. import android.widget.CheckBox;
  46. import android.widget.EditText;
  47. import android.widget.TextView;
  48. import android.widget.TextView.OnEditorActionListener;
  49. import com.actionbarsherlock.app.SherlockDialogFragment;
  50. import com.owncloud.android.MainApp;
  51. import com.owncloud.android.R;
  52. import com.owncloud.android.authentication.SsoWebViewClient.SsoWebViewClientListener;
  53. import com.owncloud.android.lib.common.accounts.AccountTypeUtils;
  54. import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;
  55. import com.owncloud.android.lib.common.OwnCloudClientFactory;
  56. import com.owncloud.android.lib.common.OwnCloudClient;
  57. import com.owncloud.android.operations.OAuth2GetAccessToken;
  58. import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
  59. import com.owncloud.android.lib.resources.status.GetRemoteStatusOperation;
  60. import com.owncloud.android.lib.common.operations.RemoteOperation;
  61. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  62. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  63. import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
  64. import com.owncloud.android.lib.resources.users.GetRemoteUserNameOperation;
  65. import com.owncloud.android.ui.dialog.SamlWebViewDialog;
  66. import com.owncloud.android.ui.dialog.SslValidatorDialog;
  67. import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;
  68. import com.owncloud.android.utils.Log_OC;
  69. import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  70. /**
  71. * This Activity is used to add an ownCloud account to the App
  72. *
  73. * @author Bartek Przybylski
  74. * @author David A. Velasco
  75. */
  76. public class AuthenticatorActivity extends AccountAuthenticatorActivity
  77. implements OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeListener, OnEditorActionListener, SsoWebViewClientListener{
  78. private static final String TAG = AuthenticatorActivity.class.getSimpleName();
  79. public static final String EXTRA_ACCOUNT = "ACCOUNT";
  80. public static final String EXTRA_USER_NAME = "USER_NAME";
  81. public static final String EXTRA_HOST_NAME = "HOST_NAME";
  82. public static final String EXTRA_ACTION = "ACTION";
  83. public static final String EXTRA_ENFORCED_UPDATE = "ENFORCE_UPDATE";
  84. private static final String KEY_AUTH_MESSAGE_VISIBILITY = "AUTH_MESSAGE_VISIBILITY";
  85. private static final String KEY_AUTH_MESSAGE_TEXT = "AUTH_MESSAGE_TEXT";
  86. private static final String KEY_HOST_URL_TEXT = "HOST_URL_TEXT";
  87. private static final String KEY_OC_VERSION = "OC_VERSION";
  88. private static final String KEY_OC_VERSION_STRING = "OC_VERSION_STRING";
  89. private static final String KEY_ACCOUNT = "ACCOUNT";
  90. private static final String KEY_SERVER_VALID = "SERVER_VALID";
  91. private static final String KEY_SERVER_CHECKED = "SERVER_CHECKED";
  92. private static final String KEY_SERVER_CHECK_IN_PROGRESS = "SERVER_CHECK_IN_PROGRESS";
  93. private static final String KEY_SERVER_STATUS_TEXT = "SERVER_STATUS_TEXT";
  94. private static final String KEY_SERVER_STATUS_ICON = "SERVER_STATUS_ICON";
  95. private static final String KEY_IS_SSL_CONN = "IS_SSL_CONN";
  96. private static final String KEY_PASSWORD_VISIBLE = "PASSWORD_VISIBLE";
  97. private static final String KEY_AUTH_STATUS_TEXT = "AUTH_STATUS_TEXT";
  98. private static final String KEY_AUTH_STATUS_ICON = "AUTH_STATUS_ICON";
  99. private static final String KEY_REFRESH_BUTTON_ENABLED = "KEY_REFRESH_BUTTON_ENABLED";
  100. //private static final String KEY_IS_SHARED_SUPPORTED = "KEY_IS_SHARE_SUPPORTED";
  101. private static final String AUTH_ON = "on";
  102. private static final String AUTH_OFF = "off";
  103. private static final String AUTH_OPTIONAL = "optional";
  104. private static final int DIALOG_LOGIN_PROGRESS = 0;
  105. private static final int DIALOG_SSL_VALIDATOR = 1;
  106. private static final int DIALOG_CERT_NOT_SAVED = 2;
  107. private static final int DIALOG_OAUTH2_LOGIN_PROGRESS = 3;
  108. public static final byte ACTION_CREATE = 0;
  109. public static final byte ACTION_UPDATE_TOKEN = 1;
  110. private static final String TAG_SAML_DIALOG = "samlWebViewDialog";
  111. private String mHostBaseUrl;
  112. private OwnCloudVersion mDiscoveredVersion;
  113. private String mAuthMessageText;
  114. private int mAuthMessageVisibility, mServerStatusText, mServerStatusIcon;
  115. private boolean mServerIsChecked, mServerIsValid, mIsSslConn;
  116. private int mAuthStatusText, mAuthStatusIcon;
  117. private TextView mAuthStatusLayout;
  118. private final Handler mHandler = new Handler();
  119. private Thread mOperationThread;
  120. private GetRemoteStatusOperation mOcServerChkOperation;
  121. private ExistenceCheckRemoteOperation mAuthCheckOperation;
  122. private RemoteOperationResult mLastSslUntrustedServerResult;
  123. private Uri mNewCapturedUriFromOAuth2Redirection;
  124. private AccountManager mAccountMgr;
  125. private boolean mJustCreated;
  126. private byte mAction;
  127. private Account mAccount;
  128. private TextView mAuthMessage;
  129. private EditText mHostUrlInput;
  130. private boolean mHostUrlInputEnabled;
  131. private View mRefreshButton;
  132. private String mAuthTokenType;
  133. private EditText mUsernameInput;
  134. private EditText mPasswordInput;
  135. private CheckBox mOAuth2Check;
  136. private TextView mOAuthAuthEndpointText;
  137. private TextView mOAuthTokenEndpointText;
  138. private SamlWebViewDialog mSamlDialog;
  139. private View mOkButton;
  140. private String mAuthToken;
  141. private boolean mResumed; // Control if activity is resumed
  142. /**
  143. * {@inheritDoc}
  144. *
  145. * IMPORTANT ENTRY POINT 1: activity is shown to the user
  146. */
  147. @Override
  148. protected void onCreate(Bundle savedInstanceState) {
  149. super.onCreate(savedInstanceState);
  150. getWindow().requestFeature(Window.FEATURE_NO_TITLE);
  151. /// set view and get references to view elements
  152. setContentView(R.layout.account_setup);
  153. mAuthMessage = (TextView) findViewById(R.id.auth_message);
  154. mHostUrlInput = (EditText) findViewById(R.id.hostUrlInput);
  155. mHostUrlInput.setText(getString(R.string.server_url)); // valid although R.string.server_url is an empty string
  156. mUsernameInput = (EditText) findViewById(R.id.account_username);
  157. mPasswordInput = (EditText) findViewById(R.id.account_password);
  158. mOAuthAuthEndpointText = (TextView)findViewById(R.id.oAuthEntryPoint_1);
  159. mOAuthTokenEndpointText = (TextView)findViewById(R.id.oAuthEntryPoint_2);
  160. mOAuth2Check = (CheckBox) findViewById(R.id.oauth_onOff_check);
  161. mOkButton = findViewById(R.id.buttonOK);
  162. mAuthStatusLayout = (TextView) findViewById(R.id.auth_status_text);
  163. /// set Host Url Input Enabled
  164. mHostUrlInputEnabled = getResources().getBoolean(R.bool.show_server_url_input);
  165. /// set visibility of link for new users
  166. boolean accountRegisterVisibility = getResources().getBoolean(R.bool.show_welcome_link);
  167. Button welcomeLink = (Button) findViewById(R.id.welcome_link);
  168. if (welcomeLink != null) {
  169. if (accountRegisterVisibility) {
  170. welcomeLink.setVisibility(View.VISIBLE);
  171. welcomeLink.setText(String.format(getString(R.string.auth_register), getString(R.string.app_name)));
  172. } else {
  173. findViewById(R.id.welcome_link).setVisibility(View.GONE);
  174. }
  175. }
  176. /// initialization
  177. mAccountMgr = AccountManager.get(this);
  178. mNewCapturedUriFromOAuth2Redirection = null;
  179. mAction = getIntent().getByteExtra(EXTRA_ACTION, ACTION_CREATE);
  180. mAccount = null;
  181. mHostBaseUrl = "";
  182. boolean refreshButtonEnabled = false;
  183. // URL input configuration applied
  184. if (!mHostUrlInputEnabled)
  185. {
  186. findViewById(R.id.hostUrlFrame).setVisibility(View.GONE);
  187. mRefreshButton = findViewById(R.id.centeredRefreshButton);
  188. } else {
  189. mRefreshButton = findViewById(R.id.embeddedRefreshButton);
  190. }
  191. if (savedInstanceState == null) {
  192. mResumed = false;
  193. /// connection state and info
  194. mAuthMessageVisibility = View.GONE;
  195. mServerStatusText = mServerStatusIcon = 0;
  196. mServerIsValid = false;
  197. mServerIsChecked = false;
  198. mIsSslConn = false;
  199. mAuthStatusText = mAuthStatusIcon = 0;
  200. /// retrieve extras from intent
  201. mAccount = getIntent().getExtras().getParcelable(EXTRA_ACCOUNT);
  202. if (mAccount != null) {
  203. String ocVersion = mAccountMgr.getUserData(mAccount, Constants.KEY_OC_VERSION);
  204. String ocVersionString = mAccountMgr.getUserData(mAccount, Constants.KEY_OC_VERSION_STRING);
  205. if (ocVersion != null) {
  206. mDiscoveredVersion = new OwnCloudVersion(ocVersion, ocVersionString);
  207. }
  208. mHostBaseUrl = normalizeUrl(mAccountMgr.getUserData(mAccount, Constants.KEY_OC_BASE_URL));
  209. mHostUrlInput.setText(mHostBaseUrl);
  210. String userName = mAccount.name.substring(0, mAccount.name.lastIndexOf('@'));
  211. mUsernameInput.setText(userName);
  212. }
  213. initAuthorizationMethod(); // checks intent and setup.xml to determine mCurrentAuthorizationMethod
  214. mJustCreated = true;
  215. if (mAction == ACTION_UPDATE_TOKEN || !mHostUrlInputEnabled) {
  216. checkOcServer();
  217. }
  218. } else {
  219. mResumed = true;
  220. /// connection state and info
  221. mAuthMessageVisibility = savedInstanceState.getInt(KEY_AUTH_MESSAGE_VISIBILITY);
  222. mAuthMessageText = savedInstanceState.getString(KEY_AUTH_MESSAGE_TEXT);
  223. mServerIsValid = savedInstanceState.getBoolean(KEY_SERVER_VALID);
  224. mServerIsChecked = savedInstanceState.getBoolean(KEY_SERVER_CHECKED);
  225. mServerStatusText = savedInstanceState.getInt(KEY_SERVER_STATUS_TEXT);
  226. mServerStatusIcon = savedInstanceState.getInt(KEY_SERVER_STATUS_ICON);
  227. mIsSslConn = savedInstanceState.getBoolean(KEY_IS_SSL_CONN);
  228. mAuthStatusText = savedInstanceState.getInt(KEY_AUTH_STATUS_TEXT);
  229. mAuthStatusIcon = savedInstanceState.getInt(KEY_AUTH_STATUS_ICON);
  230. if (savedInstanceState.getBoolean(KEY_PASSWORD_VISIBLE, false)) {
  231. showPassword();
  232. }
  233. /// server data
  234. String ocVersion = savedInstanceState.getString(KEY_OC_VERSION);
  235. String ocVersionString = savedInstanceState.getString(KEY_OC_VERSION_STRING);
  236. if (ocVersion != null) {
  237. mDiscoveredVersion = new OwnCloudVersion(ocVersion, ocVersionString);
  238. }
  239. mHostBaseUrl = savedInstanceState.getString(KEY_HOST_URL_TEXT);
  240. // account data, if updating
  241. mAccount = savedInstanceState.getParcelable(KEY_ACCOUNT);
  242. mAuthTokenType = savedInstanceState.getString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE);
  243. if (mAuthTokenType == null) {
  244. mAuthTokenType = AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());
  245. }
  246. // check if server check was interrupted by a configuration change
  247. if (savedInstanceState.getBoolean(KEY_SERVER_CHECK_IN_PROGRESS, false)) {
  248. checkOcServer();
  249. }
  250. // refresh button enabled
  251. refreshButtonEnabled = savedInstanceState.getBoolean(KEY_REFRESH_BUTTON_ENABLED);
  252. }
  253. if (mAuthMessageVisibility== View.VISIBLE) {
  254. showAuthMessage(mAuthMessageText);
  255. }
  256. else {
  257. hideAuthMessage();
  258. }
  259. adaptViewAccordingToAuthenticationMethod();
  260. showServerStatus();
  261. showAuthStatus();
  262. if (mAction == ACTION_UPDATE_TOKEN) {
  263. /// lock things that should not change
  264. mHostUrlInput.setEnabled(false);
  265. mHostUrlInput.setFocusable(false);
  266. mUsernameInput.setEnabled(false);
  267. mUsernameInput.setFocusable(false);
  268. mOAuth2Check.setVisibility(View.GONE);
  269. }
  270. //if (mServerIsChecked && !mServerIsValid && mRefreshButtonEnabled) showRefreshButton();
  271. if (mServerIsChecked && !mServerIsValid && refreshButtonEnabled) showRefreshButton();
  272. mOkButton.setEnabled(mServerIsValid); // state not automatically recovered in configuration changes
  273. if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType) ||
  274. !AUTH_OPTIONAL.equals(getString(R.string.auth_method_oauth2))) {
  275. mOAuth2Check.setVisibility(View.GONE);
  276. }
  277. mPasswordInput.setText(""); // clean password to avoid social hacking (disadvantage: password in removed if the device is turned aside)
  278. /// bind view elements to listeners and other friends
  279. mHostUrlInput.setOnFocusChangeListener(this);
  280. mHostUrlInput.setImeOptions(EditorInfo.IME_ACTION_NEXT);
  281. mHostUrlInput.setOnEditorActionListener(this);
  282. mHostUrlInput.addTextChangedListener(new TextWatcher() {
  283. @Override
  284. public void afterTextChanged(Editable s) {
  285. if (!mHostBaseUrl.equals(normalizeUrl(mHostUrlInput.getText().toString()))) {
  286. mOkButton.setEnabled(false);
  287. }
  288. }
  289. @Override
  290. public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  291. }
  292. @Override
  293. public void onTextChanged(CharSequence s, int start, int before, int count) {
  294. if (!mResumed) {
  295. mAuthStatusIcon = 0;
  296. mAuthStatusText = 0;
  297. showAuthStatus();
  298. }
  299. mResumed = false;
  300. }
  301. });
  302. mPasswordInput.setOnFocusChangeListener(this);
  303. mPasswordInput.setImeOptions(EditorInfo.IME_ACTION_DONE);
  304. mPasswordInput.setOnEditorActionListener(this);
  305. mPasswordInput.setOnTouchListener(new RightDrawableOnTouchListener() {
  306. @Override
  307. public boolean onDrawableTouch(final MotionEvent event) {
  308. if (event.getAction() == MotionEvent.ACTION_UP) {
  309. AuthenticatorActivity.this.onViewPasswordClick();
  310. }
  311. return true;
  312. }
  313. });
  314. findViewById(R.id.scroll).setOnTouchListener(new OnTouchListener() {
  315. @Override
  316. public boolean onTouch(View view, MotionEvent event) {
  317. if (event.getAction() == MotionEvent.ACTION_DOWN) {
  318. if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType) &&
  319. mHostUrlInput.hasFocus()) {
  320. checkOcServer();
  321. }
  322. }
  323. return false;
  324. }
  325. });
  326. }
  327. private void initAuthorizationMethod() {
  328. boolean oAuthRequired = false;
  329. boolean samlWebSsoRequired = false;
  330. mAuthTokenType = getIntent().getExtras().getString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE);
  331. mAccount = getIntent().getExtras().getParcelable(EXTRA_ACCOUNT);
  332. // TODO could be a good moment to validate the received token type, if not null
  333. if (mAuthTokenType == null) {
  334. if (mAccount != null) {
  335. /// same authentication method than the one used to create the account to update
  336. oAuthRequired = (mAccountMgr.getUserData(mAccount, Constants.KEY_SUPPORTS_OAUTH2) != null);
  337. samlWebSsoRequired = (mAccountMgr.getUserData(mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO) != null);
  338. } else {
  339. /// use the one set in setup.xml
  340. oAuthRequired = AUTH_ON.equals(getString(R.string.auth_method_oauth2));
  341. samlWebSsoRequired = AUTH_ON.equals(getString(R.string.auth_method_saml_web_sso));
  342. }
  343. if (oAuthRequired) {
  344. mAuthTokenType = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType());
  345. } else if (samlWebSsoRequired) {
  346. mAuthTokenType = AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType());
  347. } else {
  348. mAuthTokenType = AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());
  349. }
  350. }
  351. if (mAccount != null) {
  352. String userName = mAccount.name.substring(0, mAccount.name.lastIndexOf('@'));
  353. mUsernameInput.setText(userName);
  354. }
  355. mOAuth2Check.setChecked(AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType));
  356. }
  357. /**
  358. * Saves relevant state before {@link #onPause()}
  359. *
  360. * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag, intended to defer the
  361. * processing of the redirection caught in {@link #onNewIntent(Intent)} until {@link #onResume()}
  362. *
  363. * See {@link #loadSavedInstanceState(Bundle)}
  364. */
  365. @Override
  366. protected void onSaveInstanceState(Bundle outState) {
  367. super.onSaveInstanceState(outState);
  368. /// connection state and info
  369. outState.putInt(KEY_AUTH_MESSAGE_VISIBILITY, mAuthMessage.getVisibility());
  370. outState.putString(KEY_AUTH_MESSAGE_TEXT, mAuthMessage.getText().toString());
  371. outState.putInt(KEY_SERVER_STATUS_TEXT, mServerStatusText);
  372. outState.putInt(KEY_SERVER_STATUS_ICON, mServerStatusIcon);
  373. outState.putBoolean(KEY_SERVER_VALID, mServerIsValid);
  374. outState.putBoolean(KEY_SERVER_CHECKED, mServerIsChecked);
  375. outState.putBoolean(KEY_SERVER_CHECK_IN_PROGRESS, (!mServerIsValid && mOcServerChkOperation != null));
  376. outState.putBoolean(KEY_IS_SSL_CONN, mIsSslConn);
  377. outState.putBoolean(KEY_PASSWORD_VISIBLE, isPasswordVisible());
  378. outState.putInt(KEY_AUTH_STATUS_ICON, mAuthStatusIcon);
  379. outState.putInt(KEY_AUTH_STATUS_TEXT, mAuthStatusText);
  380. /// server data
  381. if (mDiscoveredVersion != null) {
  382. outState.putString(KEY_OC_VERSION, mDiscoveredVersion.getVersion());
  383. outState.putString(KEY_OC_VERSION_STRING, mDiscoveredVersion.getVersionString());
  384. }
  385. outState.putString(KEY_HOST_URL_TEXT, mHostBaseUrl);
  386. /// account data, if updating
  387. if (mAccount != null) {
  388. outState.putParcelable(KEY_ACCOUNT, mAccount);
  389. }
  390. outState.putString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE, mAuthTokenType);
  391. // refresh button enabled
  392. outState.putBoolean(KEY_REFRESH_BUTTON_ENABLED, (mRefreshButton.getVisibility() == View.VISIBLE));
  393. }
  394. /**
  395. * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION request
  396. * is caught here.
  397. *
  398. * To make this possible, this activity needs to be qualified with android:launchMode = "singleTask" in the
  399. * AndroidManifest.xml file.
  400. */
  401. @Override
  402. protected void onNewIntent (Intent intent) {
  403. Log_OC.d(TAG, "onNewIntent()");
  404. Uri data = intent.getData();
  405. if (data != null && data.toString().startsWith(getString(R.string.oauth2_redirect_uri))) {
  406. mNewCapturedUriFromOAuth2Redirection = data;
  407. }
  408. }
  409. /**
  410. * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION, and
  411. * deferred in {@link #onNewIntent(Intent)}, is processed here.
  412. */
  413. @Override
  414. protected void onResume() {
  415. super.onResume();
  416. if (mAction == ACTION_UPDATE_TOKEN && mJustCreated && getIntent().getBooleanExtra(EXTRA_ENFORCED_UPDATE, false)) {
  417. if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType)) {
  418. //Toast.makeText(this, R.string.auth_expired_oauth_token_toast, Toast.LENGTH_LONG).show();
  419. showAuthMessage(getString(R.string.auth_expired_oauth_token_toast));
  420. } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {
  421. //Toast.makeText(this, R.string.auth_expired_saml_sso_token_toast, Toast.LENGTH_LONG).show();
  422. showAuthMessage(getString(R.string.auth_expired_saml_sso_token_toast));
  423. } else {
  424. //Toast.makeText(this, R.string.auth_expired_basic_auth_toast, Toast.LENGTH_LONG).show();
  425. showAuthMessage(getString(R.string.auth_expired_basic_auth_toast));
  426. }
  427. }
  428. if (mNewCapturedUriFromOAuth2Redirection != null) {
  429. getOAuth2AccessTokenFromCapturedRedirection();
  430. }
  431. mJustCreated = false;
  432. }
  433. /**
  434. * Parses the redirection with the response to the GET AUTHORIZATION request to the
  435. * oAuth server and requests for the access token (GET ACCESS TOKEN)
  436. */
  437. private void getOAuth2AccessTokenFromCapturedRedirection() {
  438. /// Parse data from OAuth redirection
  439. String queryParameters = mNewCapturedUriFromOAuth2Redirection.getQuery();
  440. mNewCapturedUriFromOAuth2Redirection = null;
  441. /// Showing the dialog with instructions for the user.
  442. showDialog(DIALOG_OAUTH2_LOGIN_PROGRESS);
  443. /// GET ACCESS TOKEN to the oAuth server
  444. RemoteOperation operation = new OAuth2GetAccessToken( getString(R.string.oauth2_client_id),
  445. getString(R.string.oauth2_redirect_uri),
  446. getString(R.string.oauth2_grant_type),
  447. queryParameters);
  448. //OwnCloudClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(getString(R.string.oauth2_url_endpoint_access)), getApplicationContext());
  449. OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(mOAuthTokenEndpointText.getText().toString().trim()), getApplicationContext(), true);
  450. operation.execute(client, this, mHandler);
  451. }
  452. /**
  453. * Handles the change of focus on the text inputs for the server URL and the password
  454. */
  455. public void onFocusChange(View view, boolean hasFocus) {
  456. if (view.getId() == R.id.hostUrlInput) {
  457. if (!hasFocus) {
  458. onUrlInputFocusLost((TextView) view);
  459. }
  460. else {
  461. hideRefreshButton();
  462. }
  463. } else if (view.getId() == R.id.account_password) {
  464. onPasswordFocusChanged((TextView) view, hasFocus);
  465. }
  466. }
  467. /**
  468. * Handles changes in focus on the text input for the server URL.
  469. *
  470. * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
  471. * other field. The operation to check the existence of the server in the entered URL is
  472. * started.
  473. *
  474. * When hasFocus: user 'comes back' to write again the server URL.
  475. *
  476. * @param hostInput TextView with the URL input field receiving the change of focus.
  477. */
  478. private void onUrlInputFocusLost(TextView hostInput) {
  479. if (!mHostBaseUrl.equals(normalizeUrl(mHostUrlInput.getText().toString()))) {
  480. checkOcServer();
  481. } else {
  482. mOkButton.setEnabled(mServerIsValid);
  483. if (!mServerIsValid) {
  484. showRefreshButton();
  485. }
  486. }
  487. }
  488. private void checkOcServer() {
  489. String uri = trimUrlWebdav(mHostUrlInput.getText().toString().trim());
  490. if (!mHostUrlInputEnabled){
  491. uri = getString(R.string.server_url);
  492. }
  493. mServerIsValid = false;
  494. mServerIsChecked = false;
  495. mOkButton.setEnabled(false);
  496. mDiscoveredVersion = null;
  497. hideRefreshButton();
  498. if (uri.length() != 0) {
  499. mServerStatusText = R.string.auth_testing_connection;
  500. mServerStatusIcon = R.drawable.progress_small;
  501. showServerStatus();
  502. mOcServerChkOperation = new GetRemoteStatusOperation(uri, this);
  503. OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(uri), this, true);
  504. mOperationThread = mOcServerChkOperation.execute(client, this, mHandler);
  505. } else {
  506. mServerStatusText = 0;
  507. mServerStatusIcon = 0;
  508. showServerStatus();
  509. }
  510. }
  511. /**
  512. * Handles changes in focus on the text input for the password (basic authorization).
  513. *
  514. * When (hasFocus), the button to toggle password visibility is shown.
  515. *
  516. * When (!hasFocus), the button is made invisible and the password is hidden.
  517. *
  518. * @param passwordInput TextView with the password input field receiving the change of focus.
  519. * @param hasFocus 'True' if focus is received, 'false' if is lost
  520. */
  521. private void onPasswordFocusChanged(TextView passwordInput, boolean hasFocus) {
  522. if (hasFocus) {
  523. showViewPasswordButton();
  524. } else {
  525. hidePassword();
  526. hidePasswordButton();
  527. }
  528. }
  529. private void showViewPasswordButton() {
  530. //int drawable = android.R.drawable.ic_menu_view;
  531. int drawable = R.drawable.ic_view;
  532. if (isPasswordVisible()) {
  533. //drawable = android.R.drawable.ic_secure;
  534. drawable = R.drawable.ic_hide;
  535. }
  536. mPasswordInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable, 0);
  537. }
  538. private boolean isPasswordVisible() {
  539. return ((mPasswordInput.getInputType() & InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
  540. }
  541. private void hidePasswordButton() {
  542. mPasswordInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
  543. }
  544. private void showPassword() {
  545. mPasswordInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
  546. showViewPasswordButton();
  547. }
  548. private void hidePassword() {
  549. mPasswordInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
  550. showViewPasswordButton();
  551. }
  552. /**
  553. * Cancels the authenticator activity
  554. *
  555. * IMPORTANT ENTRY POINT 3: Never underestimate the importance of cancellation
  556. *
  557. * This method is bound in the layout/acceoun_setup.xml resource file.
  558. *
  559. * @param view Cancel button
  560. */
  561. public void onCancelClick(View view) {
  562. setResult(RESULT_CANCELED); // TODO review how is this related to AccountAuthenticator (debugging)
  563. finish();
  564. }
  565. /**
  566. * Checks the credentials of the user in the root of the ownCloud server
  567. * before creating a new local account.
  568. *
  569. * For basic authorization, a check of existence of the root folder is
  570. * performed.
  571. *
  572. * For OAuth, starts the flow to get an access token; the credentials test
  573. * is postponed until it is available.
  574. *
  575. * IMPORTANT ENTRY POINT 4
  576. *
  577. * @param view OK button
  578. */
  579. public void onOkClick(View view) {
  580. // this check should be unnecessary
  581. if (mDiscoveredVersion == null || !mDiscoveredVersion.isVersionValid() || mHostBaseUrl == null || mHostBaseUrl.length() == 0) {
  582. mServerStatusIcon = R.drawable.common_error;
  583. mServerStatusText = R.string.auth_wtf_reenter_URL;
  584. showServerStatus();
  585. mOkButton.setEnabled(false);
  586. Log_OC.wtf(TAG, "The user was allowed to click 'connect' to an unchecked server!!");
  587. return;
  588. }
  589. if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType)) {
  590. startOauthorization();
  591. } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {
  592. startSamlBasedFederatedSingleSignOnAuthorization();
  593. } else {
  594. checkBasicAuthorization();
  595. }
  596. }
  597. /**
  598. * Tests the credentials entered by the user performing a check of existence on
  599. * the root folder of the ownCloud server.
  600. */
  601. private void checkBasicAuthorization() {
  602. /// get the path to the root folder through WebDAV from the version server
  603. String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, mAuthTokenType);
  604. /// get basic credentials entered by user
  605. String username = mUsernameInput.getText().toString();
  606. String password = mPasswordInput.getText().toString();
  607. /// be gentle with the user
  608. showDialog(DIALOG_LOGIN_PROGRESS);
  609. /// test credentials accessing the root folder
  610. mAuthCheckOperation = new ExistenceCheckRemoteOperation("", this, false);
  611. OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this, true);
  612. client.setBasicCredentials(username, password);
  613. mOperationThread = mAuthCheckOperation.execute(client, this, mHandler);
  614. }
  615. /**
  616. * Starts the OAuth 'grant type' flow to get an access token, with
  617. * a GET AUTHORIZATION request to the BUILT-IN authorization server.
  618. */
  619. private void startOauthorization() {
  620. // be gentle with the user
  621. mAuthStatusIcon = R.drawable.progress_small;
  622. mAuthStatusText = R.string.oauth_login_connection;
  623. showAuthStatus();
  624. // GET AUTHORIZATION request
  625. //Uri uri = Uri.parse(getString(R.string.oauth2_url_endpoint_auth));
  626. Uri uri = Uri.parse(mOAuthAuthEndpointText.getText().toString().trim());
  627. Uri.Builder uriBuilder = uri.buildUpon();
  628. uriBuilder.appendQueryParameter(OAuth2Constants.KEY_RESPONSE_TYPE, getString(R.string.oauth2_response_type));
  629. uriBuilder.appendQueryParameter(OAuth2Constants.KEY_REDIRECT_URI, getString(R.string.oauth2_redirect_uri));
  630. uriBuilder.appendQueryParameter(OAuth2Constants.KEY_CLIENT_ID, getString(R.string.oauth2_client_id));
  631. uriBuilder.appendQueryParameter(OAuth2Constants.KEY_SCOPE, getString(R.string.oauth2_scope));
  632. //uriBuilder.appendQueryParameter(OAuth2Constants.KEY_STATE, whateverwewant);
  633. uri = uriBuilder.build();
  634. Log_OC.d(TAG, "Starting browser to view " + uri.toString());
  635. Intent i = new Intent(Intent.ACTION_VIEW, uri);
  636. startActivity(i);
  637. }
  638. /**
  639. * Starts the Web Single Sign On flow to get access to the root folder
  640. * in the server.
  641. */
  642. private void startSamlBasedFederatedSingleSignOnAuthorization() {
  643. // be gentle with the user
  644. mAuthStatusIcon = R.drawable.progress_small;
  645. mAuthStatusText = R.string.auth_connecting_auth_server;
  646. showAuthStatus();
  647. showDialog(DIALOG_LOGIN_PROGRESS);
  648. /// get the path to the root folder through WebDAV from the version server
  649. String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, mAuthTokenType);
  650. /// test credentials accessing the root folder
  651. mAuthCheckOperation = new ExistenceCheckRemoteOperation("", this, false);
  652. OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this, false);
  653. mOperationThread = mAuthCheckOperation.execute(client, this, mHandler);
  654. }
  655. /**
  656. * Callback method invoked when a RemoteOperation executed by this Activity finishes.
  657. *
  658. * Dispatches the operation flow to the right method.
  659. */
  660. @Override
  661. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  662. if (operation instanceof GetRemoteStatusOperation) {
  663. onOcServerCheckFinish((GetRemoteStatusOperation) operation, result);
  664. } else if (operation instanceof OAuth2GetAccessToken) {
  665. onGetOAuthAccessTokenFinish((OAuth2GetAccessToken)operation, result);
  666. } else if (operation instanceof ExistenceCheckRemoteOperation) {
  667. if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {
  668. onSamlBasedFederatedSingleSignOnAuthorizationStart(operation, result);
  669. } else {
  670. onAuthorizationCheckFinish((ExistenceCheckRemoteOperation)operation, result);
  671. }
  672. } else if (operation instanceof GetRemoteUserNameOperation) {
  673. onGetUserNameFinish((GetRemoteUserNameOperation) operation, result);
  674. }
  675. }
  676. private void onGetUserNameFinish(GetRemoteUserNameOperation operation, RemoteOperationResult result) {
  677. if (result.isSuccess()) {
  678. boolean success = false;
  679. String username = operation.getUserName();
  680. if ( mAction == ACTION_CREATE) {
  681. mUsernameInput.setText(username);
  682. success = createAccount();
  683. } else {
  684. if (!mUsernameInput.getText().toString().equals(username)) {
  685. // fail - not a new account, but an existing one; disallow
  686. result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_THE_SAME);
  687. updateAuthStatusIconAndText(result);
  688. showAuthStatus();
  689. Log_OC.d(TAG, result.getLogMessage());
  690. } else {
  691. updateToken();
  692. success = true;
  693. }
  694. }
  695. if (success)
  696. finish();
  697. } else {
  698. updateAuthStatusIconAndText(result);
  699. showAuthStatus();
  700. Log_OC.e(TAG, "Access to user name failed: " + result.getLogMessage());
  701. }
  702. }
  703. private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperation operation, RemoteOperationResult result) {
  704. try {
  705. dismissDialog(DIALOG_LOGIN_PROGRESS);
  706. } catch (IllegalArgumentException e) {
  707. // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
  708. }
  709. //if (result.isTemporalRedirection() && result.isIdPRedirection()) {
  710. if (result.isIdPRedirection()) {
  711. String url = result.getRedirectedLocation();
  712. String targetUrl = mHostBaseUrl + AccountUtils.getWebdavPath(mDiscoveredVersion, mAuthTokenType);
  713. // Show dialog
  714. mSamlDialog = SamlWebViewDialog.newInstance(url, targetUrl);
  715. mSamlDialog.show(getSupportFragmentManager(), TAG_SAML_DIALOG);
  716. mAuthStatusIcon = 0;
  717. mAuthStatusText = 0;
  718. } else {
  719. mAuthStatusIcon = R.drawable.common_error;
  720. mAuthStatusText = R.string.auth_unsupported_auth_method;
  721. }
  722. showAuthStatus();
  723. }
  724. /**
  725. * Processes the result of the server check performed when the user finishes the enter of the
  726. * server URL.
  727. *
  728. * @param operation Server check performed.
  729. * @param result Result of the check.
  730. */
  731. private void onOcServerCheckFinish(GetRemoteStatusOperation operation, RemoteOperationResult result) {
  732. if (operation.equals(mOcServerChkOperation)) {
  733. /// save result state
  734. mServerIsChecked = true;
  735. mServerIsValid = result.isSuccess();
  736. mIsSslConn = (result.getCode() == ResultCode.OK_SSL);
  737. mOcServerChkOperation = null;
  738. /// update status icon and text
  739. if (mServerIsValid) {
  740. hideRefreshButton();
  741. } else {
  742. showRefreshButton();
  743. }
  744. updateServerStatusIconAndText(result);
  745. showServerStatus();
  746. /// very special case (TODO: move to a common place for all the remote operations)
  747. if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
  748. mLastSslUntrustedServerResult = result;
  749. showDialog(DIALOG_SSL_VALIDATOR);
  750. }
  751. /// retrieve discovered version and normalize server URL
  752. mDiscoveredVersion = operation.getDiscoveredVersion();
  753. mHostBaseUrl = normalizeUrl(mHostUrlInput.getText().toString());
  754. /// allow or not the user try to access the server
  755. mOkButton.setEnabled(mServerIsValid);
  756. } // else nothing ; only the last check operation is considered;
  757. // multiple can be triggered if the user amends a URL before a previous check can be triggered
  758. }
  759. private String normalizeUrl(String url) {
  760. if (url != null && url.length() > 0) {
  761. url = url.trim();
  762. if (!url.toLowerCase().startsWith("http://") &&
  763. !url.toLowerCase().startsWith("https://")) {
  764. if (mIsSslConn) {
  765. url = "https://" + url;
  766. } else {
  767. url = "http://" + url;
  768. }
  769. }
  770. // OC-208: Add suffix remote.php/webdav to normalize (OC-34)
  771. url = trimUrlWebdav(url);
  772. if (url.endsWith("/")) {
  773. url = url.substring(0, url.length() - 1);
  774. }
  775. }
  776. return (url != null ? url : "");
  777. }
  778. private String trimUrlWebdav(String url){
  779. if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0)){
  780. url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0.length());
  781. } else if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_2_0)){
  782. url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_2_0.length());
  783. } else if (url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_1_2)){
  784. url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_1_2.length());
  785. }
  786. return (url != null ? url : "");
  787. }
  788. /**
  789. * Chooses the right icon and text to show to the user for the received operation result.
  790. *
  791. * @param result Result of a remote operation performed in this activity
  792. */
  793. private void updateServerStatusIconAndText(RemoteOperationResult result) {
  794. mServerStatusIcon = R.drawable.common_error; // the most common case in the switch below
  795. switch (result.getCode()) {
  796. case OK_SSL:
  797. mServerStatusIcon = android.R.drawable.ic_secure;
  798. mServerStatusText = R.string.auth_secure_connection;
  799. break;
  800. case OK_NO_SSL:
  801. case OK:
  802. if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://") ) {
  803. mServerStatusText = R.string.auth_connection_established;
  804. mServerStatusIcon = R.drawable.ic_ok;
  805. } else {
  806. mServerStatusText = R.string.auth_nossl_plain_ok_title;
  807. mServerStatusIcon = android.R.drawable.ic_partial_secure;
  808. }
  809. break;
  810. case NO_NETWORK_CONNECTION:
  811. mServerStatusIcon = R.drawable.no_network;
  812. mServerStatusText = R.string.auth_no_net_conn_title;
  813. break;
  814. case SSL_RECOVERABLE_PEER_UNVERIFIED:
  815. mServerStatusText = R.string.auth_ssl_unverified_server_title;
  816. break;
  817. case BAD_OC_VERSION:
  818. mServerStatusText = R.string.auth_bad_oc_version_title;
  819. break;
  820. case WRONG_CONNECTION:
  821. mServerStatusText = R.string.auth_wrong_connection_title;
  822. break;
  823. case TIMEOUT:
  824. mServerStatusText = R.string.auth_timeout_title;
  825. break;
  826. case INCORRECT_ADDRESS:
  827. mServerStatusText = R.string.auth_incorrect_address_title;
  828. break;
  829. case SSL_ERROR:
  830. mServerStatusText = R.string.auth_ssl_general_error_title;
  831. break;
  832. case UNAUTHORIZED:
  833. mServerStatusText = R.string.auth_unauthorized;
  834. break;
  835. case HOST_NOT_AVAILABLE:
  836. mServerStatusText = R.string.auth_unknown_host_title;
  837. break;
  838. case INSTANCE_NOT_CONFIGURED:
  839. mServerStatusText = R.string.auth_not_configured_title;
  840. break;
  841. case FILE_NOT_FOUND:
  842. mServerStatusText = R.string.auth_incorrect_path_title;
  843. break;
  844. case OAUTH2_ERROR:
  845. mServerStatusText = R.string.auth_oauth_error;
  846. break;
  847. case OAUTH2_ERROR_ACCESS_DENIED:
  848. mServerStatusText = R.string.auth_oauth_error_access_denied;
  849. break;
  850. case UNHANDLED_HTTP_CODE:
  851. case UNKNOWN_ERROR:
  852. mServerStatusText = R.string.auth_unknown_error_title;
  853. break;
  854. default:
  855. mServerStatusText = 0;
  856. mServerStatusIcon = 0;
  857. }
  858. }
  859. /**
  860. * Chooses the right icon and text to show to the user for the received operation result.
  861. *
  862. * @param result Result of a remote operation performed in this activity
  863. */
  864. private void updateAuthStatusIconAndText(RemoteOperationResult result) {
  865. mAuthStatusIcon = R.drawable.common_error; // the most common case in the switch below
  866. switch (result.getCode()) {
  867. case OK_SSL:
  868. mAuthStatusIcon = android.R.drawable.ic_secure;
  869. mAuthStatusText = R.string.auth_secure_connection;
  870. break;
  871. case OK_NO_SSL:
  872. case OK:
  873. if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://") ) {
  874. mAuthStatusText = R.string.auth_connection_established;
  875. mAuthStatusIcon = R.drawable.ic_ok;
  876. } else {
  877. mAuthStatusText = R.string.auth_nossl_plain_ok_title;
  878. mAuthStatusIcon = android.R.drawable.ic_partial_secure;
  879. }
  880. break;
  881. case NO_NETWORK_CONNECTION:
  882. mAuthStatusIcon = R.drawable.no_network;
  883. mAuthStatusText = R.string.auth_no_net_conn_title;
  884. break;
  885. case SSL_RECOVERABLE_PEER_UNVERIFIED:
  886. mAuthStatusText = R.string.auth_ssl_unverified_server_title;
  887. break;
  888. case BAD_OC_VERSION:
  889. mAuthStatusText = R.string.auth_bad_oc_version_title;
  890. break;
  891. case WRONG_CONNECTION:
  892. mAuthStatusText = R.string.auth_wrong_connection_title;
  893. break;
  894. case TIMEOUT:
  895. mAuthStatusText = R.string.auth_timeout_title;
  896. break;
  897. case INCORRECT_ADDRESS:
  898. mAuthStatusText = R.string.auth_incorrect_address_title;
  899. break;
  900. case SSL_ERROR:
  901. mAuthStatusText = R.string.auth_ssl_general_error_title;
  902. break;
  903. case UNAUTHORIZED:
  904. mAuthStatusText = R.string.auth_unauthorized;
  905. break;
  906. case HOST_NOT_AVAILABLE:
  907. mAuthStatusText = R.string.auth_unknown_host_title;
  908. break;
  909. case INSTANCE_NOT_CONFIGURED:
  910. mAuthStatusText = R.string.auth_not_configured_title;
  911. break;
  912. case FILE_NOT_FOUND:
  913. mAuthStatusText = R.string.auth_incorrect_path_title;
  914. break;
  915. case OAUTH2_ERROR:
  916. mAuthStatusText = R.string.auth_oauth_error;
  917. break;
  918. case OAUTH2_ERROR_ACCESS_DENIED:
  919. mAuthStatusText = R.string.auth_oauth_error_access_denied;
  920. break;
  921. case ACCOUNT_NOT_NEW:
  922. mAuthStatusText = R.string.auth_account_not_new;
  923. break;
  924. case ACCOUNT_NOT_THE_SAME:
  925. mAuthStatusText = R.string.auth_account_not_the_same;
  926. break;
  927. case UNHANDLED_HTTP_CODE:
  928. case UNKNOWN_ERROR:
  929. mAuthStatusText = R.string.auth_unknown_error_title;
  930. break;
  931. default:
  932. mAuthStatusText = 0;
  933. mAuthStatusIcon = 0;
  934. }
  935. }
  936. /**
  937. * Processes the result of the request for and access token send
  938. * to an OAuth authorization server.
  939. *
  940. * @param operation Operation performed requesting the access token.
  941. * @param result Result of the operation.
  942. */
  943. private void onGetOAuthAccessTokenFinish(OAuth2GetAccessToken operation, RemoteOperationResult result) {
  944. try {
  945. dismissDialog(DIALOG_OAUTH2_LOGIN_PROGRESS);
  946. } catch (IllegalArgumentException e) {
  947. // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
  948. }
  949. String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, mAuthTokenType);
  950. if (result.isSuccess() && webdav_path != null) {
  951. /// be gentle with the user
  952. showDialog(DIALOG_LOGIN_PROGRESS);
  953. /// time to test the retrieved access token on the ownCloud server
  954. mAuthToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Constants.KEY_ACCESS_TOKEN);
  955. Log_OC.d(TAG, "Got ACCESS TOKEN: " + mAuthToken);
  956. mAuthCheckOperation = new ExistenceCheckRemoteOperation("", this, false);
  957. OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this, true);
  958. client.setBearerCredentials(mAuthToken);
  959. mAuthCheckOperation.execute(client, this, mHandler);
  960. } else {
  961. updateAuthStatusIconAndText(result);
  962. showAuthStatus();
  963. Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
  964. }
  965. }
  966. /**
  967. * Processes the result of the access check performed to try the user credentials.
  968. *
  969. * Creates a new account through the AccountManager.
  970. *
  971. * @param operation Access check performed.
  972. * @param result Result of the operation.
  973. */
  974. private void onAuthorizationCheckFinish(ExistenceCheckRemoteOperation operation, RemoteOperationResult result) {
  975. try {
  976. dismissDialog(DIALOG_LOGIN_PROGRESS);
  977. } catch (IllegalArgumentException e) {
  978. // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
  979. }
  980. if (result.isSuccess()) {
  981. Log_OC.d(TAG, "Successful access - time to save the account");
  982. boolean success = false;
  983. if (mAction == ACTION_CREATE) {
  984. success = createAccount();
  985. } else {
  986. updateToken();
  987. success = true;
  988. }
  989. if (success) {
  990. finish();
  991. }
  992. } else if (result.isServerFail() || result.isException()) {
  993. /// if server fail or exception in authorization, the UI is updated as when a server check failed
  994. mServerIsChecked = true;
  995. mServerIsValid = false;
  996. mIsSslConn = false;
  997. mOcServerChkOperation = null;
  998. mDiscoveredVersion = null;
  999. mHostBaseUrl = normalizeUrl(mHostUrlInput.getText().toString());
  1000. // update status icon and text
  1001. updateServerStatusIconAndText(result);
  1002. showServerStatus();
  1003. mAuthStatusIcon = 0;
  1004. mAuthStatusText = 0;
  1005. showAuthStatus();
  1006. // update input controls state
  1007. showRefreshButton();
  1008. mOkButton.setEnabled(false);
  1009. // very special case (TODO: move to a common place for all the remote operations) (dangerous here?)
  1010. if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
  1011. mLastSslUntrustedServerResult = result;
  1012. showDialog(DIALOG_SSL_VALIDATOR);
  1013. }
  1014. } else { // authorization fail due to client side - probably wrong credentials
  1015. updateAuthStatusIconAndText(result);
  1016. showAuthStatus();
  1017. Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
  1018. }
  1019. }
  1020. /**
  1021. * Sets the proper response to get that the Account Authenticator that started this activity saves
  1022. * a new authorization token for mAccount.
  1023. */
  1024. private void updateToken() {
  1025. Bundle response = new Bundle();
  1026. response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
  1027. response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);
  1028. if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType)) {
  1029. response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
  1030. // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
  1031. mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
  1032. } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {
  1033. response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
  1034. // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
  1035. mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
  1036. } else {
  1037. response.putString(AccountManager.KEY_AUTHTOKEN, mPasswordInput.getText().toString());
  1038. mAccountMgr.setPassword(mAccount, mPasswordInput.getText().toString());
  1039. }
  1040. setAccountAuthenticatorResult(response);
  1041. }
  1042. /**
  1043. * Creates a new account through the Account Authenticator that started this activity.
  1044. *
  1045. * This makes the account permanent.
  1046. *
  1047. * TODO Decide how to name the OAuth accounts
  1048. */
  1049. private boolean createAccount() {
  1050. /// create and save new ownCloud account
  1051. boolean isOAuth = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType);
  1052. boolean isSaml = AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType);
  1053. Uri uri = Uri.parse(mHostBaseUrl);
  1054. String username = mUsernameInput.getText().toString().trim();
  1055. if (isOAuth) {
  1056. username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();
  1057. }
  1058. String accountName = username + "@" + uri.getHost();
  1059. if (uri.getPort() >= 0) {
  1060. accountName += ":" + uri.getPort();
  1061. }
  1062. mAccount = new Account(accountName, MainApp.getAccountType());
  1063. if (AccountUtils.exists(mAccount, getApplicationContext())) {
  1064. // fail - not a new account, but an existing one; disallow
  1065. RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW);
  1066. updateAuthStatusIconAndText(result);
  1067. showAuthStatus();
  1068. Log_OC.d(TAG, result.getLogMessage());
  1069. return false;
  1070. } else {
  1071. if (isOAuth || isSaml) {
  1072. mAccountMgr.addAccountExplicitly(mAccount, "", null); // with external authorizations, the password is never input in the app
  1073. } else {
  1074. mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);
  1075. }
  1076. /// add the new account as default in preferences, if there is none already
  1077. Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
  1078. if (defaultAccount == null) {
  1079. SharedPreferences.Editor editor = PreferenceManager
  1080. .getDefaultSharedPreferences(this).edit();
  1081. editor.putString("select_oc_account", accountName);
  1082. editor.commit();
  1083. }
  1084. /// prepare result to return to the Authenticator
  1085. // TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done
  1086. final Intent intent = new Intent();
  1087. intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, MainApp.getAccountType());
  1088. intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
  1089. /*if (!isOAuth)
  1090. intent.putExtra(AccountManager.KEY_AUTHTOKEN, MainApp.getAccountType()); */
  1091. intent.putExtra(AccountManager.KEY_USERDATA, username);
  1092. if (isOAuth || isSaml) {
  1093. mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
  1094. }
  1095. /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
  1096. mAccountMgr.setUserData(mAccount, Constants.KEY_OC_VERSION, mDiscoveredVersion.getVersion());
  1097. mAccountMgr.setUserData(mAccount, Constants.KEY_OC_VERSION_STRING, mDiscoveredVersion.getVersionString());
  1098. mAccountMgr.setUserData(mAccount, Constants.KEY_OC_BASE_URL, mHostBaseUrl);
  1099. if (isSaml) {
  1100. mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE");
  1101. } else if (isOAuth) {
  1102. mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_OAUTH2, "TRUE");
  1103. }
  1104. setAccountAuthenticatorResult(intent.getExtras());
  1105. setResult(RESULT_OK, intent);
  1106. return true;
  1107. }
  1108. }
  1109. /**
  1110. * {@inheritDoc}
  1111. *
  1112. * Necessary to update the contents of the SSL Dialog
  1113. *
  1114. * TODO move to some common place for all possible untrusted SSL failures
  1115. */
  1116. @Override
  1117. protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
  1118. switch (id) {
  1119. case DIALOG_LOGIN_PROGRESS:
  1120. case DIALOG_CERT_NOT_SAVED:
  1121. case DIALOG_OAUTH2_LOGIN_PROGRESS:
  1122. break;
  1123. case DIALOG_SSL_VALIDATOR: {
  1124. ((SslValidatorDialog)dialog).updateResult(mLastSslUntrustedServerResult);
  1125. break;
  1126. }
  1127. default:
  1128. Log_OC.e(TAG, "Incorrect dialog called with id = " + id);
  1129. }
  1130. }
  1131. /**
  1132. * {@inheritDoc}
  1133. */
  1134. @Override
  1135. protected Dialog onCreateDialog(int id) {
  1136. Dialog dialog = null;
  1137. switch (id) {
  1138. case DIALOG_LOGIN_PROGRESS: {
  1139. /// simple progress dialog
  1140. ProgressDialog working_dialog = new ProgressDialog(this);
  1141. working_dialog.setMessage(getResources().getString(R.string.auth_trying_to_login));
  1142. working_dialog.setIndeterminate(true);
  1143. working_dialog.setCancelable(true);
  1144. working_dialog
  1145. .setOnCancelListener(new DialogInterface.OnCancelListener() {
  1146. @Override
  1147. public void onCancel(DialogInterface dialog) {
  1148. /// TODO study if this is enough
  1149. Log_OC.i(TAG, "Login canceled");
  1150. if (mOperationThread != null) {
  1151. mOperationThread.interrupt();
  1152. finish();
  1153. }
  1154. }
  1155. });
  1156. dialog = working_dialog;
  1157. break;
  1158. }
  1159. case DIALOG_OAUTH2_LOGIN_PROGRESS: {
  1160. ProgressDialog working_dialog = new ProgressDialog(this);
  1161. working_dialog.setMessage(String.format("Getting authorization"));
  1162. working_dialog.setIndeterminate(true);
  1163. working_dialog.setCancelable(true);
  1164. working_dialog
  1165. .setOnCancelListener(new DialogInterface.OnCancelListener() {
  1166. @Override
  1167. public void onCancel(DialogInterface dialog) {
  1168. Log_OC.i(TAG, "Login canceled");
  1169. finish();
  1170. }
  1171. });
  1172. dialog = working_dialog;
  1173. break;
  1174. }
  1175. case DIALOG_SSL_VALIDATOR: {
  1176. /// TODO start to use new dialog interface, at least for this (it is a FragmentDialog already)
  1177. dialog = SslValidatorDialog.newInstance(this, mLastSslUntrustedServerResult, this);
  1178. break;
  1179. }
  1180. case DIALOG_CERT_NOT_SAVED: {
  1181. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  1182. builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
  1183. builder.setCancelable(false);
  1184. builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
  1185. @Override
  1186. public void onClick(DialogInterface dialog, int which) {
  1187. dialog.dismiss();
  1188. };
  1189. });
  1190. dialog = builder.create();
  1191. break;
  1192. }
  1193. default:
  1194. Log_OC.e(TAG, "Incorrect dialog called with id = " + id);
  1195. }
  1196. return dialog;
  1197. }
  1198. /**
  1199. * Starts and activity to open the 'new account' page in the ownCloud web site
  1200. *
  1201. * @param view 'Account register' button
  1202. */
  1203. public void onRegisterClick(View view) {
  1204. Intent register = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.welcome_link_url)));
  1205. setResult(RESULT_CANCELED);
  1206. startActivity(register);
  1207. }
  1208. /**
  1209. * Updates the content and visibility state of the icon and text associated
  1210. * to the last check on the ownCloud server.
  1211. */
  1212. private void showServerStatus() {
  1213. TextView tv = (TextView) findViewById(R.id.server_status_text);
  1214. if (mServerStatusIcon == 0 && mServerStatusText == 0) {
  1215. tv.setVisibility(View.INVISIBLE);
  1216. } else {
  1217. tv.setText(mServerStatusText);
  1218. tv.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon, 0, 0, 0);
  1219. tv.setVisibility(View.VISIBLE);
  1220. }
  1221. }
  1222. /**
  1223. * Updates the content and visibility state of the icon and text associated
  1224. * to the interactions with the OAuth authorization server.
  1225. */
  1226. private void showAuthStatus() {
  1227. if (mAuthStatusIcon == 0 && mAuthStatusText == 0) {
  1228. mAuthStatusLayout.setVisibility(View.INVISIBLE);
  1229. } else {
  1230. mAuthStatusLayout.setText(mAuthStatusText);
  1231. mAuthStatusLayout.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon, 0, 0, 0);
  1232. mAuthStatusLayout.setVisibility(View.VISIBLE);
  1233. }
  1234. }
  1235. private void showRefreshButton() {
  1236. mRefreshButton.setVisibility(View.VISIBLE);
  1237. }
  1238. private void hideRefreshButton() {
  1239. mRefreshButton.setVisibility(View.GONE);
  1240. }
  1241. /**
  1242. * Called when the refresh button in the input field for ownCloud host is clicked.
  1243. *
  1244. * Performs a new check on the URL in the input field.
  1245. *
  1246. * @param view Refresh 'button'
  1247. */
  1248. public void onRefreshClick(View view) {
  1249. checkOcServer();
  1250. }
  1251. /**
  1252. * Called when the eye icon in the password field is clicked.
  1253. *
  1254. * Toggles the visibility of the password in the field.
  1255. */
  1256. public void onViewPasswordClick() {
  1257. int selectionStart = mPasswordInput.getSelectionStart();
  1258. int selectionEnd = mPasswordInput.getSelectionEnd();
  1259. if (isPasswordVisible()) {
  1260. hidePassword();
  1261. } else {
  1262. showPassword();
  1263. }
  1264. mPasswordInput.setSelection(selectionStart, selectionEnd);
  1265. }
  1266. /**
  1267. * Called when the checkbox for OAuth authorization is clicked.
  1268. *
  1269. * Hides or shows the input fields for user & password.
  1270. *
  1271. * @param view 'View password' 'button'
  1272. */
  1273. public void onCheckClick(View view) {
  1274. CheckBox oAuth2Check = (CheckBox)view;
  1275. if (oAuth2Check.isChecked()) {
  1276. mAuthTokenType = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType());
  1277. } else {
  1278. mAuthTokenType = AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());
  1279. }
  1280. adaptViewAccordingToAuthenticationMethod();
  1281. }
  1282. /**
  1283. * Changes the visibility of input elements depending on
  1284. * the current authorization method.
  1285. */
  1286. private void adaptViewAccordingToAuthenticationMethod () {
  1287. if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType)) {
  1288. // OAuth 2 authorization
  1289. mOAuthAuthEndpointText.setVisibility(View.VISIBLE);
  1290. mOAuthTokenEndpointText.setVisibility(View.VISIBLE);
  1291. mUsernameInput.setVisibility(View.GONE);
  1292. mPasswordInput.setVisibility(View.GONE);
  1293. } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {
  1294. // SAML-based web Single Sign On
  1295. mOAuthAuthEndpointText.setVisibility(View.GONE);
  1296. mOAuthTokenEndpointText.setVisibility(View.GONE);
  1297. mUsernameInput.setVisibility(View.GONE);
  1298. mPasswordInput.setVisibility(View.GONE);
  1299. } else {
  1300. // basic HTTP authorization
  1301. mOAuthAuthEndpointText.setVisibility(View.GONE);
  1302. mOAuthTokenEndpointText.setVisibility(View.GONE);
  1303. mUsernameInput.setVisibility(View.VISIBLE);
  1304. mPasswordInput.setVisibility(View.VISIBLE);
  1305. }
  1306. }
  1307. /**
  1308. * Called from SslValidatorDialog when a new server certificate was correctly saved.
  1309. */
  1310. public void onSavedCertificate() {
  1311. checkOcServer();
  1312. }
  1313. /**
  1314. * Called from SslValidatorDialog when a new server certificate could not be saved
  1315. * when the user requested it.
  1316. */
  1317. @Override
  1318. public void onFailedSavingCertificate() {
  1319. showDialog(DIALOG_CERT_NOT_SAVED);
  1320. }
  1321. /**
  1322. * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
  1323. *
  1324. * Used to trigger the authentication check when the user presses 'enter' after writing the password,
  1325. * or to throw the server test when the only field on screen is the URL input field.
  1326. */
  1327. @Override
  1328. public boolean onEditorAction(TextView inputField, int actionId, KeyEvent event) {
  1329. if (actionId == EditorInfo.IME_ACTION_DONE && inputField != null && inputField.equals(mPasswordInput)) {
  1330. if (mOkButton.isEnabled()) {
  1331. mOkButton.performClick();
  1332. }
  1333. } else if (actionId == EditorInfo.IME_ACTION_NEXT && inputField != null && inputField.equals(mHostUrlInput)) {
  1334. if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {
  1335. checkOcServer();
  1336. }
  1337. }
  1338. return false; // always return false to grant that the software keyboard is hidden anyway
  1339. }
  1340. private abstract static class RightDrawableOnTouchListener implements OnTouchListener {
  1341. private int fuzz = 75;
  1342. /**
  1343. * {@inheritDoc}
  1344. */
  1345. @Override
  1346. public boolean onTouch(View view, MotionEvent event) {
  1347. Drawable rightDrawable = null;
  1348. if (view instanceof TextView) {
  1349. Drawable[] drawables = ((TextView)view).getCompoundDrawables();
  1350. if (drawables.length > 2) {
  1351. rightDrawable = drawables[2];
  1352. }
  1353. }
  1354. if (rightDrawable != null) {
  1355. final int x = (int) event.getX();
  1356. final int y = (int) event.getY();
  1357. final Rect bounds = rightDrawable.getBounds();
  1358. if (x >= (view.getRight() - bounds.width() - fuzz) && x <= (view.getRight() - view.getPaddingRight() + fuzz)
  1359. && y >= (view.getPaddingTop() - fuzz) && y <= (view.getHeight() - view.getPaddingBottom()) + fuzz) {
  1360. return onDrawableTouch(event);
  1361. }
  1362. }
  1363. return false;
  1364. }
  1365. public abstract boolean onDrawableTouch(final MotionEvent event);
  1366. }
  1367. public void onSamlDialogSuccess(String sessionCookie) {
  1368. mAuthToken = sessionCookie;
  1369. if (sessionCookie != null && sessionCookie.length() > 0) {
  1370. mAuthToken = sessionCookie;
  1371. GetRemoteUserNameOperation getUserOperation = new GetRemoteUserNameOperation();
  1372. OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(mHostBaseUrl), getApplicationContext(), true);
  1373. client.setSsoSessionCookie(mAuthToken);
  1374. getUserOperation.execute(client, this, mHandler);
  1375. }
  1376. }
  1377. @Override
  1378. public void onSsoFinished(String sessionCookies) {
  1379. //Toast.makeText(this, "got cookies: " + sessionCookie, Toast.LENGTH_LONG).show();
  1380. if (sessionCookies != null && sessionCookies.length() > 0) {
  1381. Log_OC.d(TAG, "Successful SSO - time to save the account");
  1382. onSamlDialogSuccess(sessionCookies);
  1383. Fragment fd = getSupportFragmentManager().findFragmentByTag(TAG_SAML_DIALOG);
  1384. if (fd != null && fd instanceof SherlockDialogFragment) {
  1385. Dialog d = ((SherlockDialogFragment)fd).getDialog();
  1386. if (d != null && d.isShowing()) {
  1387. d.dismiss();
  1388. }
  1389. }
  1390. } else {
  1391. // TODO - show fail
  1392. Log_OC.d(TAG, "SSO failed");
  1393. }
  1394. }
  1395. /** Show auth_message
  1396. *
  1397. * @param message
  1398. */
  1399. private void showAuthMessage(String message) {
  1400. mAuthMessage.setVisibility(View.VISIBLE);
  1401. mAuthMessage.setText(message);
  1402. }
  1403. private void hideAuthMessage() {
  1404. mAuthMessage.setVisibility(View.GONE);
  1405. }
  1406. @Override
  1407. public boolean onTouchEvent(MotionEvent event) {
  1408. if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType) &&
  1409. mHostUrlInput.hasFocus() && event.getAction() == MotionEvent.ACTION_DOWN) {
  1410. checkOcServer();
  1411. }
  1412. return super.onTouchEvent(event);
  1413. }
  1414. }