AuthenticatorActivity.java 43 KB

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