8c8798c596127123d6082bb7014b12f1ab3e80ce
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / AuthenticatorActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 */
19
20 package com.owncloud.android.ui.activity;
21
22 import com.owncloud.android.AccountUtils;
23 import com.owncloud.android.authenticator.AccountAuthenticator;
24 import com.owncloud.android.authenticator.oauth2.OAuth2Context;
25 import com.owncloud.android.ui.dialog.SslValidatorDialog;
26 import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;
27 import com.owncloud.android.utils.OwnCloudVersion;
28 import com.owncloud.android.network.OwnCloudClientUtils;
29 import com.owncloud.android.operations.OwnCloudServerCheckOperation;
30 import com.owncloud.android.operations.ExistenceCheckOperation;
31 import com.owncloud.android.operations.OAuth2GetAccessToken;
32 import com.owncloud.android.operations.OnRemoteOperationListener;
33 import com.owncloud.android.operations.RemoteOperation;
34 import com.owncloud.android.operations.RemoteOperationResult;
35 import com.owncloud.android.operations.RemoteOperationResult.ResultCode;
36
37 import android.accounts.Account;
38 import android.accounts.AccountAuthenticatorActivity;
39 import android.accounts.AccountManager;
40 import android.app.AlertDialog;
41 import android.app.Dialog;
42 import android.app.ProgressDialog;
43 import android.content.ContentResolver;
44 import android.content.DialogInterface;
45 import android.content.Intent;
46 import android.content.SharedPreferences;
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.util.Log;
53 import android.view.View;
54 import android.view.View.OnFocusChangeListener;
55 import android.view.Window;
56 import android.widget.CheckBox;
57 import android.widget.EditText;
58 import android.widget.Button;
59 import android.widget.ImageView;
60 import android.widget.TextView;
61 import android.widget.Toast;
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 {
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 int DIALOG_LOGIN_PROGRESS = 0;
94 private static final int DIALOG_SSL_VALIDATOR = 1;
95 private static final int DIALOG_CERT_NOT_SAVED = 2;
96 private static final int DIALOG_OAUTH2_LOGIN_PROGRESS = 3;
97
98 public static final byte ACTION_CREATE = 0;
99 public static final byte ACTION_UPDATE_TOKEN = 1;
100
101
102 private String mHostBaseUrl;
103 private OwnCloudVersion mDiscoveredVersion;
104
105 private int mStatusText, mStatusIcon;
106 private boolean mStatusCorrect, mIsSslConn;
107 private int mOAuth2StatusText, mOAuth2StatusIcon;
108
109 private final Handler mHandler = new Handler();
110 private Thread mOperationThread;
111 private OwnCloudServerCheckOperation mOcServerChkOperation;
112 private ExistenceCheckOperation mAuthCheckOperation;
113 private RemoteOperationResult mLastSslUntrustedServerResult;
114
115 //private Thread mOAuth2GetCodeThread;
116 //private OAuth2GetAuthorizationToken mOAuth2GetCodeRunnable;
117 //private TokenReceiver tokenReceiver;
118 //private JSONObject mCodeResponseJson;
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
164 /// complete label for 'register account' button
165 Button b = (Button) findViewById(R.id.account_register);
166 if (b != null) {
167 b.setText(String.format(getString(R.string.auth_register), getString(R.string.app_name)));
168 }
169
170 /// bind view elements to listeners
171 mHostUrlInput.setOnFocusChangeListener(this);
172 mPasswordInput.setOnFocusChangeListener(this);
173
174 /// initialization
175 mAccountMgr = AccountManager.get(this);
176 mNewCapturedUriFromOAuth2Redirection = null; // TODO save?
177 mAction = getIntent().getByteExtra(EXTRA_ACTION, ACTION_CREATE);
178 mAccount = null;
179
180 if (savedInstanceState == null) {
181 /// connection state and info
182 mStatusText = mStatusIcon = 0;
183 mStatusCorrect = false;
184 mIsSslConn = false;
185
186 /// retrieve extras from intent
187 String tokenType = getIntent().getExtras().getString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE);
188 boolean oAuthRequired = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(tokenType);
189 mOAuth2Check.setChecked(oAuthRequired);
190 changeViewByOAuth2Check(oAuthRequired);
191
192 mAccount = getIntent().getExtras().getParcelable(EXTRA_ACCOUNT);
193 if (mAccount != null) {
194 String ocVersion = mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION);
195 if (ocVersion != null) {
196 mDiscoveredVersion = new OwnCloudVersion(ocVersion);
197 }
198 mHostBaseUrl = mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL);
199 mHostUrlInput.setText(mHostBaseUrl);
200 String userName = mAccount.name.substring(0, mAccount.name.lastIndexOf('@'));
201 mUsernameInput.setText(userName);
202 }
203
204 } else {
205 loadSavedInstanceState(savedInstanceState);
206 }
207
208 if (mAction == ACTION_UPDATE_TOKEN) {
209 /// lock things that should not change
210 mHostUrlInput.setEnabled(false);
211 mUsernameInput.setEnabled(false);
212 mOAuth2Check.setVisibility(View.GONE);
213 checkOcServer();
214 }
215
216 mPasswordInput.setText(""); // clean password to avoid social hacking (disadvantage: password in removed if the device is turned aside)
217 mJustCreated = true;
218 }
219
220
221 /**
222 * Saves relevant state before {@link #onPause()}
223 *
224 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag, intended to defer the
225 * processing of the redirection caught in {@link #onNewIntent(Intent)} until {@link #onResume()}
226 *
227 * See {@link #loadSavedInstanceState(Bundle)}
228 */
229 @Override
230 protected void onSaveInstanceState(Bundle outState) {
231 super.onSaveInstanceState(outState);
232
233 /// connection state and info
234 outState.putInt(KEY_STATUS_TEXT, mStatusText);
235 outState.putInt(KEY_STATUS_ICON, mStatusIcon);
236 outState.putBoolean(KEY_STATUS_CORRECT, mStatusCorrect);
237 outState.putBoolean(KEY_IS_SSL_CONN, mIsSslConn);
238
239 /// server data
240 if (mDiscoveredVersion != null)
241 outState.putString(KEY_OC_VERSION, mDiscoveredVersion.toString());
242 outState.putString(KEY_HOST_URL_TEXT, mHostBaseUrl);
243
244 /// account data, if updating
245 if (mAccount != null)
246 outState.putParcelable(KEY_ACCOUNT, mAccount);
247
248 // Saving the state of oAuth2 components.
249 outState.putInt(KEY_OAUTH2_STATUS_ICON, mOAuth2StatusIcon);
250 outState.putInt(KEY_OAUTH2_STATUS_TEXT, mOAuth2StatusText);
251
252 /* Leave old OAuth flow
253 if (codeResponseJson != null){
254 outState.putString(KEY_OAUTH2_CODE_RESULT, codeResponseJson.toString());
255 }
256 */
257 }
258
259
260 /**
261 * Loads saved state
262 *
263 * See {@link #onSaveInstanceState(Bundle)}.
264 *
265 * @param savedInstanceState Saved state, as received in {@link #onCreate(Bundle)}.
266 */
267 private void loadSavedInstanceState(Bundle savedInstanceState) {
268 /// connection state and info
269 mStatusCorrect = savedInstanceState.getBoolean(KEY_STATUS_CORRECT);
270 mIsSslConn = savedInstanceState.getBoolean(KEY_IS_SSL_CONN);
271 mStatusText = savedInstanceState.getInt(KEY_STATUS_TEXT);
272 mStatusIcon = savedInstanceState.getInt(KEY_STATUS_ICON);
273 updateConnStatus();
274
275 /// UI settings depending upon connection
276 mOkButton.setEnabled(mStatusCorrect); // TODO really necessary?
277 if (!mStatusCorrect)
278 mRefreshButton.setVisibility(View.VISIBLE); // seems that setting visibility is necessary
279 else
280 mRefreshButton.setVisibility(View.INVISIBLE);
281
282 /// server data
283 String ocVersion = savedInstanceState.getString(KEY_OC_VERSION);
284 if (ocVersion != null)
285 mDiscoveredVersion = new OwnCloudVersion(ocVersion);
286 mHostBaseUrl = savedInstanceState.getString(KEY_HOST_URL_TEXT);
287
288 // account data, if updating
289 mAccount = savedInstanceState.getParcelable(KEY_ACCOUNT);
290
291 // state of oAuth2 components
292 mOAuth2StatusIcon = savedInstanceState.getInt(KEY_OAUTH2_STATUS_ICON);
293 mOAuth2StatusText = savedInstanceState.getInt(KEY_OAUTH2_STATUS_TEXT);
294
295 /* Leave old OAuth flow
296 // We store a JSon object with all the data returned from oAuth2 server when we get user_code.
297 // Is better than store variable by variable. We use String object to serialize from/to it.
298 try {
299 if (savedInstanceState.containsKey(KEY_OAUTH2_CODE_RESULT)) {
300 codeResponseJson = new JSONObject(savedInstanceState.getString(KEY_OAUTH2_CODE_RESULT));
301 }
302 } catch (JSONException e) {
303 Log.e(TAG, "onCreate->JSONException: " + e.toString());
304 }*/
305 // END of getting the state of oAuth2 components.
306
307 }
308
309
310 /**
311 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION request
312 * is caught here.
313 *
314 * To make this possible, this activity needs to be qualified with android:launchMode = "singleTask" in the
315 * AndroidManifest.xml file.
316 */
317 @Override
318 protected void onNewIntent (Intent intent) {
319 Log.d(TAG, "onNewIntent()");
320 Uri data = intent.getData();
321 if (data != null && data.toString().startsWith(OAuth2Context.MY_REDIRECT_URI)) {
322 mNewCapturedUriFromOAuth2Redirection = data;
323 }
324 }
325
326
327 /**
328 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION, and
329 * deferred in {@link #onNewIntent(Intent)}, is processed here.
330 */
331 @Override
332 protected void onResume() {
333 super.onResume();
334 // the state of mOAuth2Check is automatically recovered between configuration changes, but not before onCreate() finishes; so keep the next lines here
335 changeViewByOAuth2Check(mOAuth2Check.isChecked());
336 if (mAction == ACTION_UPDATE_TOKEN && mJustCreated) {
337 if (mOAuth2Check.isChecked())
338 Toast.makeText(this, R.string.auth_expired_oauth_token_toast, Toast.LENGTH_LONG).show();
339 else
340 Toast.makeText(this, R.string.auth_expired_basic_auth_toast, Toast.LENGTH_LONG).show();
341 }
342
343
344 /* LEAVE OLD OAUTH FLOW ;
345 // (old oauth code) Registering token receiver. We must listening to the service that is pooling to the oAuth server for a token.
346 if (tokenReceiver == null) {
347 IntentFilter tokenFilter = new IntentFilter(OAuth2GetTokenService.TOKEN_RECEIVED_MESSAGE);
348 tokenReceiver = new TokenReceiver();
349 this.registerReceiver(tokenReceiver,tokenFilter);
350 } */
351 // (new oauth code)
352 if (mNewCapturedUriFromOAuth2Redirection != null) {
353 getOAuth2AccessTokenFromCapturedRedirection();
354 }
355
356 mJustCreated = false;
357 }
358
359
360 @Override protected void onDestroy() {
361 super.onDestroy();
362
363 /* LEAVE OLD OAUTH FLOW
364 // We must stop the service thats it's pooling to oAuth2 server for a token.
365 Intent tokenService = new Intent(this, OAuth2GetTokenService.class);
366 stopService(tokenService);
367
368 // We stop listening the result of the pooling service.
369 if (tokenReceiver != null) {
370 unregisterReceiver(tokenReceiver);
371 tokenReceiver = null;
372 }*/
373
374 }
375
376
377 /**
378 * Parses the redirection with the response to the GET AUTHORIZATION request to the
379 * oAuth server and requests for the access token (GET ACCESS TOKEN)
380 */
381 private void getOAuth2AccessTokenFromCapturedRedirection() {
382 /// Parse data from OAuth redirection
383 String queryParameters = mNewCapturedUriFromOAuth2Redirection.getQuery();
384 mNewCapturedUriFromOAuth2Redirection = null;
385
386 /// Showing the dialog with instructions for the user.
387 showDialog(DIALOG_OAUTH2_LOGIN_PROGRESS);
388
389 /// GET ACCESS TOKEN to the oAuth server
390 RemoteOperation operation = new OAuth2GetAccessToken(queryParameters);
391 WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(getString(R.string.oauth_url_endpoint_access)), getApplicationContext());
392 operation.execute(client, this, mHandler);
393 }
394
395
396
397 /**
398 * Handles the change of focus on the text inputs for the server URL and the password
399 */
400 public void onFocusChange(View view, boolean hasFocus) {
401 if (view.getId() == R.id.hostUrlInput) {
402 onUrlInputFocusChanged((TextView) view, hasFocus);
403
404 } else if (view.getId() == R.id.account_password) {
405 onPasswordFocusChanged((TextView) view, hasFocus);
406 }
407 }
408
409
410 /**
411 * Handles changes in focus on the text input for the server URL.
412 *
413 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
414 * other field. The operation to check the existence of the server in the entered URL is
415 * started.
416 *
417 * When hasFocus: user 'comes back' to write again the server URL.
418 *
419 * @param hostInput TextView with the URL input field receiving the change of focus.
420 * @param hasFocus 'True' if focus is received, 'false' if is lost
421 */
422 private void onUrlInputFocusChanged(TextView hostInput, boolean hasFocus) {
423 if (!hasFocus) {
424 checkOcServer();
425
426 } else {
427 // avoids that the 'connect' button can be clicked if the test was previously passed
428 mOkButton.setEnabled(false);
429 }
430 }
431
432
433 private void checkOcServer() {
434 String uri = mHostUrlInput.getText().toString().trim();
435 if (uri.length() != 0) {
436 mStatusText = R.string.auth_testing_connection;
437 mStatusIcon = R.drawable.progress_small;
438 updateConnStatus();
439 /** TODO cancel previous connection check if the user tries to ammend a wrong URL
440 if(mConnChkOperation != null) {
441 mConnChkOperation.cancel();
442 } */
443 mOcServerChkOperation = new OwnCloudServerCheckOperation(uri, this);
444 WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(uri), this);
445 mHostBaseUrl = "";
446 mDiscoveredVersion = null;
447 mOperationThread = mOcServerChkOperation.execute(client, this, mHandler);
448 } else {
449 mRefreshButton.setVisibility(View.INVISIBLE);
450 mStatusText = 0;
451 mStatusIcon = 0;
452 updateConnStatus();
453 }
454 }
455
456
457 /**
458 * Handles changes in focus on the text input for the password (basic authorization).
459 *
460 * When (hasFocus), the button to toggle password visibility is shown.
461 *
462 * When (!hasFocus), the button is made invisible and the password is hidden.
463 *
464 * @param passwordInput TextView with the password input field receiving the change of focus.
465 * @param hasFocus 'True' if focus is received, 'false' if is lost
466 */
467 private void onPasswordFocusChanged(TextView passwordInput, boolean hasFocus) {
468 if (hasFocus) {
469 mViewPasswordButton.setVisibility(View.VISIBLE);
470 } else {
471 int input_type = InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD;
472 passwordInput.setInputType(input_type);
473 mViewPasswordButton.setVisibility(View.INVISIBLE);
474 }
475 }
476
477
478
479 /**
480 * Cancels the authenticator activity
481 *
482 * IMPORTANT ENTRY POINT 3: Never underestimate the importance of cancellation
483 *
484 * This method is bound in the layout/acceoun_setup.xml resource file.
485 *
486 * @param view Cancel button
487 */
488 public void onCancelClick(View view) {
489 setResult(RESULT_CANCELED); // TODO review how is this related to AccountAuthenticator
490 finish();
491 }
492
493
494
495 /**
496 * Checks the credentials of the user in the root of the ownCloud server
497 * before creating a new local account.
498 *
499 * For basic authorization, a check of existence of the root folder is
500 * performed.
501 *
502 * For OAuth, starts the flow to get an access token; the credentials test
503 * is postponed until it is available.
504 *
505 * IMPORTANT ENTRY POINT 4
506 *
507 * @param view OK button
508 */
509 public void onOkClick(View view) {
510 // this check should be unnecessary
511 if (mDiscoveredVersion == null || !mDiscoveredVersion.isVersionValid() || mHostBaseUrl == null || mHostBaseUrl.length() == 0) {
512 mStatusIcon = R.drawable.common_error;
513 mStatusText = R.string.auth_wtf_reenter_URL;
514 updateConnStatus();
515 mOkButton.setEnabled(false);
516 Log.wtf(TAG, "The user was allowed to click 'connect' to an unchecked server!!");
517 return;
518 }
519
520 if (mOAuth2Check.isChecked()) {
521 startOauthorization();
522
523 } else {
524 checkBasicAuthorization();
525 }
526 }
527
528
529 /**
530 * Tests the credentials entered by the user performing a check of existence on
531 * the root folder of the ownCloud server.
532 */
533 private void checkBasicAuthorization() {
534 /// get the path to the root folder through WebDAV from the version server
535 String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, false);
536
537 /// get basic credentials entered by user
538 String username = mUsernameInput.getText().toString();
539 String password = mPasswordInput.getText().toString();
540
541 /// be gentle with the user
542 showDialog(DIALOG_LOGIN_PROGRESS);
543
544 /// test credentials accessing the root folder
545 mAuthCheckOperation = new ExistenceCheckOperation("", this, false);
546 WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this);
547 client.setBasicCredentials(username, password);
548 mOperationThread = mAuthCheckOperation.execute(client, this, mHandler);
549 }
550
551
552 /**
553 * Starts the OAuth 'grant type' flow to get an access token, with
554 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
555 */
556 private void startOauthorization() {
557 // be gentle with the user
558 mStatusIcon = R.drawable.progress_small;
559 mStatusText = R.string.oauth_login_connection;
560 updateAuthStatus();
561
562 // GET AUTHORIZATION request
563 /*
564 mOAuth2GetCodeRunnable = new OAuth2GetAuthorizationToken(, this);
565 mOAuth2GetCodeRunnable.setListener(this, mHandler);
566 mOAuth2GetCodeThread = new Thread(mOAuth2GetCodeRunnable);
567 mOAuth2GetCodeThread.start();
568 */
569
570 //if (mGrantType.equals(OAuth2Context.OAUTH2_AUTH_CODE_GRANT_TYPE)) {
571 Uri uri = Uri.parse(getString(R.string.oauth_url_endpoint_auth));
572 Uri.Builder uriBuilder = uri.buildUpon();
573 uriBuilder.appendQueryParameter(OAuth2Context.CODE_RESPONSE_TYPE, OAuth2Context.OAUTH2_CODE_RESPONSE_TYPE);
574 uriBuilder.appendQueryParameter(OAuth2Context.CODE_REDIRECT_URI, OAuth2Context.MY_REDIRECT_URI);
575 uriBuilder.appendQueryParameter(OAuth2Context.CODE_CLIENT_ID, OAuth2Context.OAUTH2_F_CLIENT_ID);
576 uriBuilder.appendQueryParameter(OAuth2Context.CODE_SCOPE, OAuth2Context.OAUTH2_F_SCOPE);
577 //uriBuilder.appendQueryParameter(OAuth2Context.CODE_STATE, whateverwewant);
578 uri = uriBuilder.build();
579 Log.d(TAG, "Starting browser to view " + uri.toString());
580 Intent i = new Intent(Intent.ACTION_VIEW, uri);
581 startActivity(i);
582 //}
583 }
584
585
586 /**
587 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
588 *
589 * Dispatches the operation flow to the right method.
590 */
591 @Override
592 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
593
594 if (operation instanceof OwnCloudServerCheckOperation) {
595 onOcServerCheckFinish((OwnCloudServerCheckOperation) operation, result);
596
597 } else if (operation instanceof OAuth2GetAccessToken) {
598 onGetOAuthAccessTokenFinish((OAuth2GetAccessToken)operation, result);
599
600 } else if (operation instanceof ExistenceCheckOperation) {
601 onAuthorizationCheckFinish((ExistenceCheckOperation)operation, result);
602
603 }
604 }
605
606
607 /**
608 * Processes the result of the server check performed when the user finishes the enter of the
609 * server URL.
610 *
611 * @param operation Server check performed.
612 * @param result Result of the check.
613 */
614 private void onOcServerCheckFinish(OwnCloudServerCheckOperation operation, RemoteOperationResult result) {
615 /// update status icon and text
616 updateStatusIconAndText(result);
617 updateConnStatus();
618
619 /// save result state
620 mStatusCorrect = result.isSuccess();
621 mIsSslConn = (result.getCode() == ResultCode.OK_SSL);
622
623 /// very special case (TODO: move to a common place for all the remote operations)
624 if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
625 mLastSslUntrustedServerResult = result;
626 showDialog(DIALOG_SSL_VALIDATOR);
627 }
628
629 /// update the visibility of the 'retry connection' button
630 if (!mStatusCorrect)
631 mRefreshButton.setVisibility(View.VISIBLE);
632 else
633 mRefreshButton.setVisibility(View.INVISIBLE);
634
635 /// retrieve discovered version and normalize server URL
636 mDiscoveredVersion = operation.getDiscoveredVersion();
637 mHostBaseUrl = mHostUrlInput.getText().toString().trim();
638 if (!mHostBaseUrl.toLowerCase().startsWith("http://") &&
639 !mHostBaseUrl.toLowerCase().startsWith("https://")) {
640
641 if (mIsSslConn) {
642 mHostBaseUrl = "https://" + mHostBaseUrl;
643 } else {
644 mHostBaseUrl = "http://" + mHostBaseUrl;
645 }
646
647 }
648 if (mHostBaseUrl.endsWith("/"))
649 mHostBaseUrl = mHostBaseUrl.substring(0, mHostBaseUrl.length() - 1);
650
651 /// allow or not the user try to access the server
652 mOkButton.setEnabled(mStatusCorrect);
653 }
654
655
656 /**
657 * Chooses the right icon and text to show to the user for the received operation result.
658 *
659 * @param result Result of a remote operation performed in this activity
660 */
661 private void updateStatusIconAndText(RemoteOperationResult result) {
662 mStatusText = mStatusIcon = 0;
663
664 switch (result.getCode()) {
665 case OK_SSL:
666 mStatusIcon = android.R.drawable.ic_secure;
667 mStatusText = R.string.auth_secure_connection;
668 break;
669
670 case OK_NO_SSL:
671 case OK:
672 if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://") ) {
673 mStatusText = R.string.auth_connection_established;
674 mStatusIcon = R.drawable.ic_ok;
675 } else {
676 mStatusText = R.string.auth_nossl_plain_ok_title;
677 mStatusIcon = android.R.drawable.ic_partial_secure;
678 }
679 break;
680
681 case SSL_RECOVERABLE_PEER_UNVERIFIED:
682 mStatusIcon = R.drawable.common_error;
683 mStatusText = R.string.auth_ssl_unverified_server_title;
684 break;
685
686 case BAD_OC_VERSION:
687 mStatusIcon = R.drawable.common_error;
688 mStatusText = R.string.auth_bad_oc_version_title;
689 break;
690 case WRONG_CONNECTION:
691 mStatusIcon = R.drawable.common_error;
692 mStatusText = R.string.auth_wrong_connection_title;
693 break;
694 case TIMEOUT:
695 mStatusIcon = R.drawable.common_error;
696 mStatusText = R.string.auth_timeout_title;
697 break;
698 case INCORRECT_ADDRESS:
699 mStatusIcon = R.drawable.common_error;
700 mStatusText = R.string.auth_incorrect_address_title;
701 break;
702
703 case SSL_ERROR:
704 mStatusIcon = R.drawable.common_error;
705 mStatusText = R.string.auth_ssl_general_error_title;
706 break;
707
708 case UNAUTHORIZED:
709 mStatusIcon = R.drawable.common_error;
710 mStatusText = R.string.auth_unauthorized;
711 break;
712 case HOST_NOT_AVAILABLE:
713 mStatusIcon = R.drawable.common_error;
714 mStatusText = R.string.auth_unknown_host_title;
715 break;
716 case NO_NETWORK_CONNECTION:
717 mStatusIcon = R.drawable.no_network;
718 mStatusText = R.string.auth_no_net_conn_title;
719 break;
720 case INSTANCE_NOT_CONFIGURED:
721 mStatusIcon = R.drawable.common_error;
722 mStatusText = R.string.auth_not_configured_title;
723 break;
724 case FILE_NOT_FOUND:
725 mStatusIcon = R.drawable.common_error;
726 mStatusText = R.string.auth_incorrect_path_title;
727 break;
728 case OAUTH2_ERROR:
729 mStatusIcon = R.drawable.common_error;
730 mStatusText = R.string.auth_oauth_error;
731 break;
732 case OAUTH2_ERROR_ACCESS_DENIED:
733 mStatusIcon = R.drawable.common_error;
734 mStatusText = R.string.auth_oauth_error_access_denied;
735 break;
736 case UNHANDLED_HTTP_CODE:
737 case UNKNOWN_ERROR:
738 mStatusIcon = R.drawable.common_error;
739 mStatusText = R.string.auth_unknown_error_title;
740 break;
741
742 default:
743 break;
744 }
745 }
746
747
748 /**
749 * Processes the result of the request for and access token send
750 * to an OAuth authorization server.
751 *
752 * @param operation Operation performed requesting the access token.
753 * @param result Result of the operation.
754 */
755 private void onGetOAuthAccessTokenFinish(OAuth2GetAccessToken operation, RemoteOperationResult result) {
756 try {
757 dismissDialog(DIALOG_OAUTH2_LOGIN_PROGRESS);
758 } catch (IllegalArgumentException e) {
759 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
760 }
761
762 String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, true);
763 if (result.isSuccess() && webdav_path != null) {
764 /// be gentle with the user
765 showDialog(DIALOG_LOGIN_PROGRESS);
766
767 /// time to test the retrieved access token on the ownCloud server
768 mOAuthAccessToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Context.KEY_ACCESS_TOKEN);
769 Log.d(TAG, "Got ACCESS TOKEN: " + mOAuthAccessToken);
770 mAuthCheckOperation = new ExistenceCheckOperation("", this, false);
771 WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this);
772 client.setBearerCredentials(mOAuthAccessToken);
773 mAuthCheckOperation.execute(client, this, mHandler);
774
775 } else {
776 updateStatusIconAndText(result);
777 updateAuthStatus();
778 Log.d(TAG, "Access failed: " + result.getLogMessage());
779 }
780 }
781
782
783 /**
784 * Processes the result of the access check performed to try the user credentials.
785 *
786 * Creates a new account through the AccountManager.
787 *
788 * @param operation Access check performed.
789 * @param result Result of the operation.
790 */
791 private void onAuthorizationCheckFinish(ExistenceCheckOperation operation, RemoteOperationResult result) {
792 try {
793 dismissDialog(DIALOG_LOGIN_PROGRESS);
794 } catch (IllegalArgumentException e) {
795 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
796 }
797
798 if (result.isSuccess()) {
799 Log.d(TAG, "Successful access - time to save the account");
800
801 if (mAction == ACTION_CREATE) {
802 createAccount();
803
804 } else {
805 updateToken();
806 }
807
808 finish();
809
810 } else {
811 updateStatusIconAndText(result);
812 updateAuthStatus();
813 Log.d(TAG, "Access failed: " + result.getLogMessage());
814 }
815 }
816
817
818 /**
819 * Sets the proper response to get that the Account Authenticator that started this activity saves
820 * a new authorization token for mAccount.
821 */
822 private void updateToken() {
823 Bundle response = new Bundle();
824 response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
825 response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);
826 boolean isOAuth = mOAuth2Check.isChecked();
827 if (isOAuth) {
828 response.putString(AccountManager.KEY_AUTHTOKEN, mOAuthAccessToken);
829 // the next line is unnecessary; the AccountManager does it when receives the response Bundle
830 // mAccountMgr.setAuthToken(mAccount, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, mOAuthAccessToken);
831 } else {
832 response.putString(AccountManager.KEY_AUTHTOKEN, mPasswordInput.getText().toString());
833 // the next line is not really necessary, because we are using the password as if it was an auth token; but let's keep it there by now
834 mAccountMgr.setPassword(mAccount, mPasswordInput.getText().toString());
835 }
836 setAccountAuthenticatorResult(response);
837 }
838
839
840 /**
841 * Creates a new account through the Account Authenticator that started this activity.
842 *
843 * This makes the account permanent.
844 *
845 * TODO Decide how to name the OAuth accounts
846 * TODO Minimize the direct interactions with the account manager; seems that not all the operations
847 * in the current code are really necessary, provided that right extras are returned to the Account
848 * Authenticator through setAccountAuthenticatorResult
849 */
850 private void createAccount() {
851 /// create and save new ownCloud account
852 boolean isOAuth = mOAuth2Check.isChecked();
853
854 Uri uri = Uri.parse(mHostBaseUrl);
855 String username = mUsernameInput.getText().toString().trim();
856 if (isOAuth) {
857 username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong(); // TODO change this to something readable
858 }
859 String accountName = username + "@" + uri.getHost();
860 if (uri.getPort() >= 0) {
861 accountName += ":" + uri.getPort();
862 }
863 mAccount = new Account(accountName, AccountAuthenticator.ACCOUNT_TYPE);
864 if (isOAuth) {
865 mAccountMgr.addAccountExplicitly(mAccount, "", null); // with our implementation, the password is never input in the app
866 } else {
867 mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);
868 }
869
870 /// add the new account as default in preferences, if there is none already
871 Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
872 if (defaultAccount == null) {
873 SharedPreferences.Editor editor = PreferenceManager
874 .getDefaultSharedPreferences(this).edit();
875 editor.putString("select_oc_account", accountName);
876 editor.commit();
877 }
878
879 /// prepare result to return to the Authenticator
880 // TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done
881 final Intent intent = new Intent();
882 intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, AccountAuthenticator.ACCOUNT_TYPE);
883 intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
884 if (!isOAuth)
885 intent.putExtra(AccountManager.KEY_AUTHTOKEN, AccountAuthenticator.ACCOUNT_TYPE); // TODO check this; not sure it's right; maybe
886 intent.putExtra(AccountManager.KEY_USERDATA, username);
887 if (isOAuth) {
888 mAccountMgr.setAuthToken(mAccount, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, mOAuthAccessToken);
889 }
890 /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
891 mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION, mDiscoveredVersion.toString());
892 mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL, mHostBaseUrl);
893 if (isOAuth)
894 mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_OAUTH2, "TRUE"); // TODO this flag should be unnecessary
895
896 setAccountAuthenticatorResult(intent.getExtras());
897 setResult(RESULT_OK, intent);
898
899 /// immediately request for the synchronization of the new account
900 Bundle bundle = new Bundle();
901 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
902 ContentResolver.requestSync(mAccount, AccountAuthenticator.AUTHORITY, bundle);
903 }
904
905
906 /**
907 * {@inheritDoc}
908 *
909 * Necessary to update the contents of the SSL Dialog
910 *
911 * TODO move to some common place for all possible untrusted SSL failures
912 */
913 @Override
914 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
915 switch (id) {
916 case DIALOG_LOGIN_PROGRESS:
917 case DIALOG_CERT_NOT_SAVED:
918 case DIALOG_OAUTH2_LOGIN_PROGRESS:
919 break;
920 case DIALOG_SSL_VALIDATOR: {
921 ((SslValidatorDialog)dialog).updateResult(mLastSslUntrustedServerResult);
922 break;
923 }
924 default:
925 Log.e(TAG, "Incorrect dialog called with id = " + id);
926 }
927 }
928
929
930 /**
931 * {@inheritDoc}
932 */
933 @Override
934 protected Dialog onCreateDialog(int id) {
935 Dialog dialog = null;
936 switch (id) {
937 case DIALOG_LOGIN_PROGRESS: {
938 /// simple progress dialog
939 ProgressDialog working_dialog = new ProgressDialog(this);
940 working_dialog.setMessage(getResources().getString(R.string.auth_trying_to_login));
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 /// TODO study if this is enough
948 Log.i(TAG, "Login canceled");
949 if (mOperationThread != null) {
950 mOperationThread.interrupt();
951 finish();
952 }
953 }
954 });
955 dialog = working_dialog;
956 break;
957 }
958 case DIALOG_OAUTH2_LOGIN_PROGRESS: {
959 /// oAuth2 dialog. We show here to the user the URL and user_code that the user must validate in a web browser. - OLD!
960 // TODO optimize this dialog
961 ProgressDialog working_dialog = new ProgressDialog(this);
962 /* Leave the old OAuth flow
963 try {
964 if (mCodeResponseJson != null && mCodeResponseJson.has(OAuth2GetCodeRunnable.CODE_VERIFICATION_URL)) {
965 working_dialog.setMessage(String.format(getString(R.string.oauth_code_validation_message),
966 mCodeResponseJson.getString(OAuth2GetCodeRunnable.CODE_VERIFICATION_URL),
967 mCodeResponseJson.getString(OAuth2GetCodeRunnable.CODE_USER_CODE)));
968 } else {*/
969 working_dialog.setMessage(String.format("Getting authorization"));
970 /*}
971 } catch (JSONException e) {
972 Log.e(TAG, "onCreateDialog->JSONException: " + e.toString());
973 }*/
974 working_dialog.setIndeterminate(true);
975 working_dialog.setCancelable(true);
976 working_dialog
977 .setOnCancelListener(new DialogInterface.OnCancelListener() {
978 @Override
979 public void onCancel(DialogInterface dialog) {
980 Log.i(TAG, "Login canceled");
981 /*if (mOAuth2GetCodeThread != null) {
982 mOAuth2GetCodeThread.interrupt();
983 finish();
984 } */
985 /*if (tokenReceiver != null) {
986 unregisterReceiver(tokenReceiver);
987 tokenReceiver = null;
988 finish();
989 }*/
990 finish();
991 }
992 });
993 dialog = working_dialog;
994 break;
995 }
996 case DIALOG_SSL_VALIDATOR: {
997 /// TODO start to use new dialog interface, at least for this (it is a FragmentDialog already)
998 dialog = SslValidatorDialog.newInstance(this, mLastSslUntrustedServerResult, this);
999 break;
1000 }
1001 case DIALOG_CERT_NOT_SAVED: {
1002 AlertDialog.Builder builder = new AlertDialog.Builder(this);
1003 builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
1004 builder.setCancelable(false);
1005 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
1006 @Override
1007 public void onClick(DialogInterface dialog, int which) {
1008 dialog.dismiss();
1009 };
1010 });
1011 dialog = builder.create();
1012 break;
1013 }
1014 default:
1015 Log.e(TAG, "Incorrect dialog called with id = " + id);
1016 }
1017 return dialog;
1018 }
1019
1020
1021 /**
1022 * Starts and activity to open the 'new account' page in the ownCloud web site
1023 *
1024 * @param view 'Account register' button
1025 */
1026 public void onRegisterClick(View view) {
1027 Intent register = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.url_account_register)));
1028 setResult(RESULT_CANCELED);
1029 startActivity(register);
1030 }
1031
1032
1033 /**
1034 * Updates the content and visibility state of the icon and text associated
1035 * to the last check on the ownCloud server.
1036 */
1037 private void updateConnStatus() {
1038 ImageView iv = (ImageView) findViewById(R.id.action_indicator);
1039 TextView tv = (TextView) findViewById(R.id.status_text);
1040
1041 if (mStatusIcon == 0 && mStatusText == 0) {
1042 iv.setVisibility(View.INVISIBLE);
1043 tv.setVisibility(View.INVISIBLE);
1044 } else {
1045 iv.setImageResource(mStatusIcon);
1046 tv.setText(mStatusText);
1047 iv.setVisibility(View.VISIBLE);
1048 tv.setVisibility(View.VISIBLE);
1049 }
1050 }
1051
1052
1053 /**
1054 * Updates the content and visibility state of the icon and text associated
1055 * to the interactions with the OAuth authorization server.
1056 */
1057 private void updateAuthStatus() {
1058 /*ImageView iv = (ImageView) findViewById(R.id.auth_status_icon);
1059 TextView tv = (TextView) findViewById(R.id.auth_status_text);*/
1060
1061 if (mStatusIcon == 0 && mStatusText == 0) {
1062 mAuthStatusLayout.setVisibility(View.INVISIBLE);
1063 /*iv.setVisibility(View.INVISIBLE);
1064 tv.setVisibility(View.INVISIBLE);*/
1065 } else {
1066 mAuthStatusLayout.setText(mStatusText);
1067 mAuthStatusLayout.setCompoundDrawablesWithIntrinsicBounds(mStatusIcon, 0, 0, 0);
1068 /*iv.setImageResource(mStatusIcon);
1069 tv.setText(mStatusText);
1070 /*iv.setVisibility(View.VISIBLE);
1071 tv.setVisibility(View.VISIBLE);^*/
1072 mAuthStatusLayout.setVisibility(View.VISIBLE);
1073 }
1074 }
1075
1076
1077 /**
1078 * Called when the refresh button in the input field for ownCloud host is clicked.
1079 *
1080 * Performs a new check on the URL in the input field.
1081 *
1082 * @param view Refresh 'button'
1083 */
1084 public void onRefreshClick(View view) {
1085 onFocusChange(mRefreshButton, false);
1086 }
1087
1088
1089 /**
1090 * Called when the eye icon in the password field is clicked.
1091 *
1092 * Toggles the visibility of the password in the field.
1093 *
1094 * @param view 'View password' 'button'
1095 */
1096 public void onViewPasswordClick(View view) {
1097 int selectionStart = mPasswordInput.getSelectionStart();
1098 int selectionEnd = mPasswordInput.getSelectionEnd();
1099 int input_type = mPasswordInput.getInputType();
1100 if ((input_type & InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
1101 input_type = InputType.TYPE_CLASS_TEXT
1102 | InputType.TYPE_TEXT_VARIATION_PASSWORD;
1103 } else {
1104 input_type = InputType.TYPE_CLASS_TEXT
1105 | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;
1106 }
1107 mPasswordInput.setInputType(input_type);
1108 mPasswordInput.setSelection(selectionStart, selectionEnd);
1109 }
1110
1111
1112 /**
1113 * Called when the checkbox for OAuth authorization is clicked.
1114 *
1115 * Hides or shows the input fields for user & password.
1116 *
1117 * @param view 'View password' 'button'
1118 */
1119 public void onCheckClick(View view) {
1120 CheckBox oAuth2Check = (CheckBox)view;
1121 changeViewByOAuth2Check(oAuth2Check.isChecked());
1122
1123 }
1124
1125 /**
1126 * Changes the visibility of input elements depending upon the kind of authorization
1127 * chosen by the user: basic or OAuth
1128 *
1129 * @param checked 'True' when OAuth is selected.
1130 */
1131 public void changeViewByOAuth2Check(Boolean checked) {
1132
1133 if (checked) {
1134 mOAuthAuthEndpointText.setVisibility(View.VISIBLE);
1135 mOAuthTokenEndpointText.setVisibility(View.VISIBLE);
1136 mUsernameInput.setVisibility(View.GONE);
1137 mPasswordInput.setVisibility(View.GONE);
1138 mViewPasswordButton.setVisibility(View.GONE);
1139 } else {
1140 mOAuthAuthEndpointText.setVisibility(View.GONE);
1141 mOAuthTokenEndpointText.setVisibility(View.GONE);
1142 mUsernameInput.setVisibility(View.VISIBLE);
1143 mPasswordInput.setVisibility(View.VISIBLE);
1144 mViewPasswordButton.setVisibility(View.INVISIBLE);
1145 }
1146
1147 }
1148
1149 /* Leave the old OAuth flow
1150 // Results from the first call to oAuth2 server : getting the user_code and verification_url.
1151 @Override
1152 public void onOAuth2GetCodeResult(ResultOAuthType type, JSONObject responseJson) {
1153 if ((type == ResultOAuthType.OK_SSL)||(type == ResultOAuthType.OK_NO_SSL)) {
1154 mCodeResponseJson = responseJson;
1155 if (mCodeResponseJson != null) {
1156 getOAuth2AccessTokenFromJsonResponse();
1157 } // else - nothing to do here - wait for callback !!!
1158
1159 } else if (type == ResultOAuthType.HOST_NOT_AVAILABLE) {
1160 updateOAuth2IconAndText(R.drawable.common_error, R.string.oauth_connection_url_unavailable);
1161 }
1162 }
1163
1164 // If the results of getting the user_code and verification_url are OK, we get the received data and we start
1165 // the polling service to oAuth2 server to get a valid token.
1166 private void getOAuth2AccessTokenFromJsonResponse() {
1167 String deviceCode = null;
1168 String verificationUrl = null;
1169 String userCode = null;
1170 int expiresIn = -1;
1171 int interval = -1;
1172
1173 Log.d(TAG, "ResponseOAuth2->" + mCodeResponseJson.toString());
1174
1175 try {
1176 // We get data that we must show to the user or we will use internally.
1177 verificationUrl = mCodeResponseJson.getString(OAuth2GetAuthorizationToken.CODE_VERIFICATION_URL);
1178 userCode = mCodeResponseJson.getString(OAuth2GetAuthorizationToken.CODE_USER_CODE);
1179 expiresIn = mCodeResponseJson.getInt(OAuth2GetAuthorizationToken.CODE_EXPIRES_IN);
1180
1181 // And we get data that we must use to get a token.
1182 deviceCode = mCodeResponseJson.getString(OAuth2GetAuthorizationToken.CODE_DEVICE_CODE);
1183 interval = mCodeResponseJson.getInt(OAuth2GetAuthorizationToken.CODE_INTERVAL);
1184
1185 } catch (JSONException e) {
1186 Log.e(TAG, "Exception accesing data in Json object" + e.toString());
1187 }
1188
1189 // Updating status widget to OK.
1190 updateOAuth2IconAndText(R.drawable.ic_ok, R.string.auth_connection_established);
1191
1192 // Showing the dialog with instructions for the user.
1193 showDialog(DIALOG_OAUTH2_LOGIN_PROGRESS);
1194
1195 // Loggin all the data.
1196 Log.d(TAG, "verificationUrl->" + verificationUrl);
1197 Log.d(TAG, "userCode->" + userCode);
1198 Log.d(TAG, "deviceCode->" + deviceCode);
1199 Log.d(TAG, "expiresIn->" + expiresIn);
1200 Log.d(TAG, "interval->" + interval);
1201
1202 // Starting the pooling service.
1203 try {
1204 Intent tokenService = new Intent(this, OAuth2GetTokenService.class);
1205 tokenService.putExtra(OAuth2GetTokenService.TOKEN_URI, OAuth2Context.OAUTH2_G_DEVICE_GETTOKEN_URL);
1206 tokenService.putExtra(OAuth2GetTokenService.TOKEN_DEVICE_CODE, deviceCode);
1207 tokenService.putExtra(OAuth2GetTokenService.TOKEN_INTERVAL, interval);
1208
1209 startService(tokenService);
1210 }
1211 catch (Exception e) {
1212 Log.e(TAG, "tokenService creation problem :", e);
1213 }
1214
1215 }
1216 */
1217
1218 /* Leave the old OAuth flow
1219 // We get data from the oAuth2 token service with this broadcast receiver.
1220 private class TokenReceiver extends BroadcastReceiver {
1221 /**
1222 * The token is received.
1223 * @author
1224 * {@link BroadcastReceiver} to enable oAuth2 token receiving.
1225 *-/
1226 @Override
1227 public void onReceive(Context context, Intent intent) {
1228 @SuppressWarnings("unchecked")
1229 HashMap<String, String> tokenResponse = (HashMap<String, String>)intent.getExtras().get(OAuth2GetTokenService.TOKEN_RECEIVED_DATA);
1230 Log.d(TAG, "TokenReceiver->" + tokenResponse.get(OAuth2GetTokenService.TOKEN_ACCESS_TOKEN));
1231 dismissDialog(DIALOG_OAUTH2_LOGIN_PROGRESS);
1232
1233 }
1234 }
1235 */
1236
1237
1238 /**
1239 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1240 */
1241 public void onSavedCertificate() {
1242 mOperationThread = mOcServerChkOperation.retry(this, mHandler);
1243 }
1244
1245 /**
1246 * Called from SslValidatorDialog when a new server certificate could not be saved
1247 * when the user requested it.
1248 */
1249 @Override
1250 public void onFailedSavingCertificate() {
1251 showDialog(DIALOG_CERT_NOT_SAVED);
1252 }
1253
1254 }