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