AuthenticatorActivity.java 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  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 com.owncloud.android.AccountUtils;
  20. import com.owncloud.android.Log_OC;
  21. import com.owncloud.android.ui.dialog.SslValidatorDialog;
  22. import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;
  23. import com.owncloud.android.utils.OwnCloudVersion;
  24. import com.owncloud.android.network.OwnCloudClientUtils;
  25. import com.owncloud.android.operations.OwnCloudServerCheckOperation;
  26. import com.owncloud.android.operations.ExistenceCheckOperation;
  27. import com.owncloud.android.operations.OAuth2GetAccessToken;
  28. import com.owncloud.android.operations.OnRemoteOperationListener;
  29. import com.owncloud.android.operations.RemoteOperation;
  30. import com.owncloud.android.operations.RemoteOperationResult;
  31. import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
  32. import android.accounts.Account;
  33. import android.accounts.AccountAuthenticatorActivity;
  34. import android.accounts.AccountManager;
  35. import android.app.AlertDialog;
  36. import android.app.Dialog;
  37. import android.app.ProgressDialog;
  38. import android.content.ContentResolver;
  39. import android.content.DialogInterface;
  40. import android.content.Intent;
  41. import android.content.SharedPreferences;
  42. import android.graphics.Rect;
  43. import android.graphics.drawable.Drawable;
  44. import android.net.Uri;
  45. import android.os.Bundle;
  46. import android.os.Handler;
  47. import android.preference.PreferenceManager;
  48. import android.text.Editable;
  49. import android.text.InputType;
  50. import android.text.TextWatcher;
  51. import android.view.KeyEvent;
  52. import android.view.MotionEvent;
  53. import android.view.View;
  54. import android.view.View.OnFocusChangeListener;
  55. import android.view.View.OnTouchListener;
  56. import android.view.Window;
  57. import android.view.inputmethod.EditorInfo;
  58. import android.widget.CheckBox;
  59. import android.widget.EditText;
  60. import android.widget.Button;
  61. import android.widget.ImageView;
  62. import android.widget.TextView;
  63. import android.widget.Toast;
  64. import android.widget.TextView.OnEditorActionListener;
  65. import com.owncloud.android.R;
  66. import eu.alefzero.webdav.WebdavClient;
  67. /**
  68. * This Activity is used to add an ownCloud account to the App
  69. *
  70. * @author Bartek Przybylski
  71. * @author David A. Velasco
  72. */
  73. public class AuthenticatorActivity extends AccountAuthenticatorActivity
  74. implements OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeListener, OnEditorActionListener {
  75. private static final String TAG = AuthenticatorActivity.class.getSimpleName();
  76. public static final String EXTRA_ACCOUNT = "ACCOUNT";
  77. public static final String EXTRA_USER_NAME = "USER_NAME";
  78. public static final String EXTRA_HOST_NAME = "HOST_NAME";
  79. public static final String EXTRA_ACTION = "ACTION";
  80. private static final String KEY_HOST_URL_TEXT = "HOST_URL_TEXT";
  81. private static final String KEY_OC_VERSION = "OC_VERSION";
  82. private static final String KEY_ACCOUNT = "ACCOUNT";
  83. private static final String KEY_SERVER_VALID = "SERVER_VALID";
  84. private static final String KEY_SERVER_CHECKED = "SERVER_CHECKED";
  85. private static final String KEY_SERVER_CHECK_IN_PROGRESS = "SERVER_CHECK_IN_PROGRESS";
  86. private static final String KEY_SERVER_STATUS_TEXT = "SERVER_STATUS_TEXT";
  87. private static final String KEY_SERVER_STATUS_ICON = "SERVER_STATUS_ICON";
  88. private static final String KEY_IS_SSL_CONN = "IS_SSL_CONN";
  89. private static final String KEY_AUTH_STATUS_TEXT = "AUTH_STATUS_TEXT";
  90. private static final String KEY_AUTH_STATUS_ICON = "AUTH_STATUS_ICON";
  91. private static final String OAUTH_MODE_ON = "on";
  92. private static final String OAUTH_MODE_OFF = "off";
  93. private static final String OAUTH_MODE_OPTIONAL = "optional";
  94. private static final int DIALOG_LOGIN_PROGRESS = 0;
  95. private static final int DIALOG_SSL_VALIDATOR = 1;
  96. private static final int DIALOG_CERT_NOT_SAVED = 2;
  97. private static final int DIALOG_OAUTH2_LOGIN_PROGRESS = 3;
  98. public static final byte ACTION_CREATE = 0;
  99. public static final byte ACTION_UPDATE_TOKEN = 1;
  100. private String mHostBaseUrl;
  101. private OwnCloudVersion mDiscoveredVersion;
  102. private int mServerStatusText, mServerStatusIcon;
  103. private boolean mServerIsChecked, mServerIsValid, mIsSslConn;
  104. private int mAuthStatusText, mAuthStatusIcon;
  105. private final Handler mHandler = new Handler();
  106. private Thread mOperationThread;
  107. private OwnCloudServerCheckOperation mOcServerChkOperation;
  108. private ExistenceCheckOperation mAuthCheckOperation;
  109. private RemoteOperationResult mLastSslUntrustedServerResult;
  110. private Uri mNewCapturedUriFromOAuth2Redirection;
  111. private AccountManager mAccountMgr;
  112. private boolean mJustCreated;
  113. private byte mAction;
  114. private Account mAccount;
  115. private ImageView mViewPasswordButton;
  116. private EditText mHostUrlInput;
  117. private EditText mUsernameInput;
  118. private EditText mPasswordInput;
  119. private CheckBox mOAuth2Check;
  120. private String mOAuthAccessToken;
  121. private View mOkButton;
  122. private TextView mAuthStatusLayout;
  123. private TextView mOAuthAuthEndpointText;
  124. private TextView mOAuthTokenEndpointText;
  125. /**
  126. * {@inheritDoc}
  127. *
  128. * IMPORTANT ENTRY POINT 1: activity is shown to the user
  129. */
  130. @Override
  131. protected void onCreate(Bundle savedInstanceState) {
  132. super.onCreate(savedInstanceState);
  133. getWindow().requestFeature(Window.FEATURE_NO_TITLE);
  134. /// set view and get references to view elements
  135. setContentView(R.layout.account_setup);
  136. mViewPasswordButton = (ImageView) findViewById(R.id.viewPasswordButton);
  137. mHostUrlInput = (EditText) findViewById(R.id.hostUrlInput);
  138. mUsernameInput = (EditText) findViewById(R.id.account_username);
  139. mPasswordInput = (EditText) findViewById(R.id.account_password);
  140. mOAuthAuthEndpointText = (TextView)findViewById(R.id.oAuthEntryPoint_1);
  141. mOAuthTokenEndpointText = (TextView)findViewById(R.id.oAuthEntryPoint_2);
  142. mOAuth2Check = (CheckBox) findViewById(R.id.oauth_onOff_check);
  143. mOkButton = findViewById(R.id.buttonOK);
  144. mAuthStatusLayout = (TextView) findViewById(R.id.auth_status_text);
  145. /// complete label for 'register account' button
  146. Button b = (Button) findViewById(R.id.account_register);
  147. if (b != null) {
  148. b.setText(String.format(getString(R.string.auth_register), getString(R.string.app_name)));
  149. }
  150. /// initialization
  151. mAccountMgr = AccountManager.get(this);
  152. mNewCapturedUriFromOAuth2Redirection = null;
  153. mAction = getIntent().getByteExtra(EXTRA_ACTION, ACTION_CREATE);
  154. mAccount = null;
  155. mHostBaseUrl = "";
  156. if (savedInstanceState == null) {
  157. /// connection state and info
  158. mServerStatusText = mServerStatusIcon = 0;
  159. mServerIsValid = false;
  160. mServerIsChecked = false;
  161. mIsSslConn = false;
  162. mAuthStatusText = mAuthStatusIcon = 0;
  163. /// retrieve extras from intent
  164. String tokenType = getIntent().getExtras().getString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE);
  165. boolean oAuthRequired = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(tokenType) || OAUTH_MODE_ON.equals(getString(R.string.oauth2_mode));
  166. mAccount = getIntent().getExtras().getParcelable(EXTRA_ACCOUNT);
  167. if (mAccount != null) {
  168. String ocVersion = mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION);
  169. if (ocVersion != null) {
  170. mDiscoveredVersion = new OwnCloudVersion(ocVersion);
  171. }
  172. mHostBaseUrl = normalizeUrl(mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL));
  173. mHostUrlInput.setText(mHostBaseUrl);
  174. String userName = mAccount.name.substring(0, mAccount.name.lastIndexOf('@'));
  175. mUsernameInput.setText(userName);
  176. oAuthRequired = (mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null);
  177. }
  178. mOAuth2Check.setChecked(oAuthRequired);
  179. changeViewByOAuth2Check(oAuthRequired);
  180. } else {
  181. /// connection state and info
  182. mServerIsValid = savedInstanceState.getBoolean(KEY_SERVER_VALID);
  183. mServerIsChecked = savedInstanceState.getBoolean(KEY_SERVER_CHECKED);
  184. mServerStatusText = savedInstanceState.getInt(KEY_SERVER_STATUS_TEXT);
  185. mServerStatusIcon = savedInstanceState.getInt(KEY_SERVER_STATUS_ICON);
  186. mIsSslConn = savedInstanceState.getBoolean(KEY_IS_SSL_CONN);
  187. mAuthStatusText = savedInstanceState.getInt(KEY_AUTH_STATUS_TEXT);
  188. mAuthStatusIcon = savedInstanceState.getInt(KEY_AUTH_STATUS_ICON);
  189. /// server data
  190. String ocVersion = savedInstanceState.getString(KEY_OC_VERSION);
  191. if (ocVersion != null) {
  192. mDiscoveredVersion = new OwnCloudVersion(ocVersion);
  193. }
  194. mHostBaseUrl = savedInstanceState.getString(KEY_HOST_URL_TEXT);
  195. // account data, if updating
  196. mAccount = savedInstanceState.getParcelable(KEY_ACCOUNT);
  197. // check if server check was interrupted by a configuration change
  198. if (savedInstanceState.getBoolean(KEY_SERVER_CHECK_IN_PROGRESS, false)) {
  199. checkOcServer();
  200. }
  201. }
  202. showServerStatus();
  203. showAuthStatus();
  204. if (mServerIsChecked && !mServerIsValid) showRefreshButton();
  205. mOkButton.setEnabled(mServerIsValid); // state not automatically recovered in configuration changes
  206. if (!OAUTH_MODE_OPTIONAL.equals(getString(R.string.oauth2_mode))) {
  207. mOAuth2Check.setVisibility(View.GONE);
  208. }
  209. if (mAction == ACTION_UPDATE_TOKEN) {
  210. /// lock things that should not change
  211. mHostUrlInput.setEnabled(false);
  212. mUsernameInput.setEnabled(false);
  213. mOAuth2Check.setVisibility(View.GONE);
  214. if (!mServerIsValid && mOcServerChkOperation == null) {
  215. checkOcServer();
  216. }
  217. }
  218. mPasswordInput.setText(""); // clean password to avoid social hacking (disadvantage: password in removed if the device is turned aside)
  219. mJustCreated = true;
  220. /// bind view elements to listeners
  221. mHostUrlInput.setOnFocusChangeListener(this);
  222. mHostUrlInput.setOnTouchListener(new RightDrawableOnTouchListener() {
  223. @Override
  224. public boolean onDrawableTouch(final MotionEvent event) {
  225. AuthenticatorActivity.this.onRefreshClick(mHostUrlInput);
  226. return true;
  227. }
  228. });
  229. mHostUrlInput.addTextChangedListener(new TextWatcher() {
  230. @Override
  231. public void afterTextChanged(Editable s) {
  232. if (!mHostBaseUrl.equals(normalizeUrl(mHostUrlInput.getText().toString()))) {
  233. mOkButton.setEnabled(false);
  234. }
  235. }
  236. @Override
  237. public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
  238. @Override
  239. public void onTextChanged(CharSequence s, int start, int before, int count) {}
  240. });
  241. mPasswordInput.setOnFocusChangeListener(this);
  242. mPasswordInput.setImeOptions(EditorInfo.IME_ACTION_DONE);
  243. mPasswordInput.setOnEditorActionListener(this);
  244. }
  245. /**
  246. * Saves relevant state before {@link #onPause()}
  247. *
  248. * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag, intended to defer the
  249. * processing of the redirection caught in {@link #onNewIntent(Intent)} until {@link #onResume()}
  250. *
  251. * See {@link #loadSavedInstanceState(Bundle)}
  252. */
  253. @Override
  254. protected void onSaveInstanceState(Bundle outState) {
  255. super.onSaveInstanceState(outState);
  256. /// connection state and info
  257. outState.putInt(KEY_SERVER_STATUS_TEXT, mServerStatusText);
  258. outState.putInt(KEY_SERVER_STATUS_ICON, mServerStatusIcon);
  259. outState.putBoolean(KEY_SERVER_VALID, mServerIsValid);
  260. outState.putBoolean(KEY_SERVER_CHECKED, mServerIsChecked);
  261. outState.putBoolean(KEY_SERVER_CHECK_IN_PROGRESS, (!mServerIsValid && mOcServerChkOperation != null));
  262. outState.putBoolean(KEY_IS_SSL_CONN, mIsSslConn);
  263. outState.putInt(KEY_AUTH_STATUS_ICON, mAuthStatusIcon);
  264. outState.putInt(KEY_AUTH_STATUS_TEXT, mAuthStatusText);
  265. /// server data
  266. if (mDiscoveredVersion != null) {
  267. outState.putString(KEY_OC_VERSION, mDiscoveredVersion.toString());
  268. }
  269. outState.putString(KEY_HOST_URL_TEXT, mHostBaseUrl);
  270. /// account data, if updating
  271. if (mAccount != null) {
  272. outState.putParcelable(KEY_ACCOUNT, mAccount);
  273. }
  274. }
  275. /**
  276. * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION request
  277. * is caught here.
  278. *
  279. * To make this possible, this activity needs to be qualified with android:launchMode = "singleTask" in the
  280. * AndroidManifest.xml file.
  281. */
  282. @Override
  283. protected void onNewIntent (Intent intent) {
  284. Log_OC.d(TAG, "onNewIntent()");
  285. Uri data = intent.getData();
  286. if (data != null && data.toString().startsWith(getString(R.string.oauth2_redirect_uri))) {
  287. mNewCapturedUriFromOAuth2Redirection = data;
  288. }
  289. }
  290. /**
  291. * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION, and
  292. * deferred in {@link #onNewIntent(Intent)}, is processed here.
  293. */
  294. @Override
  295. protected void onResume() {
  296. super.onResume();
  297. // the state of mOAuth2Check is automatically recovered between configuration changes, but not before onCreate() finishes; so keep the next lines here
  298. changeViewByOAuth2Check(mOAuth2Check.isChecked());
  299. if (mAction == ACTION_UPDATE_TOKEN && mJustCreated) {
  300. if (mOAuth2Check.isChecked())
  301. Toast.makeText(this, R.string.auth_expired_oauth_token_toast, Toast.LENGTH_LONG).show();
  302. else
  303. Toast.makeText(this, R.string.auth_expired_basic_auth_toast, Toast.LENGTH_LONG).show();
  304. }
  305. if (mNewCapturedUriFromOAuth2Redirection != null) {
  306. getOAuth2AccessTokenFromCapturedRedirection();
  307. }
  308. mJustCreated = false;
  309. }
  310. /**
  311. * Parses the redirection with the response to the GET AUTHORIZATION request to the
  312. * oAuth server and requests for the access token (GET ACCESS TOKEN)
  313. */
  314. private void getOAuth2AccessTokenFromCapturedRedirection() {
  315. /// Parse data from OAuth redirection
  316. String queryParameters = mNewCapturedUriFromOAuth2Redirection.getQuery();
  317. mNewCapturedUriFromOAuth2Redirection = null;
  318. /// Showing the dialog with instructions for the user.
  319. showDialog(DIALOG_OAUTH2_LOGIN_PROGRESS);
  320. /// GET ACCESS TOKEN to the oAuth server
  321. RemoteOperation operation = new OAuth2GetAccessToken( getString(R.string.oauth2_client_id),
  322. getString(R.string.oauth2_redirect_uri),
  323. getString(R.string.oauth2_grant_type),
  324. queryParameters);
  325. //WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(getString(R.string.oauth2_url_endpoint_access)), getApplicationContext());
  326. WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mOAuthTokenEndpointText.getText().toString().trim()), getApplicationContext());
  327. operation.execute(client, this, mHandler);
  328. }
  329. /**
  330. * Handles the change of focus on the text inputs for the server URL and the password
  331. */
  332. public void onFocusChange(View view, boolean hasFocus) {
  333. if (view.getId() == R.id.hostUrlInput) {
  334. if (!hasFocus) {
  335. onUrlInputFocusLost((TextView) view);
  336. }
  337. else {
  338. hideRefreshButton();
  339. }
  340. } else if (view.getId() == R.id.account_password) {
  341. onPasswordFocusChanged((TextView) view, hasFocus);
  342. }
  343. }
  344. /**
  345. * Handles changes in focus on the text input for the server URL.
  346. *
  347. * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
  348. * other field. The operation to check the existence of the server in the entered URL is
  349. * started.
  350. *
  351. * When hasFocus: user 'comes back' to write again the server URL.
  352. *
  353. * @param hostInput TextView with the URL input field receiving the change of focus.
  354. */
  355. private void onUrlInputFocusLost(TextView hostInput) {
  356. if (!mHostBaseUrl.equals(normalizeUrl(mHostUrlInput.getText().toString()))) {
  357. checkOcServer();
  358. } else {
  359. mOkButton.setEnabled(mServerIsValid);
  360. }
  361. }
  362. private void checkOcServer() {
  363. String uri = mHostUrlInput.getText().toString().trim();
  364. mServerIsValid = false;
  365. mServerIsChecked = false;
  366. mOkButton.setEnabled(false);
  367. mDiscoveredVersion = null;
  368. hideRefreshButton();
  369. if (uri.length() != 0) {
  370. mServerStatusText = R.string.auth_testing_connection;
  371. mServerStatusIcon = R.drawable.progress_small;
  372. showServerStatus();
  373. mOcServerChkOperation = new OwnCloudServerCheckOperation(uri, this);
  374. WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(uri), this);
  375. mOperationThread = mOcServerChkOperation.execute(client, this, mHandler);
  376. } else {
  377. mServerStatusText = 0;
  378. mServerStatusIcon = 0;
  379. showServerStatus();
  380. }
  381. }
  382. /**
  383. * Handles changes in focus on the text input for the password (basic authorization).
  384. *
  385. * When (hasFocus), the button to toggle password visibility is shown.
  386. *
  387. * When (!hasFocus), the button is made invisible and the password is hidden.
  388. *
  389. * @param passwordInput TextView with the password input field receiving the change of focus.
  390. * @param hasFocus 'True' if focus is received, 'false' if is lost
  391. */
  392. private void onPasswordFocusChanged(TextView passwordInput, boolean hasFocus) {
  393. if (hasFocus) {
  394. mViewPasswordButton.setVisibility(View.VISIBLE);
  395. } else {
  396. int input_type = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
  397. passwordInput.setInputType(input_type);
  398. mViewPasswordButton.setVisibility(View.INVISIBLE);
  399. }
  400. }
  401. /**
  402. * Cancels the authenticator activity
  403. *
  404. * IMPORTANT ENTRY POINT 3: Never underestimate the importance of cancellation
  405. *
  406. * This method is bound in the layout/acceoun_setup.xml resource file.
  407. *
  408. * @param view Cancel button
  409. */
  410. public void onCancelClick(View view) {
  411. setResult(RESULT_CANCELED); // TODO review how is this related to AccountAuthenticator (debugging)
  412. finish();
  413. }
  414. /**
  415. * Checks the credentials of the user in the root of the ownCloud server
  416. * before creating a new local account.
  417. *
  418. * For basic authorization, a check of existence of the root folder is
  419. * performed.
  420. *
  421. * For OAuth, starts the flow to get an access token; the credentials test
  422. * is postponed until it is available.
  423. *
  424. * IMPORTANT ENTRY POINT 4
  425. *
  426. * @param view OK button
  427. */
  428. public void onOkClick(View view) {
  429. // this check should be unnecessary
  430. if (mDiscoveredVersion == null || !mDiscoveredVersion.isVersionValid() || mHostBaseUrl == null || mHostBaseUrl.length() == 0) {
  431. mServerStatusIcon = R.drawable.common_error;
  432. mServerStatusText = R.string.auth_wtf_reenter_URL;
  433. showServerStatus();
  434. mOkButton.setEnabled(false);
  435. Log_OC.wtf(TAG, "The user was allowed to click 'connect' to an unchecked server!!");
  436. return;
  437. }
  438. if (mOAuth2Check.isChecked()) {
  439. startOauthorization();
  440. } else {
  441. checkBasicAuthorization();
  442. }
  443. }
  444. /**
  445. * Tests the credentials entered by the user performing a check of existence on
  446. * the root folder of the ownCloud server.
  447. */
  448. private void checkBasicAuthorization() {
  449. /// get the path to the root folder through WebDAV from the version server
  450. String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, false);
  451. /// get basic credentials entered by user
  452. String username = mUsernameInput.getText().toString();
  453. String password = mPasswordInput.getText().toString();
  454. /// be gentle with the user
  455. showDialog(DIALOG_LOGIN_PROGRESS);
  456. /// test credentials accessing the root folder
  457. mAuthCheckOperation = new ExistenceCheckOperation("", this, false);
  458. WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this);
  459. client.setBasicCredentials(username, password);
  460. mOperationThread = mAuthCheckOperation.execute(client, this, mHandler);
  461. }
  462. /**
  463. * Starts the OAuth 'grant type' flow to get an access token, with
  464. * a GET AUTHORIZATION request to the BUILT-IN authorization server.
  465. */
  466. private void startOauthorization() {
  467. // be gentle with the user
  468. mAuthStatusIcon = R.drawable.progress_small;
  469. mAuthStatusText = R.string.oauth_login_connection;
  470. showAuthStatus();
  471. // GET AUTHORIZATION request
  472. //Uri uri = Uri.parse(getString(R.string.oauth2_url_endpoint_auth));
  473. Uri uri = Uri.parse(mOAuthAuthEndpointText.getText().toString().trim());
  474. Uri.Builder uriBuilder = uri.buildUpon();
  475. uriBuilder.appendQueryParameter(OAuth2Constants.KEY_RESPONSE_TYPE, getString(R.string.oauth2_response_type));
  476. uriBuilder.appendQueryParameter(OAuth2Constants.KEY_REDIRECT_URI, getString(R.string.oauth2_redirect_uri));
  477. uriBuilder.appendQueryParameter(OAuth2Constants.KEY_CLIENT_ID, getString(R.string.oauth2_client_id));
  478. uriBuilder.appendQueryParameter(OAuth2Constants.KEY_SCOPE, getString(R.string.oauth2_scope));
  479. //uriBuilder.appendQueryParameter(OAuth2Constants.KEY_STATE, whateverwewant);
  480. uri = uriBuilder.build();
  481. Log_OC.d(TAG, "Starting browser to view " + uri.toString());
  482. Intent i = new Intent(Intent.ACTION_VIEW, uri);
  483. startActivity(i);
  484. }
  485. /**
  486. * Callback method invoked when a RemoteOperation executed by this Activity finishes.
  487. *
  488. * Dispatches the operation flow to the right method.
  489. */
  490. @Override
  491. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  492. if (operation instanceof OwnCloudServerCheckOperation) {
  493. onOcServerCheckFinish((OwnCloudServerCheckOperation) operation, result);
  494. } else if (operation instanceof OAuth2GetAccessToken) {
  495. onGetOAuthAccessTokenFinish((OAuth2GetAccessToken)operation, result);
  496. } else if (operation instanceof ExistenceCheckOperation) {
  497. onAuthorizationCheckFinish((ExistenceCheckOperation)operation, result);
  498. }
  499. }
  500. /**
  501. * Processes the result of the server check performed when the user finishes the enter of the
  502. * server URL.
  503. *
  504. * @param operation Server check performed.
  505. * @param result Result of the check.
  506. */
  507. private void onOcServerCheckFinish(OwnCloudServerCheckOperation operation, RemoteOperationResult result) {
  508. if (operation.equals(mOcServerChkOperation)) {
  509. /// save result state
  510. mServerIsChecked = true;
  511. mServerIsValid = result.isSuccess();
  512. mIsSslConn = (result.getCode() == ResultCode.OK_SSL);
  513. mOcServerChkOperation = null;
  514. /// update status icon and text
  515. if (mServerIsValid) {
  516. hideRefreshButton();
  517. } else {
  518. showRefreshButton();
  519. }
  520. updateServerStatusIconAndText(result);
  521. showServerStatus();
  522. /// very special case (TODO: move to a common place for all the remote operations)
  523. if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
  524. mLastSslUntrustedServerResult = result;
  525. showDialog(DIALOG_SSL_VALIDATOR);
  526. }
  527. /// retrieve discovered version and normalize server URL
  528. mDiscoveredVersion = operation.getDiscoveredVersion();
  529. mHostBaseUrl = normalizeUrl(mHostUrlInput.getText().toString());
  530. /// allow or not the user try to access the server
  531. mOkButton.setEnabled(mServerIsValid);
  532. } // else nothing ; only the last check operation is considered;
  533. // multiple can be triggered if the user amends a URL before a previous check can be triggered
  534. }
  535. private String normalizeUrl(String url) {
  536. if (url != null && url.length() > 0) {
  537. url = url.trim();
  538. if (!url.toLowerCase().startsWith("http://") &&
  539. !url.toLowerCase().startsWith("https://")) {
  540. if (mIsSslConn) {
  541. url = "https://" + url;
  542. } else {
  543. url = "http://" + url;
  544. }
  545. }
  546. if (url.endsWith("/")) {
  547. url = url.substring(0, url.length() - 1);
  548. }
  549. }
  550. return (url != null ? url : "");
  551. }
  552. /**
  553. * Chooses the right icon and text to show to the user for the received operation result.
  554. *
  555. * @param result Result of a remote operation performed in this activity
  556. */
  557. private void updateServerStatusIconAndText(RemoteOperationResult result) {
  558. mServerStatusIcon = R.drawable.common_error; // the most common case in the switch below
  559. switch (result.getCode()) {
  560. case OK_SSL:
  561. mServerStatusIcon = android.R.drawable.ic_secure;
  562. mServerStatusText = R.string.auth_secure_connection;
  563. break;
  564. case OK_NO_SSL:
  565. case OK:
  566. if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://") ) {
  567. mServerStatusText = R.string.auth_connection_established;
  568. mServerStatusIcon = R.drawable.ic_ok;
  569. } else {
  570. mServerStatusText = R.string.auth_nossl_plain_ok_title;
  571. mServerStatusIcon = android.R.drawable.ic_partial_secure;
  572. }
  573. break;
  574. case NO_NETWORK_CONNECTION:
  575. mServerStatusIcon = R.drawable.no_network;
  576. mServerStatusText = R.string.auth_no_net_conn_title;
  577. break;
  578. case SSL_RECOVERABLE_PEER_UNVERIFIED:
  579. mServerStatusText = R.string.auth_ssl_unverified_server_title;
  580. break;
  581. case BAD_OC_VERSION:
  582. mServerStatusText = R.string.auth_bad_oc_version_title;
  583. break;
  584. case WRONG_CONNECTION:
  585. mServerStatusText = R.string.auth_wrong_connection_title;
  586. break;
  587. case TIMEOUT:
  588. mServerStatusText = R.string.auth_timeout_title;
  589. break;
  590. case INCORRECT_ADDRESS:
  591. mServerStatusText = R.string.auth_incorrect_address_title;
  592. break;
  593. case SSL_ERROR:
  594. mServerStatusText = R.string.auth_ssl_general_error_title;
  595. break;
  596. case UNAUTHORIZED:
  597. mServerStatusText = R.string.auth_unauthorized;
  598. break;
  599. case HOST_NOT_AVAILABLE:
  600. mServerStatusText = R.string.auth_unknown_host_title;
  601. break;
  602. case INSTANCE_NOT_CONFIGURED:
  603. mServerStatusText = R.string.auth_not_configured_title;
  604. break;
  605. case FILE_NOT_FOUND:
  606. mServerStatusText = R.string.auth_incorrect_path_title;
  607. break;
  608. case OAUTH2_ERROR:
  609. mServerStatusText = R.string.auth_oauth_error;
  610. break;
  611. case OAUTH2_ERROR_ACCESS_DENIED:
  612. mServerStatusText = R.string.auth_oauth_error_access_denied;
  613. break;
  614. case UNHANDLED_HTTP_CODE:
  615. case UNKNOWN_ERROR:
  616. mServerStatusText = R.string.auth_unknown_error_title;
  617. break;
  618. default:
  619. mServerStatusText = 0;
  620. mServerStatusIcon = 0;
  621. }
  622. }
  623. /**
  624. * Chooses the right icon and text to show to the user for the received operation result.
  625. *
  626. * @param result Result of a remote operation performed in this activity
  627. */
  628. private void updateAuthStatusIconAndText(RemoteOperationResult result) {
  629. mAuthStatusIcon = R.drawable.common_error; // the most common case in the switch below
  630. switch (result.getCode()) {
  631. case OK_SSL:
  632. mAuthStatusIcon = android.R.drawable.ic_secure;
  633. mAuthStatusText = R.string.auth_secure_connection;
  634. break;
  635. case OK_NO_SSL:
  636. case OK:
  637. if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://") ) {
  638. mAuthStatusText = R.string.auth_connection_established;
  639. mAuthStatusIcon = R.drawable.ic_ok;
  640. } else {
  641. mAuthStatusText = R.string.auth_nossl_plain_ok_title;
  642. mAuthStatusIcon = android.R.drawable.ic_partial_secure;
  643. }
  644. break;
  645. case NO_NETWORK_CONNECTION:
  646. mAuthStatusIcon = R.drawable.no_network;
  647. mAuthStatusText = R.string.auth_no_net_conn_title;
  648. break;
  649. case SSL_RECOVERABLE_PEER_UNVERIFIED:
  650. mAuthStatusText = R.string.auth_ssl_unverified_server_title;
  651. break;
  652. case BAD_OC_VERSION:
  653. mAuthStatusText = R.string.auth_bad_oc_version_title;
  654. break;
  655. case WRONG_CONNECTION:
  656. mAuthStatusText = R.string.auth_wrong_connection_title;
  657. break;
  658. case TIMEOUT:
  659. mAuthStatusText = R.string.auth_timeout_title;
  660. break;
  661. case INCORRECT_ADDRESS:
  662. mAuthStatusText = R.string.auth_incorrect_address_title;
  663. break;
  664. case SSL_ERROR:
  665. mAuthStatusText = R.string.auth_ssl_general_error_title;
  666. break;
  667. case UNAUTHORIZED:
  668. mAuthStatusText = R.string.auth_unauthorized;
  669. break;
  670. case HOST_NOT_AVAILABLE:
  671. mAuthStatusText = R.string.auth_unknown_host_title;
  672. break;
  673. case INSTANCE_NOT_CONFIGURED:
  674. mAuthStatusText = R.string.auth_not_configured_title;
  675. break;
  676. case FILE_NOT_FOUND:
  677. mAuthStatusText = R.string.auth_incorrect_path_title;
  678. break;
  679. case OAUTH2_ERROR:
  680. mAuthStatusText = R.string.auth_oauth_error;
  681. break;
  682. case OAUTH2_ERROR_ACCESS_DENIED:
  683. mAuthStatusText = R.string.auth_oauth_error_access_denied;
  684. break;
  685. case UNHANDLED_HTTP_CODE:
  686. case UNKNOWN_ERROR:
  687. mAuthStatusText = R.string.auth_unknown_error_title;
  688. break;
  689. default:
  690. mAuthStatusText = 0;
  691. mAuthStatusIcon = 0;
  692. }
  693. }
  694. /**
  695. * Processes the result of the request for and access token send
  696. * to an OAuth authorization server.
  697. *
  698. * @param operation Operation performed requesting the access token.
  699. * @param result Result of the operation.
  700. */
  701. private void onGetOAuthAccessTokenFinish(OAuth2GetAccessToken operation, RemoteOperationResult result) {
  702. try {
  703. dismissDialog(DIALOG_OAUTH2_LOGIN_PROGRESS);
  704. } catch (IllegalArgumentException e) {
  705. // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
  706. }
  707. String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, true);
  708. if (result.isSuccess() && webdav_path != null) {
  709. /// be gentle with the user
  710. showDialog(DIALOG_LOGIN_PROGRESS);
  711. /// time to test the retrieved access token on the ownCloud server
  712. mOAuthAccessToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Constants.KEY_ACCESS_TOKEN);
  713. Log_OC.d(TAG, "Got ACCESS TOKEN: " + mOAuthAccessToken);
  714. mAuthCheckOperation = new ExistenceCheckOperation("", this, false);
  715. WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this);
  716. client.setBearerCredentials(mOAuthAccessToken);
  717. mAuthCheckOperation.execute(client, this, mHandler);
  718. } else {
  719. updateAuthStatusIconAndText(result);
  720. showAuthStatus();
  721. Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
  722. }
  723. }
  724. /**
  725. * Processes the result of the access check performed to try the user credentials.
  726. *
  727. * Creates a new account through the AccountManager.
  728. *
  729. * @param operation Access check performed.
  730. * @param result Result of the operation.
  731. */
  732. private void onAuthorizationCheckFinish(ExistenceCheckOperation operation, RemoteOperationResult result) {
  733. try {
  734. dismissDialog(DIALOG_LOGIN_PROGRESS);
  735. } catch (IllegalArgumentException e) {
  736. // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
  737. }
  738. if (result.isSuccess()) {
  739. Log_OC.d(TAG, "Successful access - time to save the account");
  740. if (mAction == ACTION_CREATE) {
  741. createAccount();
  742. } else {
  743. updateToken();
  744. }
  745. finish();
  746. } else {
  747. updateAuthStatusIconAndText(result);
  748. showAuthStatus();
  749. Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
  750. }
  751. }
  752. /**
  753. * Sets the proper response to get that the Account Authenticator that started this activity saves
  754. * a new authorization token for mAccount.
  755. */
  756. private void updateToken() {
  757. Bundle response = new Bundle();
  758. response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
  759. response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);
  760. boolean isOAuth = mOAuth2Check.isChecked();
  761. if (isOAuth) {
  762. response.putString(AccountManager.KEY_AUTHTOKEN, mOAuthAccessToken);
  763. // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
  764. mAccountMgr.setAuthToken(mAccount, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, mOAuthAccessToken);
  765. } else {
  766. response.putString(AccountManager.KEY_AUTHTOKEN, mPasswordInput.getText().toString());
  767. mAccountMgr.setPassword(mAccount, mPasswordInput.getText().toString());
  768. }
  769. setAccountAuthenticatorResult(response);
  770. }
  771. /**
  772. * Creates a new account through the Account Authenticator that started this activity.
  773. *
  774. * This makes the account permanent.
  775. *
  776. * TODO Decide how to name the OAuth accounts
  777. */
  778. private void createAccount() {
  779. /// create and save new ownCloud account
  780. boolean isOAuth = mOAuth2Check.isChecked();
  781. Uri uri = Uri.parse(mHostBaseUrl);
  782. String username = mUsernameInput.getText().toString().trim();
  783. if (isOAuth) {
  784. username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();
  785. }
  786. String accountName = username + "@" + uri.getHost();
  787. if (uri.getPort() >= 0) {
  788. accountName += ":" + uri.getPort();
  789. }
  790. mAccount = new Account(accountName, AccountAuthenticator.ACCOUNT_TYPE);
  791. if (isOAuth) {
  792. mAccountMgr.addAccountExplicitly(mAccount, "", null); // with our implementation, the password is never input in the app
  793. } else {
  794. mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);
  795. }
  796. /// add the new account as default in preferences, if there is none already
  797. Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
  798. if (defaultAccount == null) {
  799. SharedPreferences.Editor editor = PreferenceManager
  800. .getDefaultSharedPreferences(this).edit();
  801. editor.putString("select_oc_account", accountName);
  802. editor.commit();
  803. }
  804. /// prepare result to return to the Authenticator
  805. // TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done
  806. final Intent intent = new Intent();
  807. intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, AccountAuthenticator.ACCOUNT_TYPE);
  808. intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
  809. if (!isOAuth)
  810. intent.putExtra(AccountManager.KEY_AUTHTOKEN, AccountAuthenticator.ACCOUNT_TYPE); // TODO check this; not sure it's right; maybe
  811. intent.putExtra(AccountManager.KEY_USERDATA, username);
  812. if (isOAuth) {
  813. mAccountMgr.setAuthToken(mAccount, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, mOAuthAccessToken);
  814. }
  815. /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
  816. mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION, mDiscoveredVersion.toString());
  817. mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL, mHostBaseUrl);
  818. if (isOAuth)
  819. mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_OAUTH2, "TRUE"); // TODO this flag should be unnecessary
  820. setAccountAuthenticatorResult(intent.getExtras());
  821. setResult(RESULT_OK, intent);
  822. /// immediately request for the synchronization of the new account
  823. Bundle bundle = new Bundle();
  824. bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
  825. ContentResolver.requestSync(mAccount, AccountAuthenticator.AUTHORITY, bundle);
  826. }
  827. /**
  828. * {@inheritDoc}
  829. *
  830. * Necessary to update the contents of the SSL Dialog
  831. *
  832. * TODO move to some common place for all possible untrusted SSL failures
  833. */
  834. @Override
  835. protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
  836. switch (id) {
  837. case DIALOG_LOGIN_PROGRESS:
  838. case DIALOG_CERT_NOT_SAVED:
  839. case DIALOG_OAUTH2_LOGIN_PROGRESS:
  840. break;
  841. case DIALOG_SSL_VALIDATOR: {
  842. ((SslValidatorDialog)dialog).updateResult(mLastSslUntrustedServerResult);
  843. break;
  844. }
  845. default:
  846. Log_OC.e(TAG, "Incorrect dialog called with id = " + id);
  847. }
  848. }
  849. /**
  850. * {@inheritDoc}
  851. */
  852. @Override
  853. protected Dialog onCreateDialog(int id) {
  854. Dialog dialog = null;
  855. switch (id) {
  856. case DIALOG_LOGIN_PROGRESS: {
  857. /// simple progress dialog
  858. ProgressDialog working_dialog = new ProgressDialog(this);
  859. working_dialog.setMessage(getResources().getString(R.string.auth_trying_to_login));
  860. working_dialog.setIndeterminate(true);
  861. working_dialog.setCancelable(true);
  862. working_dialog
  863. .setOnCancelListener(new DialogInterface.OnCancelListener() {
  864. @Override
  865. public void onCancel(DialogInterface dialog) {
  866. /// TODO study if this is enough
  867. Log_OC.i(TAG, "Login canceled");
  868. if (mOperationThread != null) {
  869. mOperationThread.interrupt();
  870. finish();
  871. }
  872. }
  873. });
  874. dialog = working_dialog;
  875. break;
  876. }
  877. case DIALOG_OAUTH2_LOGIN_PROGRESS: {
  878. ProgressDialog working_dialog = new ProgressDialog(this);
  879. working_dialog.setMessage(String.format("Getting authorization"));
  880. working_dialog.setIndeterminate(true);
  881. working_dialog.setCancelable(true);
  882. working_dialog
  883. .setOnCancelListener(new DialogInterface.OnCancelListener() {
  884. @Override
  885. public void onCancel(DialogInterface dialog) {
  886. Log_OC.i(TAG, "Login canceled");
  887. finish();
  888. }
  889. });
  890. dialog = working_dialog;
  891. break;
  892. }
  893. case DIALOG_SSL_VALIDATOR: {
  894. /// TODO start to use new dialog interface, at least for this (it is a FragmentDialog already)
  895. dialog = SslValidatorDialog.newInstance(this, mLastSslUntrustedServerResult, this);
  896. break;
  897. }
  898. case DIALOG_CERT_NOT_SAVED: {
  899. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  900. builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
  901. builder.setCancelable(false);
  902. builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
  903. @Override
  904. public void onClick(DialogInterface dialog, int which) {
  905. dialog.dismiss();
  906. };
  907. });
  908. dialog = builder.create();
  909. break;
  910. }
  911. default:
  912. Log_OC.e(TAG, "Incorrect dialog called with id = " + id);
  913. }
  914. return dialog;
  915. }
  916. /**
  917. * Starts and activity to open the 'new account' page in the ownCloud web site
  918. *
  919. * @param view 'Account register' button
  920. */
  921. public void onRegisterClick(View view) {
  922. Intent register = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.url_account_register)));
  923. setResult(RESULT_CANCELED);
  924. startActivity(register);
  925. }
  926. /**
  927. * Updates the content and visibility state of the icon and text associated
  928. * to the last check on the ownCloud server.
  929. */
  930. private void showServerStatus() {
  931. TextView tv = (TextView) findViewById(R.id.server_status_text);
  932. if (mServerStatusIcon == 0 && mServerStatusText == 0) {
  933. tv.setVisibility(View.INVISIBLE);
  934. } else {
  935. tv.setText(mServerStatusText);
  936. tv.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon, 0, 0, 0);
  937. tv.setVisibility(View.VISIBLE);
  938. }
  939. }
  940. /**
  941. * Updates the content and visibility state of the icon and text associated
  942. * to the interactions with the OAuth authorization server.
  943. */
  944. private void showAuthStatus() {
  945. if (mAuthStatusIcon == 0 && mAuthStatusText == 0) {
  946. mAuthStatusLayout.setVisibility(View.INVISIBLE);
  947. } else {
  948. mAuthStatusLayout.setText(mAuthStatusText);
  949. mAuthStatusLayout.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon, 0, 0, 0);
  950. mAuthStatusLayout.setVisibility(View.VISIBLE);
  951. }
  952. }
  953. private void showRefreshButton() {
  954. mHostUrlInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.ic_action_refresh_black, 0);
  955. }
  956. private void hideRefreshButton() {
  957. mHostUrlInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
  958. }
  959. /**
  960. * Called when the refresh button in the input field for ownCloud host is clicked.
  961. *
  962. * Performs a new check on the URL in the input field.
  963. *
  964. * @param view Refresh 'button'
  965. */
  966. public void onRefreshClick(View view) {
  967. checkOcServer();
  968. }
  969. /**
  970. * Called when the eye icon in the password field is clicked.
  971. *
  972. * Toggles the visibility of the password in the field.
  973. *
  974. * @param view 'View password' 'button'
  975. */
  976. public void onViewPasswordClick(View view) {
  977. int selectionStart = mPasswordInput.getSelectionStart();
  978. int selectionEnd = mPasswordInput.getSelectionEnd();
  979. int input_type = mPasswordInput.getInputType();
  980. if ((input_type & InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
  981. input_type = InputType.TYPE_CLASS_TEXT
  982. | InputType.TYPE_TEXT_VARIATION_PASSWORD;
  983. } else {
  984. input_type = InputType.TYPE_CLASS_TEXT
  985. | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;
  986. }
  987. mPasswordInput.setInputType(input_type);
  988. mPasswordInput.setSelection(selectionStart, selectionEnd);
  989. }
  990. /**
  991. * Called when the checkbox for OAuth authorization is clicked.
  992. *
  993. * Hides or shows the input fields for user & password.
  994. *
  995. * @param view 'View password' 'button'
  996. */
  997. public void onCheckClick(View view) {
  998. CheckBox oAuth2Check = (CheckBox)view;
  999. changeViewByOAuth2Check(oAuth2Check.isChecked());
  1000. }
  1001. /**
  1002. * Changes the visibility of input elements depending upon the kind of authorization
  1003. * chosen by the user: basic or OAuth
  1004. *
  1005. * @param checked 'True' when OAuth is selected.
  1006. */
  1007. public void changeViewByOAuth2Check(Boolean checked) {
  1008. if (checked) {
  1009. mOAuthAuthEndpointText.setVisibility(View.VISIBLE);
  1010. mOAuthTokenEndpointText.setVisibility(View.VISIBLE);
  1011. mUsernameInput.setVisibility(View.GONE);
  1012. mPasswordInput.setVisibility(View.GONE);
  1013. mViewPasswordButton.setVisibility(View.GONE);
  1014. } else {
  1015. mOAuthAuthEndpointText.setVisibility(View.GONE);
  1016. mOAuthTokenEndpointText.setVisibility(View.GONE);
  1017. mUsernameInput.setVisibility(View.VISIBLE);
  1018. mPasswordInput.setVisibility(View.VISIBLE);
  1019. mViewPasswordButton.setVisibility(View.INVISIBLE);
  1020. }
  1021. }
  1022. /**
  1023. * Called from SslValidatorDialog when a new server certificate was correctly saved.
  1024. */
  1025. public void onSavedCertificate() {
  1026. mOperationThread = mOcServerChkOperation.retry(this, mHandler);
  1027. }
  1028. /**
  1029. * Called from SslValidatorDialog when a new server certificate could not be saved
  1030. * when the user requested it.
  1031. */
  1032. @Override
  1033. public void onFailedSavingCertificate() {
  1034. showDialog(DIALOG_CERT_NOT_SAVED);
  1035. }
  1036. /**
  1037. * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
  1038. *
  1039. * Used to trigger the authorization check when the user presses 'enter' after writing the password.
  1040. */
  1041. @Override
  1042. public boolean onEditorAction(TextView inputField, int actionId, KeyEvent event) {
  1043. if (inputField != null && inputField.equals(mPasswordInput) &&
  1044. actionId == EditorInfo.IME_ACTION_DONE) {
  1045. if (mOkButton.isEnabled()) {
  1046. mOkButton.performClick();
  1047. }
  1048. }
  1049. return false; // always return false to grant that the software keyboard is hidden anyway
  1050. }
  1051. private abstract static class RightDrawableOnTouchListener implements OnTouchListener {
  1052. private int fuzz = 10;
  1053. /**
  1054. * {@inheritDoc}
  1055. */
  1056. @Override
  1057. public boolean onTouch(View view, MotionEvent event) {
  1058. if (event.getAction() == MotionEvent.ACTION_DOWN) {
  1059. Drawable rightDrawable = null;
  1060. if (view instanceof TextView) {
  1061. Drawable[] drawables = ((TextView)view).getCompoundDrawables();
  1062. if (drawables.length > 2) {
  1063. rightDrawable = drawables[2];
  1064. }
  1065. }
  1066. if (rightDrawable != null) {
  1067. final int x = (int) event.getX();
  1068. final int y = (int) event.getY();
  1069. final Rect bounds = rightDrawable.getBounds();
  1070. if (x >= (view.getRight() - bounds.width() - fuzz) && x <= (view.getRight() - view.getPaddingRight() + fuzz)
  1071. && y >= (view.getPaddingTop() - fuzz) && y <= (view.getHeight() - view.getPaddingBottom()) + fuzz) {
  1072. return onDrawableTouch(event);
  1073. }
  1074. }
  1075. }
  1076. return false;
  1077. }
  1078. public abstract boolean onDrawableTouch(final MotionEvent event);
  1079. }
  1080. }