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