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
, false
);
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
);
616 public void onFocusChange(View view
, boolean hasFocus
) {
617 if (view
.getId() == R
.id
.host_URL
) {
619 TextView tv
= ((TextView
) findViewById(R
.id
.host_URL
));
620 String uri
= tv
.getText().toString().trim();
621 if (uri
.length() != 0) {
622 setResultIconAndText(R
.drawable
.progress_small
,
623 R
.string
.auth_testing_connection
);
624 //mConnChkRunnable = new ConnectionCheckerRunnable(uri, this);
625 mConnChkRunnable
= new ConnectionCheckOperation(uri
, this);
626 //mConnChkRunnable.setListener(this, mHandler);
627 //mAuthThread = new Thread(mConnChkRunnable);
628 //mAuthThread.start();
629 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(uri
), this);
630 mDiscoveredVersion
= null
;
631 mAuthThread
= mConnChkRunnable
.execute(client
, this, mHandler
);
633 findViewById(R
.id
.refreshButton
).setVisibility(
635 setResultIconAndText(0, 0);
638 // avoids that the 'connect' button can be clicked if the test was previously passed
639 findViewById(R
.id
.buttonOK
).setEnabled(false
);
641 } else if (view
.getId() == R
.id
.account_password
) {
642 ImageView iv
= (ImageView
) findViewById(R
.id
.viewPassword
);
644 iv
.setVisibility(View
.VISIBLE
);
646 TextView v
= (TextView
) findViewById(R
.id
.account_password
);
647 int input_type
= InputType
.TYPE_CLASS_TEXT
648 | InputType
.TYPE_TEXT_VARIATION_PASSWORD
;
649 v
.setInputType(input_type
);
650 iv
.setVisibility(View
.INVISIBLE
);
655 private void setResultIconAndText(int drawable_id
, int text_id
) {
656 ImageView iv
= (ImageView
) findViewById(R
.id
.action_indicator
);
657 TextView tv
= (TextView
) findViewById(R
.id
.status_text
);
659 if (drawable_id
== 0 && text_id
== 0) {
660 iv
.setVisibility(View
.INVISIBLE
);
661 tv
.setVisibility(View
.INVISIBLE
);
663 iv
.setImageResource(drawable_id
);
665 iv
.setVisibility(View
.VISIBLE
);
666 tv
.setVisibility(View
.VISIBLE
);
671 public void onClick(View v
) {
672 if (v
.getId() == R
.id
.refreshButton
) {
673 onFocusChange(findViewById(R
.id
.host_URL
), false
);
674 } else if (v
.getId() == R
.id
.viewPassword
) {
675 TextView view
= (TextView
) findViewById(R
.id
.account_password
);
676 int input_type
= view
.getInputType();
677 if ((input_type
& InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) == InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) {
678 input_type
= InputType
.TYPE_CLASS_TEXT
679 | InputType
.TYPE_TEXT_VARIATION_PASSWORD
;
681 input_type
= InputType
.TYPE_CLASS_TEXT
682 | InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
;
684 view
.setInputType(input_type
);
688 @Override protected void onDestroy() {
689 // We must stop the service thats it's pooling to oAuth2 server for a token.
690 Intent tokenService
= new Intent(this, OAuth2GetTokenService
.class);
691 stopService(tokenService
);
693 // We stop listening the result of the pooling service.
694 if (tokenReceiver
!= null
) {
695 unregisterReceiver(tokenReceiver
);
696 tokenReceiver
= null
;
703 // Controlling the oAuth2 checkbox on the activity: hide and show widgets.
704 public void onOff_check_Click(View view
) {
705 CheckBox oAuth2Check
= (CheckBox
)view
;
706 changeViewByOAuth2Check(oAuth2Check
.isChecked());
710 public void changeViewByOAuth2Check(Boolean checked
) {
712 EditText oAuth2Url
= (EditText
) findViewById(R
.id
.oAuth_URL
);
713 EditText accountUsername
= (EditText
) findViewById(R
.id
.account_username
);
714 EditText accountPassword
= (EditText
) findViewById(R
.id
.account_password
);
715 ImageView viewPassword
= (ImageView
) findViewById(R
.id
.viewPassword
);
716 ImageView auth2ActionIndicator
= (ImageView
) findViewById(R
.id
.auth2_action_indicator
);
717 TextView oauth2StatusText
= (TextView
) findViewById(R
.id
.oauth2_status_text
);
720 oAuth2Url
.setVisibility(View
.VISIBLE
);
721 accountUsername
.setVisibility(View
.GONE
);
722 accountPassword
.setVisibility(View
.GONE
);
723 viewPassword
.setVisibility(View
.GONE
);
724 auth2ActionIndicator
.setVisibility(View
.INVISIBLE
);
725 oauth2StatusText
.setVisibility(View
.INVISIBLE
);
727 oAuth2Url
.setVisibility(View
.GONE
);
728 accountUsername
.setVisibility(View
.VISIBLE
);
729 accountPassword
.setVisibility(View
.VISIBLE
);
730 viewPassword
.setVisibility(View
.INVISIBLE
);
731 auth2ActionIndicator
.setVisibility(View
.GONE
);
732 oauth2StatusText
.setVisibility(View
.GONE
);
737 // Controlling the oAuth2 result of server connection.
738 private void setOAuth2ResultIconAndText(int drawable_id
, int text_id
) {
739 ImageView iv
= (ImageView
) findViewById(R
.id
.auth2_action_indicator
);
740 TextView tv
= (TextView
) findViewById(R
.id
.oauth2_status_text
);
742 if (drawable_id
== 0 && text_id
== 0) {
743 iv
.setVisibility(View
.INVISIBLE
);
744 tv
.setVisibility(View
.INVISIBLE
);
746 iv
.setImageResource(drawable_id
);
748 iv
.setVisibility(View
.VISIBLE
);
749 tv
.setVisibility(View
.VISIBLE
);
753 // Results from the first call to oAuth2 server : getting the user_code and verification_url.
755 public void onOAuth2GetCodeResult(ResultOAuthType type
, JSONObject responseJson
) {
756 if ((type
== ResultOAuthType
.OK_SSL
)||(type
== ResultOAuthType
.OK_NO_SSL
)) {
757 codeResponseJson
= responseJson
;
758 if (codeResponseJson
!= null
) {
759 getOAuth2AccessTokenFromJsonResponse();
760 } // else - nothing to do here - wait for callback !!!
762 } else if (type
== ResultOAuthType
.HOST_NOT_AVAILABLE
) {
763 setOAuth2ResultIconAndText(R
.drawable
.common_error
, R
.string
.oauth_connection_url_unavailable
);
767 // If the results of getting the user_code and verification_url are OK, we get the received data and we start
768 // the polling service to oAuth2 server to get a valid token.
769 private void getOAuth2AccessTokenFromJsonResponse() {
770 String deviceCode
= null
;
771 String verificationUrl
= null
;
772 String userCode
= null
;
776 Log
.d(TAG
, "ResponseOAuth2->" + codeResponseJson
.toString());
779 // We get data that we must show to the user or we will use internally.
780 verificationUrl
= codeResponseJson
.getString(OAuth2GetCodeRunnable
.CODE_VERIFICATION_URL
);
781 userCode
= codeResponseJson
.getString(OAuth2GetCodeRunnable
.CODE_USER_CODE
);
782 expiresIn
= codeResponseJson
.getInt(OAuth2GetCodeRunnable
.CODE_EXPIRES_IN
);
784 // And we get data that we must use to get a token.
785 deviceCode
= codeResponseJson
.getString(OAuth2GetCodeRunnable
.CODE_DEVICE_CODE
);
786 interval
= codeResponseJson
.getInt(OAuth2GetCodeRunnable
.CODE_INTERVAL
);
788 } catch (JSONException e
) {
789 Log
.e(TAG
, "Exception accesing data in Json object" + e
.toString());
792 // Updating status widget to OK.
793 setOAuth2ResultIconAndText(R
.drawable
.ic_ok
, R
.string
.auth_connection_established
);
795 // Showing the dialog with instructions for the user.
796 showDialog(OAUTH2_LOGIN_PROGRESS
);
798 // Loggin all the data.
799 Log
.d(TAG
, "verificationUrl->" + verificationUrl
);
800 Log
.d(TAG
, "userCode->" + userCode
);
801 Log
.d(TAG
, "deviceCode->" + deviceCode
);
802 Log
.d(TAG
, "expiresIn->" + expiresIn
);
803 Log
.d(TAG
, "interval->" + interval
);
805 // Starting the pooling service.
807 Intent tokenService
= new Intent(this, OAuth2GetTokenService
.class);
808 tokenService
.putExtra(OAuth2GetTokenService
.TOKEN_URI
, OAuth2Context
.OAUTH2_G_DEVICE_GETTOKEN_URL
);
809 tokenService
.putExtra(OAuth2GetTokenService
.TOKEN_DEVICE_CODE
, deviceCode
);
810 tokenService
.putExtra(OAuth2GetTokenService
.TOKEN_INTERVAL
, interval
);
812 startService(tokenService
);
814 catch (Exception e
) {
815 Log
.e(TAG
, "tokenService creation problem :", e
);
820 private void getOAuth2AccessTokenFromCapturedRedirection() {
821 Map
<String
, String
> responseValues
= new HashMap
<String
, String
>();
822 //String queryParameters = getIntent().getData().getQuery();
823 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
824 mNewCapturedUriFromOAuth2Redirection
= null
;
826 Log
.v(TAG
, "Queryparameters (Code) = " + queryParameters
);
828 String
[] pairs
= queryParameters
.split("&");
829 Log
.v(TAG
, "Pairs (Code) = " + pairs
.toString());
835 StringBuilder sb
= new StringBuilder();
837 while (pairs
.length
> i
) {
839 String
[] part
= pairs
[i
].split("=");
841 while (part
.length
> j
) {
845 sb
.append(key
+ " = ");
848 responseValues
.put(key
, value
);
849 sb
.append(value
+ "\n");
852 Log
.v(TAG
, "[" + i
+ "," + j
+ "] = " + p
);
859 // Updating status widget to OK.
860 setOAuth2ResultIconAndText(R
.drawable
.ic_ok
, R
.string
.auth_connection_established
);
862 // Showing the dialog with instructions for the user.
863 showDialog(OAUTH2_LOGIN_PROGRESS
);
866 RemoteOperation operation
= new GetOAuth2AccessToken(responseValues
);
867 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(OAuth2Context
.OAUTH2_F_TOKEN_ENDPOINT_URL
), getApplicationContext());
868 operation
.execute(client
, this, mHandler
);
873 // We get data from the oAuth2 token service with this broadcast receiver.
874 private class TokenReceiver
extends BroadcastReceiver
{
876 * The token is received.
878 * {@link BroadcastReceiver} to enable oAuth2 token receiving.
881 public void onReceive(Context context
, Intent intent
) {
882 @SuppressWarnings("unchecked")
883 HashMap
<String
, String
> tokenResponse
= (HashMap
<String
, String
>)intent
.getExtras().get(OAuth2GetTokenService
.TOKEN_RECEIVED_DATA
);
884 Log
.d(TAG
, "TokenReceiver->" + tokenResponse
.get(OAuth2GetTokenService
.TOKEN_ACCESS_TOKEN
));
885 dismissDialog(OAUTH2_LOGIN_PROGRESS
);
891 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
892 if (operation
instanceof ConnectionCheckOperation
) {
894 mStatusText
= mStatusIcon
= 0;
895 mStatusCorrect
= false
;
896 String t_url
= ((TextView
) findViewById(R
.id
.host_URL
)).getText()
897 .toString().trim().toLowerCase();
899 switch (result
.getCode()) {
902 mStatusIcon
= android
.R
.drawable
.ic_secure
;
903 mStatusText
= R
.string
.auth_secure_connection
;
904 mStatusCorrect
= true
;
910 mStatusCorrect
= true
;
911 if (t_url
.startsWith("http://") ) {
912 mStatusText
= R
.string
.auth_connection_established
;
913 mStatusIcon
= R
.drawable
.ic_ok
;
915 mStatusText
= R
.string
.auth_nossl_plain_ok_title
;
916 mStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
922 mStatusIcon
= R
.drawable
.common_error
;
923 mStatusText
= R
.string
.auth_bad_oc_version_title
;
925 case WRONG_CONNECTION
:
926 mStatusIcon
= R
.drawable
.common_error
;
927 mStatusText
= R
.string
.auth_wrong_connection_title
;
930 mStatusIcon
= R
.drawable
.common_error
;
931 mStatusText
= R
.string
.auth_timeout_title
;
933 case INCORRECT_ADDRESS
:
934 mStatusIcon
= R
.drawable
.common_error
;
935 mStatusText
= R
.string
.auth_incorrect_address_title
;
938 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
939 mStatusIcon
= R
.drawable
.common_error
;
940 mStatusText
= R
.string
.auth_ssl_unverified_server_title
;
941 mLastSslUntrustedServerResult
= result
;
942 showDialog(DIALOG_SSL_VALIDATOR
);
946 mStatusIcon
= R
.drawable
.common_error
;
947 mStatusText
= R
.string
.auth_ssl_general_error_title
;
950 case HOST_NOT_AVAILABLE
:
951 mStatusIcon
= R
.drawable
.common_error
;
952 mStatusText
= R
.string
.auth_unknown_host_title
;
954 case NO_NETWORK_CONNECTION
:
955 mStatusIcon
= R
.drawable
.no_network
;
956 mStatusText
= R
.string
.auth_no_net_conn_title
;
958 case INSTANCE_NOT_CONFIGURED
:
959 mStatusIcon
= R
.drawable
.common_error
;
960 mStatusText
= R
.string
.auth_not_configured_title
;
963 mStatusIcon
= R
.drawable
.common_error
;
964 mStatusText
= R
.string
.auth_incorrect_path_title
;
966 case UNHANDLED_HTTP_CODE
:
968 mStatusIcon
= R
.drawable
.common_error
;
969 mStatusText
= R
.string
.auth_unknown_error_title
;
972 Log
.e(TAG
, "Incorrect connection checker result type: " + result
.getHttpCode());
974 setResultIconAndText(mStatusIcon
, mStatusText
);
976 findViewById(R
.id
.refreshButton
).setVisibility(View
.VISIBLE
);
978 findViewById(R
.id
.refreshButton
).setVisibility(View
.INVISIBLE
);
979 findViewById(R
.id
.buttonOK
).setEnabled(mStatusCorrect
);
981 } else if (operation
instanceof GetOAuth2AccessToken
) {
984 dismissDialog(OAUTH2_LOGIN_PROGRESS
);
985 } catch (IllegalArgumentException e
) {
986 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
989 if (result
.isSuccess()) {
991 /// time to test the retrieved access token on the ownCloud server
992 String url
= ((TextView
) findViewById(R
.id
.host_URL
)).getText()
994 if (url
.endsWith("/"))
995 url
= url
.substring(0, url
.length() - 1);
998 /*String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion);
1000 if (webdav_path == null) {
1001 onAuthenticationResult(false, getString(R.string.auth_bad_oc_version_title));
1007 prefix
= "https://";
1011 if (url
.toLowerCase().startsWith("http://")
1012 || url
.toLowerCase().startsWith("https://")) {
1017 mBaseUrl
= prefix
+ url
;
1018 //String url_str = prefix + url + webdav_path;
1019 String url_str
= prefix
+ url
+ "/remote.php/odav";
1020 uri
= Uri
.parse(url_str
);
1022 } catch (Exception e
) {
1023 // should never happen
1024 onAuthenticationResult(false
, getString(R
.string
.auth_incorrect_address_title
));
1028 showDialog(DIALOG_LOGIN_PROGRESS
);
1029 String accessToken
= ((GetOAuth2AccessToken
)operation
).getResultTokenMap().get(OAuth2Context
.KEY_ACCESS_TOKEN
);
1030 Log
.d(TAG
, "Got ACCESS TOKEN: " + accessToken
);
1031 mAuthChkOperation
= new ExistenceCheckOperation("", this, accessToken
);
1032 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(uri
, getApplicationContext());
1033 mAuthChkOperation
.execute(client
, this, mHandler
);
1037 TextView tv
= (TextView
) findViewById(R
.id
.oAuth_URL
);
1038 tv
.setError("A valid authorization could not be obtained");
1042 } else if (operation
instanceof ExistenceCheckOperation
) {
1045 dismissDialog(DIALOG_LOGIN_PROGRESS
);
1046 } catch (IllegalArgumentException e
) {
1047 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
1050 if (result
.isSuccess()) {
1051 TextView tv
= (TextView
) findViewById(R
.id
.oAuth_URL
);
1052 Log
.d(TAG
, "Checked access - time to save the account");
1054 Uri uri
= Uri
.parse(mBaseUrl
);
1055 String username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1056 String accountName
= username
+ "@" + uri
.getHost();
1057 if (uri
.getPort() >= 0) {
1058 accountName
+= ":" + uri
.getPort();
1060 // TODO - check that accountName does not exist
1061 Account account
= new Account(accountName
, AccountAuthenticator
.ACCOUNT_TYPE
);
1062 AccountManager accManager
= AccountManager
.get(this);
1063 accManager
.addAccountExplicitly(account
, "", null
); // with our implementation, the password is never input in the app
1065 // Add this account as default in the preferences, if there is none
1066 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1067 if (defaultAccount
== null
) {
1068 SharedPreferences
.Editor editor
= PreferenceManager
.getDefaultSharedPreferences(this).edit();
1069 editor
.putString("select_oc_account", accountName
);
1073 /// account data to save by the AccountManager
1074 final Intent intent
= new Intent();
1075 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, AccountAuthenticator
.ACCOUNT_TYPE
);
1076 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, account
.name
);
1077 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1079 accManager
.setAuthToken(account
, AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
, ((ExistenceCheckOperation
) operation
).getAccessToken());
1081 accManager
.setUserData(account
, AccountAuthenticator
.KEY_OC_VERSION
, mConnChkRunnable
.getDiscoveredVersion().toString());
1082 accManager
.setUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
, mBaseUrl
);
1083 accManager
.setUserData(account
, AccountAuthenticator
.KEY_SUPPORTS_OAUTH2
, "TRUE");
1085 setAccountAuthenticatorResult(intent
.getExtras());
1086 setResult(RESULT_OK
, intent
);
1088 /// enforce the first account synchronization
1089 Bundle bundle
= new Bundle();
1090 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
1091 ContentResolver
.requestSync(account
, "org.owncloud", bundle
);
1096 TextView tv
= (TextView
) findViewById(R
.id
.oAuth_URL
);
1097 tv
.setError(result
.getLogMessage());
1098 Log
.d(TAG
, "Access failed: " + result
.getLogMessage());
1104 public void onSavedCertificate() {
1105 mAuthThread
= mConnChkRunnable
.retry(this, mHandler
);
1109 public void onFailedSavingCertificate() {
1110 showDialog(DIALOG_CERT_NOT_SAVED
);