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