1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
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.
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/>.
19 package com
.owncloud
.android
.ui
.activity
;
21 import java
.net
.MalformedURLException
;
23 import java
.util
.HashMap
;
26 import org
.json
.JSONException
;
27 import org
.json
.JSONObject
;
29 import com
.owncloud
.android
.AccountUtils
;
30 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
31 import com
.owncloud
.android
.authenticator
.AuthenticationRunnable
;
32 import com
.owncloud
.android
.authenticator
.OnAuthenticationResultListener
;
33 import com
.owncloud
.android
.authenticator
.OnConnectCheckListener
;
34 import com
.owncloud
.android
.authenticator
.oauth2
.OAuth2Context
;
35 import com
.owncloud
.android
.authenticator
.oauth2
.OAuth2GetCodeRunnable
;
36 import com
.owncloud
.android
.authenticator
.oauth2
.OnOAuth2GetCodeResultListener
;
37 import com
.owncloud
.android
.authenticator
.oauth2
.connection
.ConnectorOAuth2
;
38 import com
.owncloud
.android
.authenticator
.oauth2
.services
.OAuth2GetTokenService
;
39 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
;
40 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
.OnSslValidatorListener
;
41 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
42 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
43 import com
.owncloud
.android
.operations
.ConnectionCheckOperation
;
44 import com
.owncloud
.android
.operations
.ExistenceCheckOperation
;
45 import com
.owncloud
.android
.operations
.GetOAuth2AccessToken
;
46 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
47 import com
.owncloud
.android
.operations
.RemoteOperation
;
48 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
50 import android
.accounts
.Account
;
51 import android
.accounts
.AccountAuthenticatorActivity
;
52 import android
.accounts
.AccountManager
;
53 import android
.app
.AlertDialog
;
54 import android
.app
.Dialog
;
55 import android
.app
.ProgressDialog
;
56 import android
.content
.BroadcastReceiver
;
57 import android
.content
.ContentResolver
;
58 import android
.content
.Context
;
59 import android
.content
.DialogInterface
;
60 import android
.content
.Intent
;
61 import android
.content
.IntentFilter
;
62 import android
.content
.SharedPreferences
;
63 import android
.net
.Uri
;
64 import android
.os
.Bundle
;
65 import android
.os
.Handler
;
66 import android
.preference
.PreferenceManager
;
67 import android
.text
.InputType
;
68 import android
.util
.Log
;
69 import android
.view
.View
;
70 import android
.view
.View
.OnClickListener
;
71 import android
.view
.View
.OnFocusChangeListener
;
72 import android
.view
.Window
;
73 import android
.widget
.CheckBox
;
74 import android
.widget
.EditText
;
75 import android
.widget
.Button
;
76 import android
.widget
.ImageView
;
77 import android
.widget
.TextView
;
78 import com
.owncloud
.android
.R
;
80 import eu
.alefzero
.webdav
.WebdavClient
;
83 * This Activity is used to add an ownCloud account to the App
85 * @author Bartek Przybylski
88 public class AuthenticatorActivity
extends AccountAuthenticatorActivity
89 implements OnAuthenticationResultListener
, OnConnectCheckListener
, OnRemoteOperationListener
, OnSslValidatorListener
,
90 OnFocusChangeListener
, OnClickListener
, OnOAuth2GetCodeResultListener
{
92 private static final int DIALOG_LOGIN_PROGRESS
= 0;
93 private static final int DIALOG_SSL_VALIDATOR
= 1;
94 private static final int DIALOG_CERT_NOT_SAVED
= 2;
96 private static final String TAG
= "AuthActivity";
98 private Thread mAuthThread
;
99 private AuthenticationRunnable mAuthRunnable
;
100 private ConnectionCheckOperation mConnChkRunnable
;
101 private ExistenceCheckOperation mAuthChkOperation
;
102 private final Handler mHandler
= new Handler();
103 private String mBaseUrl
;
104 private OwnCloudVersion mDiscoveredVersion
;
106 private static final String STATUS_TEXT
= "STATUS_TEXT";
107 private static final String STATUS_ICON
= "STATUS_ICON";
108 private static final String STATUS_CORRECT
= "STATUS_CORRECT";
109 private static final String IS_SSL_CONN
= "IS_SSL_CONN";
110 private static final String OC_VERSION
= "OC_VERSION";
111 private int mStatusText
, mStatusIcon
;
112 private boolean mStatusCorrect
, mIsSslConn
;
113 private RemoteOperationResult mLastSslUntrustedServerResult
;
115 public static final String PARAM_USERNAME
= "param_Username";
116 public static final String PARAM_HOSTNAME
= "param_Hostname";
119 private static final int OAUTH2_LOGIN_PROGRESS
= 3;
120 private static final String OAUTH2_STATUS_TEXT
= "OAUTH2_STATUS_TEXT";
121 private static final String OAUTH2_STATUS_ICON
= "OAUTH2_STATUS_ICON";
122 private static final String OAUTH2_CODE_RESULT
= "CODE_RESULT";
123 private static final String OAUTH2_IS_CHECKED
= "OAUTH2_IS_CHECKED";
124 private Thread mOAuth2GetCodeThread
;
125 private OAuth2GetCodeRunnable mOAuth2GetCodeRunnable
;
126 private TokenReceiver tokenReceiver
;
127 private JSONObject codeResponseJson
;
128 private int mOAuth2StatusText
, mOAuth2StatusIcon
;
130 public ConnectorOAuth2 connectorOAuth2
;
132 // Variables used to save the on the state the contents of all fields.
133 private static final String HOST_URL_TEXT
= "HOST_URL_TEXT";
134 private static final String ACCOUNT_USERNAME
= "ACCOUNT_USERNAME";
135 private static final String ACCOUNT_PASSWORD
= "ACCOUNT_PASSWORD";
137 //private boolean mNewRedirectUriCaptured;
138 private Uri mNewCapturedUriFromOAuth2Redirection
;
140 // END of oAuth2 variables.
143 protected void onCreate(Bundle savedInstanceState
) {
144 super.onCreate(savedInstanceState
);
145 getWindow().requestFeature(Window
.FEATURE_NO_TITLE
);
146 setContentView(R
.layout
.account_setup
);
147 ImageView iv
= (ImageView
) findViewById(R
.id
.refreshButton
);
148 ImageView iv2
= (ImageView
) findViewById(R
.id
.viewPassword
);
149 TextView tv
= (TextView
) findViewById(R
.id
.host_URL
);
150 TextView tv2
= (TextView
) findViewById(R
.id
.account_password
);
151 EditText oauth2Url
= (EditText
)findViewById(R
.id
.oAuth_URL
);
152 oauth2Url
.setText("OWNCLOUD AUTHORIZATION PROVIDER IN TEST");
154 if (savedInstanceState
!= null
) {
155 mStatusIcon
= savedInstanceState
.getInt(STATUS_ICON
);
156 mStatusText
= savedInstanceState
.getInt(STATUS_TEXT
);
157 mStatusCorrect
= savedInstanceState
.getBoolean(STATUS_CORRECT
);
158 mIsSslConn
= savedInstanceState
.getBoolean(IS_SSL_CONN
);
159 setResultIconAndText(mStatusIcon
, mStatusText
);
160 findViewById(R
.id
.buttonOK
).setEnabled(mStatusCorrect
);
162 iv
.setVisibility(View
.VISIBLE
);
164 iv
.setVisibility(View
.INVISIBLE
);
166 String ocVersion
= savedInstanceState
.getString(OC_VERSION
, null
);
167 if (ocVersion
!= null
)
168 mDiscoveredVersion
= new OwnCloudVersion(ocVersion
);
170 // Getting the state of oAuth2 components.
171 mOAuth2StatusIcon
= savedInstanceState
.getInt(OAUTH2_STATUS_ICON
);
172 mOAuth2StatusText
= savedInstanceState
.getInt(OAUTH2_STATUS_TEXT
);
173 // We set this to true if the rotation happens when the user is validating oAuth2 user_code.
174 changeViewByOAuth2Check(savedInstanceState
.getBoolean(OAUTH2_IS_CHECKED
));
175 // We store a JSon object with all the data returned from oAuth2 server when we get user_code.
176 // Is better than store variable by variable. We use String object to serialize from/to it.
178 if (savedInstanceState
.containsKey(OAUTH2_CODE_RESULT
)) {
179 codeResponseJson
= new JSONObject(savedInstanceState
.getString(OAUTH2_CODE_RESULT
));
181 } catch (JSONException e
) {
182 Log
.e(TAG
, "onCreate->JSONException: " + e
.toString());
184 // END of getting the state of oAuth2 components.
186 // Getting contents of each field.
187 EditText hostUrl
= (EditText
)findViewById(R
.id
.host_URL
);
188 hostUrl
.setText(savedInstanceState
.getString(HOST_URL_TEXT
), TextView
.BufferType
.EDITABLE
);
189 EditText accountUsername
= (EditText
)findViewById(R
.id
.account_username
);
190 accountUsername
.setText(savedInstanceState
.getString(ACCOUNT_USERNAME
), TextView
.BufferType
.EDITABLE
);
191 EditText accountPassword
= (EditText
)findViewById(R
.id
.account_password
);
192 accountPassword
.setText(savedInstanceState
.getString(ACCOUNT_PASSWORD
), TextView
.BufferType
.EDITABLE
);
193 // END of getting contents of each field
196 mStatusText
= mStatusIcon
= 0;
197 mStatusCorrect
= false
;
200 iv
.setOnClickListener(this);
201 iv2
.setOnClickListener(this);
202 tv
.setOnFocusChangeListener(this);
203 tv2
.setOnFocusChangeListener(this);
205 Button b
= (Button
) findViewById(R
.id
.account_register
);
207 b
.setText(String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
210 mNewCapturedUriFromOAuth2Redirection
= null
;
215 protected void onNewIntent (Intent intent
) {
216 Uri data
= intent
.getData();
217 //mNewRedirectUriCaptured = (data != null && data.toString().startsWith(OAuth2Context.MY_REDIRECT_URI));
218 if (data
!= null
&& data
.toString().startsWith(OAuth2Context
.MY_REDIRECT_URI
)) {
219 mNewCapturedUriFromOAuth2Redirection
= data
;
221 Log
.d(TAG
, "onNewIntent()");
227 protected void onSaveInstanceState(Bundle outState
) {
228 outState
.putInt(STATUS_ICON
, mStatusIcon
);
229 outState
.putInt(STATUS_TEXT
, mStatusText
);
230 outState
.putBoolean(STATUS_CORRECT
, mStatusCorrect
);
231 if (mDiscoveredVersion
!= null
)
232 outState
.putString(OC_VERSION
, mDiscoveredVersion
.toString());
234 // Saving the state of oAuth2 components.
235 outState
.putInt(OAUTH2_STATUS_ICON
, mOAuth2StatusIcon
);
236 outState
.putInt(OAUTH2_STATUS_TEXT
, mOAuth2StatusText
);
237 CheckBox oAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
238 outState
.putBoolean(OAUTH2_IS_CHECKED
, oAuth2Check
.isChecked());
239 if (codeResponseJson
!= null
){
240 outState
.putString(OAUTH2_CODE_RESULT
, codeResponseJson
.toString());
242 // END of saving the state of oAuth2 components.
244 // Saving contents of each field.
245 outState
.putString(HOST_URL_TEXT
,((TextView
) findViewById(R
.id
.host_URL
)).getText().toString().trim());
246 outState
.putString(ACCOUNT_USERNAME
,((TextView
) findViewById(R
.id
.account_username
)).getText().toString().trim());
247 outState
.putString(ACCOUNT_PASSWORD
,((TextView
) findViewById(R
.id
.account_password
)).getText().toString().trim());
249 super.onSaveInstanceState(outState
);
253 protected Dialog
onCreateDialog(int id
) {
254 Dialog dialog
= null
;
256 case DIALOG_LOGIN_PROGRESS
: {
257 ProgressDialog working_dialog
= new ProgressDialog(this);
258 working_dialog
.setMessage(getResources().getString(
259 R
.string
.auth_trying_to_login
));
260 working_dialog
.setIndeterminate(true
);
261 working_dialog
.setCancelable(true
);
263 .setOnCancelListener(new DialogInterface
.OnCancelListener() {
265 public void onCancel(DialogInterface dialog
) {
266 Log
.i(TAG
, "Login canceled");
267 if (mAuthThread
!= null
) {
268 mAuthThread
.interrupt();
273 dialog
= working_dialog
;
276 // oAuth2 dialog. We show here to the user the URL and user_code that the user must validate in a web browser.
277 case OAUTH2_LOGIN_PROGRESS
: {
278 ProgressDialog working_dialog
= new ProgressDialog(this);
280 if (codeResponseJson
!= null
&& codeResponseJson
.has(OAuth2GetCodeRunnable
.CODE_VERIFICATION_URL
)) {
281 working_dialog
.setMessage(String
.format(getString(R
.string
.oauth_code_validation_message
),
282 codeResponseJson
.getString(OAuth2GetCodeRunnable
.CODE_VERIFICATION_URL
),
283 codeResponseJson
.getString(OAuth2GetCodeRunnable
.CODE_USER_CODE
)));
285 working_dialog
.setMessage(String
.format("Getting authorization"));
287 } catch (JSONException e
) {
288 Log
.e(TAG
, "onCreateDialog->JSONException: " + e
.toString());
290 working_dialog
.setIndeterminate(true
);
291 working_dialog
.setCancelable(true
);
293 .setOnCancelListener(new DialogInterface
.OnCancelListener() {
295 public void onCancel(DialogInterface dialog
) {
296 Log
.i(TAG
, "Login canceled");
297 if (mOAuth2GetCodeThread
!= null
) {
298 mOAuth2GetCodeThread
.interrupt();
301 if (tokenReceiver
!= null
) {
302 unregisterReceiver(tokenReceiver
);
303 tokenReceiver
= null
;
308 dialog
= working_dialog
;
311 case DIALOG_SSL_VALIDATOR
: {
312 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
315 case DIALOG_CERT_NOT_SAVED
: {
316 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
317 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
318 builder
.setCancelable(false
);
319 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
321 public void onClick(DialogInterface dialog
, int which
) {
325 dialog
= builder
.create();
329 Log
.e(TAG
, "Incorrect dialog called with id = " + id
);
335 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
337 case DIALOG_LOGIN_PROGRESS
:
338 case DIALOG_CERT_NOT_SAVED
:
339 case OAUTH2_LOGIN_PROGRESS
:
341 case DIALOG_SSL_VALIDATOR
: {
342 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
346 Log
.e(TAG
, "Incorrect dialog called with id = " + id
);
351 protected void onResume() {
352 Log
.d(TAG
, "onResume() start");
353 // (old oauth code) Registering token receiver. We must listening to the service that is pooling to the oAuth server for a token.
354 if (tokenReceiver
== null
) {
355 IntentFilter tokenFilter
= new IntentFilter(OAuth2GetTokenService
.TOKEN_RECEIVED_MESSAGE
);
356 tokenReceiver
= new TokenReceiver();
357 this.registerReceiver(tokenReceiver
,tokenFilter
);
360 /*if (mNewRedirectUriCaptured) {
361 mNewRedirectUriCaptured = false;*/
362 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
363 getOAuth2AccessTokenFromCapturedRedirection();
370 protected void onPause() {
371 Log
.d(TAG
, "onPause() start");
376 public void onAuthenticationResult(boolean success
, String message
) {
378 TextView username_text
= (TextView
) findViewById(R
.id
.account_username
), password_text
= (TextView
) findViewById(R
.id
.account_password
);
382 url
= new URL(message
);
383 } catch (MalformedURLException e
) {
384 // should never happen
385 Log
.e(getClass().getName(), "Malformed URL: " + message
);
389 String username
= username_text
.getText().toString().trim();
390 String accountName
= username
+ "@" + url
.getHost();
391 if (url
.getPort() >= 0) {
392 accountName
+= ":" + url
.getPort();
394 Account account
= new Account(accountName
,
395 AccountAuthenticator
.ACCOUNT_TYPE
);
396 AccountManager accManager
= AccountManager
.get(this);
397 accManager
.addAccountExplicitly(account
, password_text
.getText()
400 // Add this account as default in the preferences, if there is none
402 Account defaultAccount
= AccountUtils
403 .getCurrentOwnCloudAccount(this);
404 if (defaultAccount
== null
) {
405 SharedPreferences
.Editor editor
= PreferenceManager
406 .getDefaultSharedPreferences(this).edit();
407 editor
.putString("select_oc_account", accountName
);
411 final Intent intent
= new Intent();
412 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
,
413 AccountAuthenticator
.ACCOUNT_TYPE
);
414 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, account
.name
);
415 intent
.putExtra(AccountManager
.KEY_AUTHTOKEN
,
416 AccountAuthenticator
.ACCOUNT_TYPE
);
417 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
419 accManager
.setUserData(account
, AccountAuthenticator
.KEY_OC_URL
,
421 accManager
.setUserData(account
,
422 AccountAuthenticator
.KEY_OC_VERSION
, mDiscoveredVersion
.toString());
424 accManager
.setUserData(account
,
425 AccountAuthenticator
.KEY_OC_BASE_URL
, mBaseUrl
);
427 setAccountAuthenticatorResult(intent
.getExtras());
428 setResult(RESULT_OK
, intent
);
429 Bundle bundle
= new Bundle();
430 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
431 //getContentResolver().startSync(ProviderTableMeta.CONTENT_URI,
433 ContentResolver
.requestSync(account
, "org.owncloud", bundle
);
437 * (mConnChkRunnable.getDiscoveredVersion().compareTo(OwnCloudVersion
438 * .owncloud_v2) >= 0) { Intent i = new Intent(this,
439 * ExtensionsAvailableActivity.class); startActivity(i); }
445 dismissDialog(DIALOG_LOGIN_PROGRESS
);
446 } catch (IllegalArgumentException e
) {
447 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
449 TextView tv
= (TextView
) findViewById(R
.id
.account_username
);
450 tv
.setError(message
+ " "); // the extra spaces are a workaround for an ugly bug:
451 // 1. insert wrong credentials and connect
452 // 2. put the focus on the user name field with using hardware controls (don't touch the screen); the error is shown UNDER the field
453 // 3. touch the user name field; the software keyboard appears; the error popup is moved OVER the field and SHRINKED in width, losing the last word
454 // Seen, at least, in Android 2.x devices
457 public void onCancelClick(View view
) {
458 setResult(RESULT_CANCELED
);
462 public void onOkClick(View view
) {
464 String url
= ((TextView
) findViewById(R
.id
.host_URL
)).getText()
471 if (url
.toLowerCase().startsWith("http://")
472 || url
.toLowerCase().startsWith("https://")) {
475 CheckBox oAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
476 if (oAuth2Check
!= null
&& oAuth2Check
.isChecked()) {
477 startOauthorization();
480 continueConnection(prefix
);
484 private void startOauthorization() {
485 // We start a thread to get an authorization code from the oAuth2 server.
486 setOAuth2ResultIconAndText(R
.drawable
.progress_small
, R
.string
.oauth_login_connection
);
487 mOAuth2GetCodeRunnable
= new OAuth2GetCodeRunnable(OAuth2Context
.OAUTH2_F_AUTHORIZATION_ENDPOINT_URL
, this);
488 //mOAuth2GetCodeRunnable = new OAuth2GetCodeRunnable(OAuth2Context.OAUTH2_G_DEVICE_GETCODE_URL, this);
489 mOAuth2GetCodeRunnable
.setListener(this, mHandler
);
490 mOAuth2GetCodeThread
= new Thread(mOAuth2GetCodeRunnable
);
491 mOAuth2GetCodeThread
.start();
494 public void onRegisterClick(View view
) {
495 Intent register
= new Intent(Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.url_account_register
)));
496 setResult(RESULT_CANCELED
);
497 startActivity(register
);
500 private void continueConnection(String prefix
) {
501 String url
= ((TextView
) findViewById(R
.id
.host_URL
)).getText()
503 String username
= ((TextView
) findViewById(R
.id
.account_username
))
504 .getText().toString();
505 String password
= ((TextView
) findViewById(R
.id
.account_password
))
506 .getText().toString();
507 if (url
.endsWith("/"))
508 url
= url
.substring(0, url
.length() - 1);
511 mDiscoveredVersion
= mConnChkRunnable
.getDiscoveredVersion();
512 String webdav_path
= AccountUtils
.getWebdavPath(mDiscoveredVersion
);
514 if (webdav_path
== null
) {
515 onAuthenticationResult(false
, getString(R
.string
.auth_bad_oc_version_title
));
520 mBaseUrl
= prefix
+ url
;
521 String url_str
= prefix
+ url
+ webdav_path
;
522 uri
= new URL(url_str
);
523 } catch (MalformedURLException e
) {
524 // should never happen
525 onAuthenticationResult(false
, getString(R
.string
.auth_incorrect_address_title
));
529 showDialog(DIALOG_LOGIN_PROGRESS
);
530 mAuthRunnable
= new AuthenticationRunnable(uri
, username
, password
, this);
531 mAuthRunnable
.setOnAuthenticationResultListener(this, mHandler
);
532 mAuthThread
= new Thread(mAuthRunnable
);
537 public void onConnectionCheckResult(ResultType type
) {
538 mStatusText
= mStatusIcon
= 0;
539 mStatusCorrect
= false
;
540 String t_url
= ((TextView
) findViewById(R
.id
.host_URL
)).getText()
541 .toString().trim().toLowerCase();
546 mStatusIcon
= android
.R
.drawable
.ic_secure
;
547 mStatusText
= R
.string
.auth_secure_connection
;
548 mStatusCorrect
= true
;
552 mStatusCorrect
= true
;
553 if (t_url
.startsWith("http://") ) {
554 mStatusText
= R
.string
.auth_connection_established
;
555 mStatusIcon
= R
.drawable
.ic_ok
;
557 mStatusText
= R
.string
.auth_nossl_plain_ok_title
;
558 mStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
562 mStatusIcon
= R
.drawable
.common_error
;
563 mStatusText
= R
.string
.auth_bad_oc_version_title
;
565 case WRONG_CONNECTION
:
566 mStatusIcon
= R
.drawable
.common_error
;
567 mStatusText
= R
.string
.auth_wrong_connection_title
;
570 mStatusIcon
= R
.drawable
.common_error
;
571 mStatusText
= R
.string
.auth_timeout_title
;
573 case INCORRECT_ADDRESS
:
574 mStatusIcon
= R
.drawable
.common_error
;
575 mStatusText
= R
.string
.auth_incorrect_address_title
;
577 case SSL_UNVERIFIED_SERVER
:
578 mStatusIcon
= R
.drawable
.common_error
;
579 mStatusText
= R
.string
.auth_ssl_unverified_server_title
;
582 mStatusIcon
= R
.drawable
.common_error
;
583 mStatusText
= R
.string
.auth_ssl_general_error_title
;
585 case HOST_NOT_AVAILABLE
:
586 mStatusIcon
= R
.drawable
.common_error
;
587 mStatusText
= R
.string
.auth_unknown_host_title
;
589 case NO_NETWORK_CONNECTION
:
590 mStatusIcon
= R
.drawable
.no_network
;
591 mStatusText
= R
.string
.auth_no_net_conn_title
;
593 case INSTANCE_NOT_CONFIGURED
:
594 mStatusIcon
= R
.drawable
.common_error
;
595 mStatusText
= R
.string
.auth_not_configured_title
;
598 mStatusIcon
= R
.drawable
.common_error
;
599 mStatusText
= R
.string
.auth_unknown_error_title
;
602 mStatusIcon
= R
.drawable
.common_error
;
603 mStatusText
= R
.string
.auth_incorrect_path_title
;
606 Log
.e(TAG
, "Incorrect connection checker result type: " + type
);
608 setResultIconAndText(mStatusIcon
, mStatusText
);
610 findViewById(R
.id
.refreshButton
).setVisibility(View
.VISIBLE
);
612 findViewById(R
.id
.refreshButton
).setVisibility(View
.INVISIBLE
);
613 findViewById(R
.id
.buttonOK
).setEnabled(mStatusCorrect
);
617 public void onFocusChange(View view
, boolean hasFocus
) {
618 if (view
.getId() == R
.id
.host_URL
) {
620 TextView tv
= ((TextView
) findViewById(R
.id
.host_URL
));
621 String uri
= tv
.getText().toString().trim();
622 if (uri
.length() != 0) {
623 setResultIconAndText(R
.drawable
.progress_small
,
624 R
.string
.auth_testing_connection
);
625 //mConnChkRunnable = new ConnectionCheckerRunnable(uri, this);
626 mConnChkRunnable
= new ConnectionCheckOperation(uri
, this);
627 //mConnChkRunnable.setListener(this, mHandler);
628 //mAuthThread = new Thread(mConnChkRunnable);
629 //mAuthThread.start();
630 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(uri
), this);
631 mDiscoveredVersion
= null
;
632 mAuthThread
= mConnChkRunnable
.execute(client
, this, mHandler
);
634 findViewById(R
.id
.refreshButton
).setVisibility(
636 setResultIconAndText(0, 0);
639 // avoids that the 'connect' button can be clicked if the test was previously passed
640 findViewById(R
.id
.buttonOK
).setEnabled(false
);
642 } else if (view
.getId() == R
.id
.account_password
) {
643 ImageView iv
= (ImageView
) findViewById(R
.id
.viewPassword
);
645 iv
.setVisibility(View
.VISIBLE
);
647 TextView v
= (TextView
) findViewById(R
.id
.account_password
);
648 int input_type
= InputType
.TYPE_CLASS_TEXT
649 | InputType
.TYPE_TEXT_VARIATION_PASSWORD
;
650 v
.setInputType(input_type
);
651 iv
.setVisibility(View
.INVISIBLE
);
656 private void setResultIconAndText(int drawable_id
, int text_id
) {
657 ImageView iv
= (ImageView
) findViewById(R
.id
.action_indicator
);
658 TextView tv
= (TextView
) findViewById(R
.id
.status_text
);
660 if (drawable_id
== 0 && text_id
== 0) {
661 iv
.setVisibility(View
.INVISIBLE
);
662 tv
.setVisibility(View
.INVISIBLE
);
664 iv
.setImageResource(drawable_id
);
666 iv
.setVisibility(View
.VISIBLE
);
667 tv
.setVisibility(View
.VISIBLE
);
672 public void onClick(View v
) {
673 if (v
.getId() == R
.id
.refreshButton
) {
674 onFocusChange(findViewById(R
.id
.host_URL
), false
);
675 } else if (v
.getId() == R
.id
.viewPassword
) {
676 TextView view
= (TextView
) findViewById(R
.id
.account_password
);
677 int input_type
= view
.getInputType();
678 if ((input_type
& InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) == InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) {
679 input_type
= InputType
.TYPE_CLASS_TEXT
680 | InputType
.TYPE_TEXT_VARIATION_PASSWORD
;
682 input_type
= InputType
.TYPE_CLASS_TEXT
683 | InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
;
685 view
.setInputType(input_type
);
689 @Override protected void onDestroy() {
690 // We must stop the service thats it's pooling to oAuth2 server for a token.
691 Intent tokenService
= new Intent(this, OAuth2GetTokenService
.class);
692 stopService(tokenService
);
694 // We stop listening the result of the pooling service.
695 if (tokenReceiver
!= null
) {
696 unregisterReceiver(tokenReceiver
);
697 tokenReceiver
= null
;
704 // Controlling the oAuth2 checkbox on the activity: hide and show widgets.
705 public void onOff_check_Click(View view
) {
706 CheckBox oAuth2Check
= (CheckBox
)view
;
707 changeViewByOAuth2Check(oAuth2Check
.isChecked());
711 public void changeViewByOAuth2Check(Boolean checked
) {
713 EditText oAuth2Url
= (EditText
) findViewById(R
.id
.oAuth_URL
);
714 EditText accountUsername
= (EditText
) findViewById(R
.id
.account_username
);
715 EditText accountPassword
= (EditText
) findViewById(R
.id
.account_password
);
716 ImageView viewPassword
= (ImageView
) findViewById(R
.id
.viewPassword
);
717 ImageView auth2ActionIndicator
= (ImageView
) findViewById(R
.id
.auth2_action_indicator
);
718 TextView oauth2StatusText
= (TextView
) findViewById(R
.id
.oauth2_status_text
);
721 oAuth2Url
.setVisibility(View
.VISIBLE
);
722 accountUsername
.setVisibility(View
.GONE
);
723 accountPassword
.setVisibility(View
.GONE
);
724 viewPassword
.setVisibility(View
.GONE
);
725 auth2ActionIndicator
.setVisibility(View
.INVISIBLE
);
726 oauth2StatusText
.setVisibility(View
.INVISIBLE
);
728 oAuth2Url
.setVisibility(View
.GONE
);
729 accountUsername
.setVisibility(View
.VISIBLE
);
730 accountPassword
.setVisibility(View
.VISIBLE
);
731 viewPassword
.setVisibility(View
.INVISIBLE
);
732 auth2ActionIndicator
.setVisibility(View
.GONE
);
733 oauth2StatusText
.setVisibility(View
.GONE
);
738 // Controlling the oAuth2 result of server connection.
739 private void setOAuth2ResultIconAndText(int drawable_id
, int text_id
) {
740 ImageView iv
= (ImageView
) findViewById(R
.id
.auth2_action_indicator
);
741 TextView tv
= (TextView
) findViewById(R
.id
.oauth2_status_text
);
743 if (drawable_id
== 0 && text_id
== 0) {
744 iv
.setVisibility(View
.INVISIBLE
);
745 tv
.setVisibility(View
.INVISIBLE
);
747 iv
.setImageResource(drawable_id
);
749 iv
.setVisibility(View
.VISIBLE
);
750 tv
.setVisibility(View
.VISIBLE
);
754 // Results from the first call to oAuth2 server : getting the user_code and verification_url.
756 public void onOAuth2GetCodeResult(ResultOAuthType type
, JSONObject responseJson
) {
757 if ((type
== ResultOAuthType
.OK_SSL
)||(type
== ResultOAuthType
.OK_NO_SSL
)) {
758 codeResponseJson
= responseJson
;
759 if (codeResponseJson
!= null
) {
760 getOAuth2AccessTokenFromJsonResponse();
761 } // else - nothing to do here - wait for callback !!!
763 } else if (type
== ResultOAuthType
.HOST_NOT_AVAILABLE
) {
764 setOAuth2ResultIconAndText(R
.drawable
.common_error
, R
.string
.oauth_connection_url_unavailable
);
768 // If the results of getting the user_code and verification_url are OK, we get the received data and we start
769 // the polling service to oAuth2 server to get a valid token.
770 private void getOAuth2AccessTokenFromJsonResponse() {
771 String deviceCode
= null
;
772 String verificationUrl
= null
;
773 String userCode
= null
;
777 Log
.d(TAG
, "ResponseOAuth2->" + codeResponseJson
.toString());
780 // We get data that we must show to the user or we will use internally.
781 verificationUrl
= codeResponseJson
.getString(OAuth2GetCodeRunnable
.CODE_VERIFICATION_URL
);
782 userCode
= codeResponseJson
.getString(OAuth2GetCodeRunnable
.CODE_USER_CODE
);
783 expiresIn
= codeResponseJson
.getInt(OAuth2GetCodeRunnable
.CODE_EXPIRES_IN
);
785 // And we get data that we must use to get a token.
786 deviceCode
= codeResponseJson
.getString(OAuth2GetCodeRunnable
.CODE_DEVICE_CODE
);
787 interval
= codeResponseJson
.getInt(OAuth2GetCodeRunnable
.CODE_INTERVAL
);
789 } catch (JSONException e
) {
790 Log
.e(TAG
, "Exception accesing data in Json object" + e
.toString());
793 // Updating status widget to OK.
794 setOAuth2ResultIconAndText(R
.drawable
.ic_ok
, R
.string
.auth_connection_established
);
796 // Showing the dialog with instructions for the user.
797 showDialog(OAUTH2_LOGIN_PROGRESS
);
799 // Loggin all the data.
800 Log
.d(TAG
, "verificationUrl->" + verificationUrl
);
801 Log
.d(TAG
, "userCode->" + userCode
);
802 Log
.d(TAG
, "deviceCode->" + deviceCode
);
803 Log
.d(TAG
, "expiresIn->" + expiresIn
);
804 Log
.d(TAG
, "interval->" + interval
);
806 // Starting the pooling service.
808 Intent tokenService
= new Intent(this, OAuth2GetTokenService
.class);
809 tokenService
.putExtra(OAuth2GetTokenService
.TOKEN_URI
, OAuth2Context
.OAUTH2_G_DEVICE_GETTOKEN_URL
);
810 tokenService
.putExtra(OAuth2GetTokenService
.TOKEN_DEVICE_CODE
, deviceCode
);
811 tokenService
.putExtra(OAuth2GetTokenService
.TOKEN_INTERVAL
, interval
);
813 startService(tokenService
);
815 catch (Exception e
) {
816 Log
.e(TAG
, "tokenService creation problem :", e
);
821 private void getOAuth2AccessTokenFromCapturedRedirection() {
822 Map
<String
, String
> responseValues
= new HashMap
<String
, String
>();
823 //String queryParameters = getIntent().getData().getQuery();
824 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
825 mNewCapturedUriFromOAuth2Redirection
= null
;
827 Log
.v(TAG
, "Queryparameters (Code) = " + queryParameters
);
829 String
[] pairs
= queryParameters
.split("&");
830 Log
.v(TAG
, "Pairs (Code) = " + pairs
.toString());
836 StringBuilder sb
= new StringBuilder();
838 while (pairs
.length
> i
) {
840 String
[] part
= pairs
[i
].split("=");
842 while (part
.length
> j
) {
846 sb
.append(key
+ " = ");
849 responseValues
.put(key
, value
);
850 sb
.append(value
+ "\n");
853 Log
.v(TAG
, "[" + i
+ "," + j
+ "] = " + p
);
860 // Updating status widget to OK.
861 setOAuth2ResultIconAndText(R
.drawable
.ic_ok
, R
.string
.auth_connection_established
);
863 // Showing the dialog with instructions for the user.
864 showDialog(OAUTH2_LOGIN_PROGRESS
);
867 RemoteOperation operation
= new GetOAuth2AccessToken(responseValues
);
868 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(OAuth2Context
.OAUTH2_F_TOKEN_ENDPOINT_URL
), getApplicationContext());
869 operation
.execute(client
, this, mHandler
);
874 // We get data from the oAuth2 token service with this broadcast receiver.
875 private class TokenReceiver
extends BroadcastReceiver
{
877 * The token is received.
879 * {@link BroadcastReceiver} to enable oAuth2 token receiving.
882 public void onReceive(Context context
, Intent intent
) {
883 @SuppressWarnings("unchecked")
884 HashMap
<String
, String
> tokenResponse
= (HashMap
<String
, String
>)intent
.getExtras().get(OAuth2GetTokenService
.TOKEN_RECEIVED_DATA
);
885 Log
.d(TAG
, "TokenReceiver->" + tokenResponse
.get(OAuth2GetTokenService
.TOKEN_ACCESS_TOKEN
));
886 dismissDialog(OAUTH2_LOGIN_PROGRESS
);
892 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
893 if (operation
instanceof ConnectionCheckOperation
) {
895 mStatusText
= mStatusIcon
= 0;
896 mStatusCorrect
= false
;
897 String t_url
= ((TextView
) findViewById(R
.id
.host_URL
)).getText()
898 .toString().trim().toLowerCase();
900 switch (result
.getCode()) {
903 mStatusIcon
= android
.R
.drawable
.ic_secure
;
904 mStatusText
= R
.string
.auth_secure_connection
;
905 mStatusCorrect
= true
;
911 mStatusCorrect
= true
;
912 if (t_url
.startsWith("http://") ) {
913 mStatusText
= R
.string
.auth_connection_established
;
914 mStatusIcon
= R
.drawable
.ic_ok
;
916 mStatusText
= R
.string
.auth_nossl_plain_ok_title
;
917 mStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
923 mStatusIcon
= R
.drawable
.common_error
;
924 mStatusText
= R
.string
.auth_bad_oc_version_title
;
926 case WRONG_CONNECTION
:
927 mStatusIcon
= R
.drawable
.common_error
;
928 mStatusText
= R
.string
.auth_wrong_connection_title
;
931 mStatusIcon
= R
.drawable
.common_error
;
932 mStatusText
= R
.string
.auth_timeout_title
;
934 case INCORRECT_ADDRESS
:
935 mStatusIcon
= R
.drawable
.common_error
;
936 mStatusText
= R
.string
.auth_incorrect_address_title
;
939 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
940 mStatusIcon
= R
.drawable
.common_error
;
941 mStatusText
= R
.string
.auth_ssl_unverified_server_title
;
942 mLastSslUntrustedServerResult
= result
;
943 showDialog(DIALOG_SSL_VALIDATOR
);
947 mStatusIcon
= R
.drawable
.common_error
;
948 mStatusText
= R
.string
.auth_ssl_general_error_title
;
951 case HOST_NOT_AVAILABLE
:
952 mStatusIcon
= R
.drawable
.common_error
;
953 mStatusText
= R
.string
.auth_unknown_host_title
;
955 case NO_NETWORK_CONNECTION
:
956 mStatusIcon
= R
.drawable
.no_network
;
957 mStatusText
= R
.string
.auth_no_net_conn_title
;
959 case INSTANCE_NOT_CONFIGURED
:
960 mStatusIcon
= R
.drawable
.common_error
;
961 mStatusText
= R
.string
.auth_not_configured_title
;
964 mStatusIcon
= R
.drawable
.common_error
;
965 mStatusText
= R
.string
.auth_incorrect_path_title
;
967 case UNHANDLED_HTTP_CODE
:
969 mStatusIcon
= R
.drawable
.common_error
;
970 mStatusText
= R
.string
.auth_unknown_error_title
;
973 Log
.e(TAG
, "Incorrect connection checker result type: " + result
.getHttpCode());
975 setResultIconAndText(mStatusIcon
, mStatusText
);
977 findViewById(R
.id
.refreshButton
).setVisibility(View
.VISIBLE
);
979 findViewById(R
.id
.refreshButton
).setVisibility(View
.INVISIBLE
);
980 findViewById(R
.id
.buttonOK
).setEnabled(mStatusCorrect
);
982 } else if (operation
instanceof GetOAuth2AccessToken
) {
985 dismissDialog(OAUTH2_LOGIN_PROGRESS
);
986 } catch (IllegalArgumentException e
) {
987 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
990 if (result
.isSuccess()) {
992 /// time to test the retrieved access token on the ownCloud server
993 String url
= ((TextView
) findViewById(R
.id
.host_URL
)).getText()
995 if (url
.endsWith("/"))
996 url
= url
.substring(0, url
.length() - 1);
999 /*String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion);
1001 if (webdav_path == null) {
1002 onAuthenticationResult(false, getString(R.string.auth_bad_oc_version_title));
1008 prefix
= "https://";
1012 if (url
.toLowerCase().startsWith("http://")
1013 || url
.toLowerCase().startsWith("https://")) {
1018 mBaseUrl
= prefix
+ url
;
1019 //String url_str = prefix + url + webdav_path;
1020 String url_str
= prefix
+ url
+ "/remote.php/odav";
1021 uri
= Uri
.parse(url_str
);
1023 } catch (Exception e
) {
1024 // should never happen
1025 onAuthenticationResult(false
, getString(R
.string
.auth_incorrect_address_title
));
1029 showDialog(DIALOG_LOGIN_PROGRESS
);
1030 String accessToken
= ((GetOAuth2AccessToken
)operation
).getResultTokenMap().get(OAuth2Context
.KEY_ACCESS_TOKEN
);
1031 Log
.d(TAG
, "ACCESS TOKEN: " + accessToken
);
1032 mAuthChkOperation
= new ExistenceCheckOperation("", this, accessToken
);
1033 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(uri
, getApplicationContext());
1034 mAuthChkOperation
.execute(client
, this, mHandler
);
1038 TextView tv
= (TextView
) findViewById(R
.id
.oAuth_URL
);
1039 tv
.setError("A valid authorization could not be obtained");
1043 } else if (operation
instanceof ExistenceCheckOperation
) {
1046 dismissDialog(DIALOG_LOGIN_PROGRESS
);
1047 } catch (IllegalArgumentException e
) {
1048 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
1051 if (result
.isSuccess()) {
1052 TextView tv
= (TextView
) findViewById(R
.id
.oAuth_URL
);
1053 tv
.setError("OOOOOKKKKKK");
1054 Log
.d(TAG
, "OOOOK!!!!");
1056 Uri uri = Uri.parse(mBaseUrl);
1057 String username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();
1058 String accountName = username + "@" + uri.getHost();
1059 if (uri.getPort() >= 0) {
1060 accountName += ":" + uri.getPort();
1062 // TODO - check that accountName does not exist
1063 Account account = new Account(accountName, AccountAuthenticator.ACCOUNT_TYPE);
1064 AccountManager accManager = AccountManager.get(this);
1065 /// TODO SAVE THE ACCESS TOKEN, HERE OR IN SOME BETTER PLACE
1066 //accManager.addAccountExplicitly(account, mAccesToken, null); //// IS THIS REALLY NEEDED? IS NOT REDUNDANT WITH SETACCOUNTAUTHENTICATORRESULT?
1068 // Add this account as default in the preferences, if there is none
1069 Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
1070 if (defaultAccount == null) {
1071 SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
1072 editor.putString("select_oc_account", accountName);
1076 /// account data to save by the AccountManager
1077 final Intent intent = new Intent();
1078 intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, AccountAuthenticator.ACCOUNT_TYPE);
1079 intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, account.name);
1080 intent.putExtra(AccountManager.KEY_AUTHTOKEN, AccountAuthenticator.ACCOUNT_TYPE);
1081 intent.putExtra(AccountManager.KEY_USERDATA, username);
1082 intent.putExtra(AccountManager.KEY_AUTHTOKEN, mAccessToken)
1084 accManager.setUserData(account, AccountAuthenticator.KEY_OC_VERSION, mConnChkRunnable.getDiscoveredVersion().toString());
1085 accManager.setUserData(account, AccountAuthenticator.KEY_OC_BASE_URL, mBaseUrl);
1087 setAccountAuthenticatorResult(intent.getExtras());
1088 setResult(RESULT_OK, intent);
1090 /// enforce the first account synchronization
1091 Bundle bundle = new Bundle();
1092 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
1093 ContentResolver.requestSync(account, "org.owncloud", bundle);
1099 TextView tv
= (TextView
) findViewById(R
.id
.oAuth_URL
);
1100 tv
.setError(result
.getLogMessage());
1101 Log
.d(TAG
, "NOOOOO " + result
.getLogMessage());
1107 public void onSavedCertificate() {
1108 mAuthThread
= mConnChkRunnable
.retry(this, mHandler
);
1112 public void onFailedSavingCertificate() {
1113 showDialog(DIALOG_CERT_NOT_SAVED
);