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