AuthenticatorActivity.java 68 KB

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