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