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