AuthenticatorActivity.java 52 KB

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