AuthenticatorActivity.java 54 KB

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