AuthenticatorActivity.java 53 KB

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