1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
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
.authentication
;
21 import com
.owncloud
.android
.AccountUtils
;
22 import com
.owncloud
.android
.Log_OC
;
23 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
;
24 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
.OnSslValidatorListener
;
25 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
26 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
27 import com
.owncloud
.android
.operations
.OwnCloudServerCheckOperation
;
28 import com
.owncloud
.android
.operations
.ExistenceCheckOperation
;
29 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
30 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
31 import com
.owncloud
.android
.operations
.RemoteOperation
;
32 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
33 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
35 import android
.accounts
.Account
;
36 import android
.accounts
.AccountAuthenticatorActivity
;
37 import android
.accounts
.AccountManager
;
38 import android
.app
.AlertDialog
;
39 import android
.app
.Dialog
;
40 import android
.app
.ProgressDialog
;
41 import android
.content
.ContentResolver
;
42 import android
.content
.DialogInterface
;
43 import android
.content
.Intent
;
44 import android
.content
.SharedPreferences
;
45 import android
.net
.Uri
;
46 import android
.os
.Bundle
;
47 import android
.os
.Handler
;
48 import android
.preference
.PreferenceManager
;
49 import android
.text
.InputType
;
50 import android
.view
.View
;
51 import android
.view
.View
.OnFocusChangeListener
;
52 import android
.view
.Window
;
53 import android
.widget
.CheckBox
;
54 import android
.widget
.EditText
;
55 import android
.widget
.Button
;
56 import android
.widget
.ImageView
;
57 import android
.widget
.TextView
;
58 import android
.widget
.Toast
;
60 import com
.owncloud
.android
.R
;
62 import eu
.alefzero
.webdav
.WebdavClient
;
65 * This Activity is used to add an ownCloud account to the App
67 * @author Bartek Przybylski
68 * @author David A. Velasco
70 public class AuthenticatorActivity
extends AccountAuthenticatorActivity
71 implements OnRemoteOperationListener
, OnSslValidatorListener
, OnFocusChangeListener
{
73 private static final String TAG
= AuthenticatorActivity
.class.getSimpleName();
75 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
76 public static final String EXTRA_USER_NAME
= "USER_NAME";
77 public static final String EXTRA_HOST_NAME
= "HOST_NAME";
78 public static final String EXTRA_ACTION
= "ACTION";
80 private static final String KEY_HOST_URL_TEXT
= "HOST_URL_TEXT";
81 private static final String KEY_OC_VERSION
= "OC_VERSION";
82 private static final String KEY_ACCOUNT
= "ACCOUNT";
83 private static final String KEY_STATUS_TEXT
= "STATUS_TEXT";
84 private static final String KEY_STATUS_ICON
= "STATUS_ICON";
85 private static final String KEY_STATUS_CORRECT
= "STATUS_CORRECT";
86 private static final String KEY_IS_SSL_CONN
= "IS_SSL_CONN";
87 private static final String KEY_OAUTH2_STATUS_TEXT
= "OAUTH2_STATUS_TEXT";
88 private static final String KEY_OAUTH2_STATUS_ICON
= "OAUTH2_STATUS_ICON";
90 private static final String OAUTH_MODE_ON
= "on";
91 private static final String OAUTH_MODE_OFF
= "off";
92 private static final String OAUTH_MODE_OPTIONAL
= "optional";
94 private static final int DIALOG_LOGIN_PROGRESS
= 0;
95 private static final int DIALOG_SSL_VALIDATOR
= 1;
96 private static final int DIALOG_CERT_NOT_SAVED
= 2;
97 private static final int DIALOG_OAUTH2_LOGIN_PROGRESS
= 3;
99 public static final byte ACTION_CREATE
= 0;
100 public static final byte ACTION_UPDATE_TOKEN
= 1;
103 private String mHostBaseUrl
;
104 private OwnCloudVersion mDiscoveredVersion
;
106 private int mStatusText
, mStatusIcon
;
107 private boolean mStatusCorrect
, mIsSslConn
;
108 private int mOAuth2StatusText
, mOAuth2StatusIcon
;
110 private final Handler mHandler
= new Handler();
111 private Thread mOperationThread
;
112 private OwnCloudServerCheckOperation mOcServerChkOperation
;
113 private ExistenceCheckOperation mAuthCheckOperation
;
114 private RemoteOperationResult mLastSslUntrustedServerResult
;
116 private Uri mNewCapturedUriFromOAuth2Redirection
;
118 private AccountManager mAccountMgr
;
119 private boolean mJustCreated
;
120 private byte mAction
;
121 private Account mAccount
;
123 private ImageView mRefreshButton
;
124 private ImageView mViewPasswordButton
;
125 private EditText mHostUrlInput
;
126 private EditText mUsernameInput
;
127 private EditText mPasswordInput
;
128 private CheckBox mOAuth2Check
;
129 private String mOAuthAccessToken
;
130 private View mOkButton
;
131 private TextView mAuthStatusLayout
;
133 private TextView mOAuthAuthEndpointText
;
134 private TextView mOAuthTokenEndpointText
;
140 * IMPORTANT ENTRY POINT 1: activity is shown to the user
143 protected void onCreate(Bundle savedInstanceState
) {
144 super.onCreate(savedInstanceState
);
145 getWindow().requestFeature(Window
.FEATURE_NO_TITLE
);
147 /// set view and get references to view elements
148 setContentView(R
.layout
.account_setup
);
149 mRefreshButton
= (ImageView
) findViewById(R
.id
.refreshButton
);
150 mViewPasswordButton
= (ImageView
) findViewById(R
.id
.viewPasswordButton
);
151 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
152 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
153 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
154 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
155 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
156 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
157 mOkButton
= findViewById(R
.id
.buttonOK
);
158 mAuthStatusLayout
= (TextView
) findViewById(R
.id
.auth_status_text
);
160 /// complete label for 'register account' button
161 Button b
= (Button
) findViewById(R
.id
.account_register
);
163 b
.setText(String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
166 /// bind view elements to listeners
167 mHostUrlInput
.setOnFocusChangeListener(this);
168 mPasswordInput
.setOnFocusChangeListener(this);
171 mAccountMgr
= AccountManager
.get(this);
172 mNewCapturedUriFromOAuth2Redirection
= null
;
173 mAction
= getIntent().getByteExtra(EXTRA_ACTION
, ACTION_CREATE
);
176 if (savedInstanceState
== null
) {
177 /// connection state and info
178 mStatusText
= mStatusIcon
= 0;
179 mStatusCorrect
= false
;
184 /// retrieve extras from intent
185 String tokenType
= getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
186 boolean oAuthRequired
= AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
.equals(tokenType
) || OAUTH_MODE_ON
.equals(getString(R
.string
.oauth2_mode
));
188 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
189 if (mAccount
!= null
) {
190 String ocVersion
= mAccountMgr
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
);
191 if (ocVersion
!= null
) {
192 mDiscoveredVersion
= new OwnCloudVersion(ocVersion
);
194 mHostBaseUrl
= mAccountMgr
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
);
195 mHostUrlInput
.setText(mHostBaseUrl
);
196 String userName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
197 mUsernameInput
.setText(userName
);
198 oAuthRequired
= (mAccountMgr
.getUserData(mAccount
, AccountAuthenticator
.KEY_SUPPORTS_OAUTH2
) != null
);
200 mOAuth2Check
.setChecked(oAuthRequired
);
201 changeViewByOAuth2Check(oAuthRequired
);
205 loadSavedInstanceState(savedInstanceState
);
208 if (!OAUTH_MODE_OPTIONAL
.equals(getString(R
.string
.oauth2_mode
))) {
209 mOAuth2Check
.setVisibility(View
.GONE
);
212 if (mAction
== ACTION_UPDATE_TOKEN
) {
213 /// lock things that should not change
214 mHostUrlInput
.setEnabled(false
);
215 mUsernameInput
.setEnabled(false
);
216 mOAuth2Check
.setVisibility(View
.GONE
);
220 mPasswordInput
.setText(""); // clean password to avoid social hacking (disadvantage: password in removed if the device is turned aside)
226 * Saves relevant state before {@link #onPause()}
228 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag, intended to defer the
229 * processing of the redirection caught in {@link #onNewIntent(Intent)} until {@link #onResume()}
231 * See {@link #loadSavedInstanceState(Bundle)}
234 protected void onSaveInstanceState(Bundle outState
) {
235 super.onSaveInstanceState(outState
);
237 /// connection state and info
238 outState
.putInt(KEY_STATUS_TEXT
, mStatusText
);
239 outState
.putInt(KEY_STATUS_ICON
, mStatusIcon
);
240 outState
.putBoolean(KEY_STATUS_CORRECT
, mStatusCorrect
);
241 outState
.putBoolean(KEY_IS_SSL_CONN
, mIsSslConn
);
244 if (mDiscoveredVersion
!= null
)
245 outState
.putString(KEY_OC_VERSION
, mDiscoveredVersion
.toString());
246 outState
.putString(KEY_HOST_URL_TEXT
, mHostBaseUrl
);
248 /// account data, if updating
249 if (mAccount
!= null
)
250 outState
.putParcelable(KEY_ACCOUNT
, mAccount
);
252 // Saving the state of oAuth2 components.
253 outState
.putInt(KEY_OAUTH2_STATUS_ICON
, mOAuth2StatusIcon
);
254 outState
.putInt(KEY_OAUTH2_STATUS_TEXT
, mOAuth2StatusText
);
262 * See {@link #onSaveInstanceState(Bundle)}.
264 * @param savedInstanceState Saved state, as received in {@link #onCreate(Bundle)}.
266 private void loadSavedInstanceState(Bundle savedInstanceState
) {
267 /// connection state and info
268 mStatusCorrect
= savedInstanceState
.getBoolean(KEY_STATUS_CORRECT
);
269 mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
270 mStatusText
= savedInstanceState
.getInt(KEY_STATUS_TEXT
);
271 mStatusIcon
= savedInstanceState
.getInt(KEY_STATUS_ICON
);
274 /// UI settings depending upon connection
275 mOkButton
.setEnabled(mStatusCorrect
);
277 mRefreshButton
.setVisibility(View
.VISIBLE
); // seems that setting visibility is necessary
279 mRefreshButton
.setVisibility(View
.INVISIBLE
);
282 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
283 if (ocVersion
!= null
)
284 mDiscoveredVersion
= new OwnCloudVersion(ocVersion
);
285 mHostBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
287 // account data, if updating
288 mAccount
= savedInstanceState
.getParcelable(KEY_ACCOUNT
);
290 // state of oAuth2 components
291 mOAuth2StatusIcon
= savedInstanceState
.getInt(KEY_OAUTH2_STATUS_ICON
);
292 mOAuth2StatusText
= savedInstanceState
.getInt(KEY_OAUTH2_STATUS_TEXT
);
293 // END of getting the state of oAuth2 components.
298 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION request
301 * To make this possible, this activity needs to be qualified with android:launchMode = "singleTask" in the
302 * AndroidManifest.xml file.
305 protected void onNewIntent (Intent intent
) {
306 Log_OC
.d(TAG
, "onNewIntent()");
307 Uri data
= intent
.getData();
308 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
309 mNewCapturedUriFromOAuth2Redirection
= data
;
315 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION, and
316 * deferred in {@link #onNewIntent(Intent)}, is processed here.
319 protected void onResume() {
321 // the state of mOAuth2Check is automatically recovered between configuration changes, but not before onCreate() finishes; so keep the next lines here
322 changeViewByOAuth2Check(mOAuth2Check
.isChecked());
323 if (mAction
== ACTION_UPDATE_TOKEN
&& mJustCreated
) {
324 if (mOAuth2Check
.isChecked())
325 Toast
.makeText(this, R
.string
.auth_expired_oauth_token_toast
, Toast
.LENGTH_LONG
).show();
327 Toast
.makeText(this, R
.string
.auth_expired_basic_auth_toast
, Toast
.LENGTH_LONG
).show();
330 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
331 getOAuth2AccessTokenFromCapturedRedirection();
334 mJustCreated
= false
;
339 * Parses the redirection with the response to the GET AUTHORIZATION request to the
340 * oAuth server and requests for the access token (GET ACCESS TOKEN)
342 private void getOAuth2AccessTokenFromCapturedRedirection() {
343 /// Parse data from OAuth redirection
344 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
345 mNewCapturedUriFromOAuth2Redirection
= null
;
347 /// Showing the dialog with instructions for the user.
348 showDialog(DIALOG_OAUTH2_LOGIN_PROGRESS
);
350 /// GET ACCESS TOKEN to the oAuth server
351 RemoteOperation operation
= new OAuth2GetAccessToken( getString(R
.string
.oauth2_client_id
),
352 getString(R
.string
.oauth2_redirect_uri
),
353 getString(R
.string
.oauth2_grant_type
),
355 //WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(getString(R.string.oauth2_url_endpoint_access)), getApplicationContext());
356 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(mOAuthTokenEndpointText
.getText().toString().trim()), getApplicationContext());
357 operation
.execute(client
, this, mHandler
);
363 * Handles the change of focus on the text inputs for the server URL and the password
365 public void onFocusChange(View view
, boolean hasFocus
) {
366 if (view
.getId() == R
.id
.hostUrlInput
) {
367 onUrlInputFocusChanged((TextView
) view
, hasFocus
);
369 } else if (view
.getId() == R
.id
.account_password
) {
370 onPasswordFocusChanged((TextView
) view
, hasFocus
);
376 * Handles changes in focus on the text input for the server URL.
378 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
379 * other field. The operation to check the existence of the server in the entered URL is
382 * When hasFocus: user 'comes back' to write again the server URL.
384 * @param hostInput TextView with the URL input field receiving the change of focus.
385 * @param hasFocus 'True' if focus is received, 'false' if is lost
387 private void onUrlInputFocusChanged(TextView hostInput
, boolean hasFocus
) {
392 // avoids that the 'connect' button can be clicked if the test was previously passed
393 mOkButton
.setEnabled(false
);
398 private void checkOcServer() {
399 String uri
= mHostUrlInput
.getText().toString().trim();
400 if (uri
.length() != 0) {
401 mStatusText
= R
.string
.auth_testing_connection
;
402 mStatusIcon
= R
.drawable
.progress_small
;
404 /** TODO cancel previous connection check if the user tries to ammend a wrong URL
405 if(mConnChkOperation != null) {
406 mConnChkOperation.cancel();
408 mOcServerChkOperation
= new OwnCloudServerCheckOperation(uri
, this);
409 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(uri
), this);
411 mDiscoveredVersion
= null
;
412 mOperationThread
= mOcServerChkOperation
.execute(client
, this, mHandler
);
414 mRefreshButton
.setVisibility(View
.INVISIBLE
);
423 * Handles changes in focus on the text input for the password (basic authorization).
425 * When (hasFocus), the button to toggle password visibility is shown.
427 * When (!hasFocus), the button is made invisible and the password is hidden.
429 * @param passwordInput TextView with the password input field receiving the change of focus.
430 * @param hasFocus 'True' if focus is received, 'false' if is lost
432 private void onPasswordFocusChanged(TextView passwordInput
, boolean hasFocus
) {
434 mViewPasswordButton
.setVisibility(View
.VISIBLE
);
436 int input_type
= InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
;
437 passwordInput
.setInputType(input_type
);
438 mViewPasswordButton
.setVisibility(View
.INVISIBLE
);
445 * Cancels the authenticator activity
447 * IMPORTANT ENTRY POINT 3: Never underestimate the importance of cancellation
449 * This method is bound in the layout/acceoun_setup.xml resource file.
451 * @param view Cancel button
453 public void onCancelClick(View view
) {
454 setResult(RESULT_CANCELED
); // TODO review how is this related to AccountAuthenticator (debugging)
461 * Checks the credentials of the user in the root of the ownCloud server
462 * before creating a new local account.
464 * For basic authorization, a check of existence of the root folder is
467 * For OAuth, starts the flow to get an access token; the credentials test
468 * is postponed until it is available.
470 * IMPORTANT ENTRY POINT 4
472 * @param view OK button
474 public void onOkClick(View view
) {
475 // this check should be unnecessary
476 if (mDiscoveredVersion
== null
|| !mDiscoveredVersion
.isVersionValid() || mHostBaseUrl
== null
|| mHostBaseUrl
.length() == 0) {
477 mStatusIcon
= R
.drawable
.common_error
;
478 mStatusText
= R
.string
.auth_wtf_reenter_URL
;
480 mOkButton
.setEnabled(false
);
481 Log_OC
.wtf(TAG
, "The user was allowed to click 'connect' to an unchecked server!!");
485 if (mOAuth2Check
.isChecked()) {
486 startOauthorization();
489 checkBasicAuthorization();
495 * Tests the credentials entered by the user performing a check of existence on
496 * the root folder of the ownCloud server.
498 private void checkBasicAuthorization() {
499 /// get the path to the root folder through WebDAV from the version server
500 String webdav_path
= AccountUtils
.getWebdavPath(mDiscoveredVersion
, false
);
502 /// get basic credentials entered by user
503 String username
= mUsernameInput
.getText().toString();
504 String password
= mPasswordInput
.getText().toString();
506 /// be gentle with the user
507 showDialog(DIALOG_LOGIN_PROGRESS
);
509 /// test credentials accessing the root folder
510 mAuthCheckOperation
= new ExistenceCheckOperation("", this, false
);
511 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(mHostBaseUrl
+ webdav_path
), this);
512 client
.setBasicCredentials(username
, password
);
513 mOperationThread
= mAuthCheckOperation
.execute(client
, this, mHandler
);
518 * Starts the OAuth 'grant type' flow to get an access token, with
519 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
521 private void startOauthorization() {
522 // be gentle with the user
523 mStatusIcon
= R
.drawable
.progress_small
;
524 mStatusText
= R
.string
.oauth_login_connection
;
527 // GET AUTHORIZATION request
528 //Uri uri = Uri.parse(getString(R.string.oauth2_url_endpoint_auth));
529 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
530 Uri
.Builder uriBuilder
= uri
.buildUpon();
531 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
));
532 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
));
533 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
));
534 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
));
535 //uriBuilder.appendQueryParameter(OAuth2Constants.KEY_STATE, whateverwewant);
536 uri
= uriBuilder
.build();
537 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
538 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
544 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
546 * Dispatches the operation flow to the right method.
549 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
551 if (operation
instanceof OwnCloudServerCheckOperation
) {
552 onOcServerCheckFinish((OwnCloudServerCheckOperation
) operation
, result
);
554 } else if (operation
instanceof OAuth2GetAccessToken
) {
555 onGetOAuthAccessTokenFinish((OAuth2GetAccessToken
)operation
, result
);
557 } else if (operation
instanceof ExistenceCheckOperation
) {
558 onAuthorizationCheckFinish((ExistenceCheckOperation
)operation
, result
);
565 * Processes the result of the server check performed when the user finishes the enter of the
568 * @param operation Server check performed.
569 * @param result Result of the check.
571 private void onOcServerCheckFinish(OwnCloudServerCheckOperation operation
, RemoteOperationResult result
) {
572 /// update status icon and text
573 updateStatusIconAndText(result
);
576 /// save result state
577 mStatusCorrect
= result
.isSuccess();
578 mIsSslConn
= (result
.getCode() == ResultCode
.OK_SSL
);
580 /// very special case (TODO: move to a common place for all the remote operations)
581 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
582 mLastSslUntrustedServerResult
= result
;
583 showDialog(DIALOG_SSL_VALIDATOR
);
586 /// update the visibility of the 'retry connection' button
588 mRefreshButton
.setVisibility(View
.VISIBLE
);
590 mRefreshButton
.setVisibility(View
.INVISIBLE
);
592 /// retrieve discovered version and normalize server URL
593 mDiscoveredVersion
= operation
.getDiscoveredVersion();
594 mHostBaseUrl
= mHostUrlInput
.getText().toString().trim();
595 if (!mHostBaseUrl
.toLowerCase().startsWith("http://") &&
596 !mHostBaseUrl
.toLowerCase().startsWith("https://")) {
599 mHostBaseUrl
= "https://" + mHostBaseUrl
;
601 mHostBaseUrl
= "http://" + mHostBaseUrl
;
605 if (mHostBaseUrl
.endsWith("/"))
606 mHostBaseUrl
= mHostBaseUrl
.substring(0, mHostBaseUrl
.length() - 1);
608 /// allow or not the user try to access the server
609 mOkButton
.setEnabled(mStatusCorrect
);
614 * Chooses the right icon and text to show to the user for the received operation result.
616 * @param result Result of a remote operation performed in this activity
618 private void updateStatusIconAndText(RemoteOperationResult result
) {
619 mStatusText
= mStatusIcon
= 0;
621 switch (result
.getCode()) {
623 mStatusIcon
= android
.R
.drawable
.ic_secure
;
624 mStatusText
= R
.string
.auth_secure_connection
;
629 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
630 mStatusText
= R
.string
.auth_connection_established
;
631 mStatusIcon
= R
.drawable
.ic_ok
;
633 mStatusText
= R
.string
.auth_nossl_plain_ok_title
;
634 mStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
638 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
639 mStatusIcon
= R
.drawable
.common_error
;
640 mStatusText
= R
.string
.auth_ssl_unverified_server_title
;
644 mStatusIcon
= R
.drawable
.common_error
;
645 mStatusText
= R
.string
.auth_bad_oc_version_title
;
647 case WRONG_CONNECTION
:
648 mStatusIcon
= R
.drawable
.common_error
;
649 mStatusText
= R
.string
.auth_wrong_connection_title
;
652 mStatusIcon
= R
.drawable
.common_error
;
653 mStatusText
= R
.string
.auth_timeout_title
;
655 case INCORRECT_ADDRESS
:
656 mStatusIcon
= R
.drawable
.common_error
;
657 mStatusText
= R
.string
.auth_incorrect_address_title
;
661 mStatusIcon
= R
.drawable
.common_error
;
662 mStatusText
= R
.string
.auth_ssl_general_error_title
;
666 mStatusIcon
= R
.drawable
.common_error
;
667 mStatusText
= R
.string
.auth_unauthorized
;
669 case HOST_NOT_AVAILABLE
:
670 mStatusIcon
= R
.drawable
.common_error
;
671 mStatusText
= R
.string
.auth_unknown_host_title
;
673 case NO_NETWORK_CONNECTION
:
674 mStatusIcon
= R
.drawable
.no_network
;
675 mStatusText
= R
.string
.auth_no_net_conn_title
;
677 case INSTANCE_NOT_CONFIGURED
:
678 mStatusIcon
= R
.drawable
.common_error
;
679 mStatusText
= R
.string
.auth_not_configured_title
;
682 mStatusIcon
= R
.drawable
.common_error
;
683 mStatusText
= R
.string
.auth_incorrect_path_title
;
686 mStatusIcon
= R
.drawable
.common_error
;
687 mStatusText
= R
.string
.auth_oauth_error
;
689 case OAUTH2_ERROR_ACCESS_DENIED
:
690 mStatusIcon
= R
.drawable
.common_error
;
691 mStatusText
= R
.string
.auth_oauth_error_access_denied
;
693 case UNHANDLED_HTTP_CODE
:
695 mStatusIcon
= R
.drawable
.common_error
;
696 mStatusText
= R
.string
.auth_unknown_error_title
;
706 * Processes the result of the request for and access token send
707 * to an OAuth authorization server.
709 * @param operation Operation performed requesting the access token.
710 * @param result Result of the operation.
712 private void onGetOAuthAccessTokenFinish(OAuth2GetAccessToken operation
, RemoteOperationResult result
) {
714 dismissDialog(DIALOG_OAUTH2_LOGIN_PROGRESS
);
715 } catch (IllegalArgumentException e
) {
716 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
719 String webdav_path
= AccountUtils
.getWebdavPath(mDiscoveredVersion
, true
);
720 if (result
.isSuccess() && webdav_path
!= null
) {
721 /// be gentle with the user
722 showDialog(DIALOG_LOGIN_PROGRESS
);
724 /// time to test the retrieved access token on the ownCloud server
725 mOAuthAccessToken
= ((OAuth2GetAccessToken
)operation
).getResultTokenMap().get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
726 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mOAuthAccessToken
);
727 mAuthCheckOperation
= new ExistenceCheckOperation("", this, false
);
728 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(mHostBaseUrl
+ webdav_path
), this);
729 client
.setBearerCredentials(mOAuthAccessToken
);
730 mAuthCheckOperation
.execute(client
, this, mHandler
);
733 updateStatusIconAndText(result
);
735 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
741 * Processes the result of the access check performed to try the user credentials.
743 * Creates a new account through the AccountManager.
745 * @param operation Access check performed.
746 * @param result Result of the operation.
748 private void onAuthorizationCheckFinish(ExistenceCheckOperation operation
, RemoteOperationResult result
) {
750 dismissDialog(DIALOG_LOGIN_PROGRESS
);
751 } catch (IllegalArgumentException e
) {
752 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
755 if (result
.isSuccess()) {
756 Log_OC
.d(TAG
, "Successful access - time to save the account");
758 if (mAction
== ACTION_CREATE
) {
768 updateStatusIconAndText(result
);
770 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
776 * Sets the proper response to get that the Account Authenticator that started this activity saves
777 * a new authorization token for mAccount.
779 private void updateToken() {
780 Bundle response
= new Bundle();
781 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
782 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
783 boolean isOAuth
= mOAuth2Check
.isChecked();
785 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mOAuthAccessToken
);
786 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
787 mAccountMgr
.setAuthToken(mAccount
, AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
, mOAuthAccessToken
);
789 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
790 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
792 setAccountAuthenticatorResult(response
);
797 * Creates a new account through the Account Authenticator that started this activity.
799 * This makes the account permanent.
801 * TODO Decide how to name the OAuth accounts
803 private void createAccount() {
804 /// create and save new ownCloud account
805 boolean isOAuth
= mOAuth2Check
.isChecked();
807 Uri uri
= Uri
.parse(mHostBaseUrl
);
808 String username
= mUsernameInput
.getText().toString().trim();
810 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
812 String accountName
= username
+ "@" + uri
.getHost();
813 if (uri
.getPort() >= 0) {
814 accountName
+= ":" + uri
.getPort();
816 mAccount
= new Account(accountName
, AccountAuthenticator
.ACCOUNT_TYPE
);
818 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
); // with our implementation, the password is never input in the app
820 mAccountMgr
.addAccountExplicitly(mAccount
, mPasswordInput
.getText().toString(), null
);
823 /// add the new account as default in preferences, if there is none already
824 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
825 if (defaultAccount
== null
) {
826 SharedPreferences
.Editor editor
= PreferenceManager
827 .getDefaultSharedPreferences(this).edit();
828 editor
.putString("select_oc_account", accountName
);
832 /// prepare result to return to the Authenticator
833 // TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done
834 final Intent intent
= new Intent();
835 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, AccountAuthenticator
.ACCOUNT_TYPE
);
836 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
838 intent
.putExtra(AccountManager
.KEY_AUTHTOKEN
, AccountAuthenticator
.ACCOUNT_TYPE
); // TODO check this; not sure it's right; maybe
839 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
841 mAccountMgr
.setAuthToken(mAccount
, AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
, mOAuthAccessToken
);
843 /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
844 mAccountMgr
.setUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
, mDiscoveredVersion
.toString());
845 mAccountMgr
.setUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
, mHostBaseUrl
);
847 mAccountMgr
.setUserData(mAccount
, AccountAuthenticator
.KEY_SUPPORTS_OAUTH2
, "TRUE"); // TODO this flag should be unnecessary
849 setAccountAuthenticatorResult(intent
.getExtras());
850 setResult(RESULT_OK
, intent
);
852 /// immediately request for the synchronization of the new account
853 Bundle bundle
= new Bundle();
854 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
855 ContentResolver
.requestSync(mAccount
, AccountAuthenticator
.AUTHORITY
, bundle
);
862 * Necessary to update the contents of the SSL Dialog
864 * TODO move to some common place for all possible untrusted SSL failures
867 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
869 case DIALOG_LOGIN_PROGRESS
:
870 case DIALOG_CERT_NOT_SAVED
:
871 case DIALOG_OAUTH2_LOGIN_PROGRESS
:
873 case DIALOG_SSL_VALIDATOR
: {
874 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
878 Log_OC
.e(TAG
, "Incorrect dialog called with id = " + id
);
887 protected Dialog
onCreateDialog(int id
) {
888 Dialog dialog
= null
;
890 case DIALOG_LOGIN_PROGRESS
: {
891 /// simple progress dialog
892 ProgressDialog working_dialog
= new ProgressDialog(this);
893 working_dialog
.setMessage(getResources().getString(R
.string
.auth_trying_to_login
));
894 working_dialog
.setIndeterminate(true
);
895 working_dialog
.setCancelable(true
);
897 .setOnCancelListener(new DialogInterface
.OnCancelListener() {
899 public void onCancel(DialogInterface dialog
) {
900 /// TODO study if this is enough
901 Log_OC
.i(TAG
, "Login canceled");
902 if (mOperationThread
!= null
) {
903 mOperationThread
.interrupt();
908 dialog
= working_dialog
;
911 case DIALOG_OAUTH2_LOGIN_PROGRESS
: {
912 ProgressDialog working_dialog
= new ProgressDialog(this);
913 working_dialog
.setMessage(String
.format("Getting authorization"));
914 working_dialog
.setIndeterminate(true
);
915 working_dialog
.setCancelable(true
);
917 .setOnCancelListener(new DialogInterface
.OnCancelListener() {
919 public void onCancel(DialogInterface dialog
) {
920 Log_OC
.i(TAG
, "Login canceled");
924 dialog
= working_dialog
;
927 case DIALOG_SSL_VALIDATOR
: {
928 /// TODO start to use new dialog interface, at least for this (it is a FragmentDialog already)
929 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
932 case DIALOG_CERT_NOT_SAVED
: {
933 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
934 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
935 builder
.setCancelable(false
);
936 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
938 public void onClick(DialogInterface dialog
, int which
) {
942 dialog
= builder
.create();
946 Log_OC
.e(TAG
, "Incorrect dialog called with id = " + id
);
953 * Starts and activity to open the 'new account' page in the ownCloud web site
955 * @param view 'Account register' button
957 public void onRegisterClick(View view
) {
958 Intent register
= new Intent(Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.url_account_register
)));
959 setResult(RESULT_CANCELED
);
960 startActivity(register
);
965 * Updates the content and visibility state of the icon and text associated
966 * to the last check on the ownCloud server.
968 private void updateConnStatus() {
969 TextView tv
= (TextView
) findViewById(R
.id
.server_status_text
);
971 if (mStatusIcon
== 0 && mStatusText
== 0) {
972 tv
.setVisibility(View
.INVISIBLE
);
974 tv
.setText(mStatusText
);
975 tv
.setCompoundDrawablesWithIntrinsicBounds(mStatusIcon
, 0, 0, 0);
976 tv
.setVisibility(View
.VISIBLE
);
982 * Updates the content and visibility state of the icon and text associated
983 * to the interactions with the OAuth authorization server.
985 private void updateAuthStatus() {
986 if (mStatusIcon
== 0 && mStatusText
== 0) {
987 mAuthStatusLayout
.setVisibility(View
.INVISIBLE
);
989 mAuthStatusLayout
.setText(mStatusText
);
990 mAuthStatusLayout
.setCompoundDrawablesWithIntrinsicBounds(mStatusIcon
, 0, 0, 0);
991 mAuthStatusLayout
.setVisibility(View
.VISIBLE
);
997 * Called when the refresh button in the input field for ownCloud host is clicked.
999 * Performs a new check on the URL in the input field.
1001 * @param view Refresh 'button'
1003 public void onRefreshClick(View view
) {
1004 onFocusChange(mRefreshButton
, false
);
1009 * Called when the eye icon in the password field is clicked.
1011 * Toggles the visibility of the password in the field.
1013 * @param view 'View password' 'button'
1015 public void onViewPasswordClick(View view
) {
1016 int selectionStart
= mPasswordInput
.getSelectionStart();
1017 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1018 int input_type
= mPasswordInput
.getInputType();
1019 if ((input_type
& InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) == InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) {
1020 input_type
= InputType
.TYPE_CLASS_TEXT
1021 | InputType
.TYPE_TEXT_VARIATION_PASSWORD
;
1023 input_type
= InputType
.TYPE_CLASS_TEXT
1024 | InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
;
1026 mPasswordInput
.setInputType(input_type
);
1027 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1032 * Called when the checkbox for OAuth authorization is clicked.
1034 * Hides or shows the input fields for user & password.
1036 * @param view 'View password' 'button'
1038 public void onCheckClick(View view
) {
1039 CheckBox oAuth2Check
= (CheckBox
)view
;
1040 changeViewByOAuth2Check(oAuth2Check
.isChecked());
1045 * Changes the visibility of input elements depending upon the kind of authorization
1046 * chosen by the user: basic or OAuth
1048 * @param checked 'True' when OAuth is selected.
1050 public void changeViewByOAuth2Check(Boolean checked
) {
1053 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
1054 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
1055 mUsernameInput
.setVisibility(View
.GONE
);
1056 mPasswordInput
.setVisibility(View
.GONE
);
1057 mViewPasswordButton
.setVisibility(View
.GONE
);
1059 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
1060 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
1061 mUsernameInput
.setVisibility(View
.VISIBLE
);
1062 mPasswordInput
.setVisibility(View
.VISIBLE
);
1063 mViewPasswordButton
.setVisibility(View
.INVISIBLE
);
1069 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1071 public void onSavedCertificate() {
1072 mOperationThread
= mOcServerChkOperation
.retry(this, mHandler
);
1076 * Called from SslValidatorDialog when a new server certificate could not be saved
1077 * when the user requested it.
1080 public void onFailedSavingCertificate() {
1081 showDialog(DIALOG_CERT_NOT_SAVED
);