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
.graphics
.Rect
;
46 import android
.graphics
.drawable
.Drawable
;
47 import android
.net
.Uri
;
48 import android
.os
.Bundle
;
49 import android
.os
.Handler
;
50 import android
.preference
.PreferenceManager
;
51 import android
.text
.InputType
;
52 import android
.view
.KeyEvent
;
53 import android
.view
.MotionEvent
;
54 import android
.view
.View
;
55 import android
.view
.View
.OnFocusChangeListener
;
56 import android
.view
.View
.OnTouchListener
;
57 import android
.view
.Window
;
58 import android
.view
.inputmethod
.EditorInfo
;
59 import android
.widget
.CheckBox
;
60 import android
.widget
.EditText
;
61 import android
.widget
.Button
;
62 import android
.widget
.ImageView
;
63 import android
.widget
.TextView
;
64 import android
.widget
.Toast
;
65 import android
.widget
.TextView
.OnEditorActionListener
;
67 import com
.owncloud
.android
.R
;
69 import eu
.alefzero
.webdav
.WebdavClient
;
72 * This Activity is used to add an ownCloud account to the App
74 * @author Bartek Przybylski
75 * @author David A. Velasco
77 public class AuthenticatorActivity
extends AccountAuthenticatorActivity
78 implements OnRemoteOperationListener
, OnSslValidatorListener
, OnFocusChangeListener
, OnEditorActionListener
{
80 private static final String TAG
= AuthenticatorActivity
.class.getSimpleName();
82 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
83 public static final String EXTRA_USER_NAME
= "USER_NAME";
84 public static final String EXTRA_HOST_NAME
= "HOST_NAME";
85 public static final String EXTRA_ACTION
= "ACTION";
87 private static final String KEY_HOST_URL_TEXT
= "HOST_URL_TEXT";
88 private static final String KEY_OC_VERSION
= "OC_VERSION";
89 private static final String KEY_ACCOUNT
= "ACCOUNT";
90 private static final String KEY_STATUS_TEXT
= "STATUS_TEXT";
91 private static final String KEY_STATUS_ICON
= "STATUS_ICON";
92 private static final String KEY_STATUS_CORRECT
= "STATUS_CORRECT";
93 private static final String KEY_IS_SSL_CONN
= "IS_SSL_CONN";
94 private static final String KEY_OAUTH2_STATUS_TEXT
= "OAUTH2_STATUS_TEXT";
95 private static final String KEY_OAUTH2_STATUS_ICON
= "OAUTH2_STATUS_ICON";
97 private static final String OAUTH_MODE_ON
= "on";
98 private static final String OAUTH_MODE_OFF
= "off";
99 private static final String OAUTH_MODE_OPTIONAL
= "optional";
101 private static final int DIALOG_LOGIN_PROGRESS
= 0;
102 private static final int DIALOG_SSL_VALIDATOR
= 1;
103 private static final int DIALOG_CERT_NOT_SAVED
= 2;
104 private static final int DIALOG_OAUTH2_LOGIN_PROGRESS
= 3;
106 public static final byte ACTION_CREATE
= 0;
107 public static final byte ACTION_UPDATE_TOKEN
= 1;
110 private String mHostBaseUrl
;
111 private OwnCloudVersion mDiscoveredVersion
;
113 private int mStatusText
, mStatusIcon
;
114 private boolean mStatusCorrect
, mIsSslConn
;
115 private int mOAuth2StatusText
, mOAuth2StatusIcon
;
117 private final Handler mHandler
= new Handler();
118 private Thread mOperationThread
;
119 private OwnCloudServerCheckOperation mOcServerChkOperation
;
120 private ExistenceCheckOperation mAuthCheckOperation
;
121 private RemoteOperationResult mLastSslUntrustedServerResult
;
123 private Uri mNewCapturedUriFromOAuth2Redirection
;
125 private AccountManager mAccountMgr
;
126 private boolean mJustCreated
;
127 private byte mAction
;
128 private Account mAccount
;
130 private ImageView mViewPasswordButton
;
131 private EditText mHostUrlInput
;
132 private EditText mUsernameInput
;
133 private EditText mPasswordInput
;
134 private CheckBox mOAuth2Check
;
135 private String mOAuthAccessToken
;
136 private View mOkButton
;
137 private TextView mAuthStatusLayout
;
139 private TextView mOAuthAuthEndpointText
;
140 private TextView mOAuthTokenEndpointText
;
146 * IMPORTANT ENTRY POINT 1: activity is shown to the user
149 protected void onCreate(Bundle savedInstanceState
) {
150 super.onCreate(savedInstanceState
);
151 getWindow().requestFeature(Window
.FEATURE_NO_TITLE
);
153 /// set view and get references to view elements
154 setContentView(R
.layout
.account_setup
);
155 mViewPasswordButton
= (ImageView
) findViewById(R
.id
.viewPasswordButton
);
156 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
157 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
158 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
159 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
160 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
161 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
162 mOkButton
= findViewById(R
.id
.buttonOK
);
163 mAuthStatusLayout
= (TextView
) findViewById(R
.id
.auth_status_text
);
165 /// complete label for 'register account' button
166 Button b
= (Button
) findViewById(R
.id
.account_register
);
168 b
.setText(String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
171 /// bind view elements to listeners
172 mHostUrlInput
.setOnFocusChangeListener(this);
173 mHostUrlInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
175 public boolean onDrawableTouch(final MotionEvent event
) {
176 AuthenticatorActivity
.this.onRefreshClick(mHostUrlInput
);
180 mPasswordInput
.setOnFocusChangeListener(this);
181 mPasswordInput
.setImeOptions(EditorInfo
.IME_ACTION_DONE
);
182 mPasswordInput
.setOnEditorActionListener(this);
185 mAccountMgr
= AccountManager
.get(this);
186 mNewCapturedUriFromOAuth2Redirection
= null
;
187 mAction
= getIntent().getByteExtra(EXTRA_ACTION
, ACTION_CREATE
);
190 if (savedInstanceState
== null
) {
191 /// connection state and info
192 mStatusText
= mStatusIcon
= 0;
193 mStatusCorrect
= false
;
198 /// retrieve extras from intent
199 String tokenType
= getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
200 boolean oAuthRequired
= AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
.equals(tokenType
) || OAUTH_MODE_ON
.equals(getString(R
.string
.oauth2_mode
));
202 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
203 if (mAccount
!= null
) {
204 String ocVersion
= mAccountMgr
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
);
205 if (ocVersion
!= null
) {
206 mDiscoveredVersion
= new OwnCloudVersion(ocVersion
);
208 mHostBaseUrl
= mAccountMgr
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
);
209 mHostUrlInput
.setText(mHostBaseUrl
);
210 String userName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
211 mUsernameInput
.setText(userName
);
212 oAuthRequired
= (mAccountMgr
.getUserData(mAccount
, AccountAuthenticator
.KEY_SUPPORTS_OAUTH2
) != null
);
214 mOAuth2Check
.setChecked(oAuthRequired
);
215 changeViewByOAuth2Check(oAuthRequired
);
219 loadSavedInstanceState(savedInstanceState
);
222 if (!OAUTH_MODE_OPTIONAL
.equals(getString(R
.string
.oauth2_mode
))) {
223 mOAuth2Check
.setVisibility(View
.GONE
);
226 if (mAction
== ACTION_UPDATE_TOKEN
) {
227 /// lock things that should not change
228 mHostUrlInput
.setEnabled(false
);
229 mUsernameInput
.setEnabled(false
);
230 mOAuth2Check
.setVisibility(View
.GONE
);
234 mPasswordInput
.setText(""); // clean password to avoid social hacking (disadvantage: password in removed if the device is turned aside)
240 * Saves relevant state before {@link #onPause()}
242 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag, intended to defer the
243 * processing of the redirection caught in {@link #onNewIntent(Intent)} until {@link #onResume()}
245 * See {@link #loadSavedInstanceState(Bundle)}
248 protected void onSaveInstanceState(Bundle outState
) {
249 super.onSaveInstanceState(outState
);
251 /// connection state and info
252 outState
.putInt(KEY_STATUS_TEXT
, mStatusText
);
253 outState
.putInt(KEY_STATUS_ICON
, mStatusIcon
);
254 outState
.putBoolean(KEY_STATUS_CORRECT
, mStatusCorrect
);
255 outState
.putBoolean(KEY_IS_SSL_CONN
, mIsSslConn
);
258 if (mDiscoveredVersion
!= null
)
259 outState
.putString(KEY_OC_VERSION
, mDiscoveredVersion
.toString());
260 outState
.putString(KEY_HOST_URL_TEXT
, mHostBaseUrl
);
262 /// account data, if updating
263 if (mAccount
!= null
)
264 outState
.putParcelable(KEY_ACCOUNT
, mAccount
);
266 // Saving the state of oAuth2 components.
267 outState
.putInt(KEY_OAUTH2_STATUS_ICON
, mOAuth2StatusIcon
);
268 outState
.putInt(KEY_OAUTH2_STATUS_TEXT
, mOAuth2StatusText
);
276 * See {@link #onSaveInstanceState(Bundle)}.
278 * @param savedInstanceState Saved state, as received in {@link #onCreate(Bundle)}.
280 private void loadSavedInstanceState(Bundle savedInstanceState
) {
281 /// connection state and info
282 mStatusCorrect
= savedInstanceState
.getBoolean(KEY_STATUS_CORRECT
);
283 mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
284 mStatusText
= savedInstanceState
.getInt(KEY_STATUS_TEXT
);
285 mStatusIcon
= savedInstanceState
.getInt(KEY_STATUS_ICON
);
288 /// UI settings depending upon connection
289 mOkButton
.setEnabled(mStatusCorrect
);
290 if (!mStatusCorrect
) {
291 mHostUrlInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, R
.drawable
.ic_action_refresh_black
, 0);
293 mHostUrlInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
297 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
298 if (ocVersion
!= null
)
299 mDiscoveredVersion
= new OwnCloudVersion(ocVersion
);
300 mHostBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
302 // account data, if updating
303 mAccount
= savedInstanceState
.getParcelable(KEY_ACCOUNT
);
305 // state of oAuth2 components
306 mOAuth2StatusIcon
= savedInstanceState
.getInt(KEY_OAUTH2_STATUS_ICON
);
307 mOAuth2StatusText
= savedInstanceState
.getInt(KEY_OAUTH2_STATUS_TEXT
);
308 // END of getting the state of oAuth2 components.
313 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION request
316 * To make this possible, this activity needs to be qualified with android:launchMode = "singleTask" in the
317 * AndroidManifest.xml file.
320 protected void onNewIntent (Intent intent
) {
321 Log_OC
.d(TAG
, "onNewIntent()");
322 Uri data
= intent
.getData();
323 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
324 mNewCapturedUriFromOAuth2Redirection
= data
;
330 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION, and
331 * deferred in {@link #onNewIntent(Intent)}, is processed here.
334 protected void onResume() {
336 // the state of mOAuth2Check is automatically recovered between configuration changes, but not before onCreate() finishes; so keep the next lines here
337 changeViewByOAuth2Check(mOAuth2Check
.isChecked());
338 if (mAction
== ACTION_UPDATE_TOKEN
&& mJustCreated
) {
339 if (mOAuth2Check
.isChecked())
340 Toast
.makeText(this, R
.string
.auth_expired_oauth_token_toast
, Toast
.LENGTH_LONG
).show();
342 Toast
.makeText(this, R
.string
.auth_expired_basic_auth_toast
, Toast
.LENGTH_LONG
).show();
345 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
346 getOAuth2AccessTokenFromCapturedRedirection();
349 mJustCreated
= false
;
354 * Parses the redirection with the response to the GET AUTHORIZATION request to the
355 * oAuth server and requests for the access token (GET ACCESS TOKEN)
357 private void getOAuth2AccessTokenFromCapturedRedirection() {
358 /// Parse data from OAuth redirection
359 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
360 mNewCapturedUriFromOAuth2Redirection
= null
;
362 /// Showing the dialog with instructions for the user.
363 showDialog(DIALOG_OAUTH2_LOGIN_PROGRESS
);
365 /// GET ACCESS TOKEN to the oAuth server
366 RemoteOperation operation
= new OAuth2GetAccessToken( getString(R
.string
.oauth2_client_id
),
367 getString(R
.string
.oauth2_redirect_uri
),
368 getString(R
.string
.oauth2_grant_type
),
370 //WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(getString(R.string.oauth2_url_endpoint_access)), getApplicationContext());
371 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(mOAuthTokenEndpointText
.getText().toString().trim()), getApplicationContext());
372 operation
.execute(client
, this, mHandler
);
378 * Handles the change of focus on the text inputs for the server URL and the password
380 public void onFocusChange(View view
, boolean hasFocus
) {
381 if (view
.getId() == R
.id
.hostUrlInput
) {
382 onUrlInputFocusChanged((TextView
) view
, hasFocus
);
384 } else if (view
.getId() == R
.id
.account_password
) {
385 onPasswordFocusChanged((TextView
) view
, hasFocus
);
391 * Handles changes in focus on the text input for the server URL.
393 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
394 * other field. The operation to check the existence of the server in the entered URL is
397 * When hasFocus: user 'comes back' to write again the server URL.
399 * @param hostInput TextView with the URL input field receiving the change of focus.
400 * @param hasFocus 'True' if focus is received, 'false' if is lost
402 private void onUrlInputFocusChanged(TextView hostInput
, boolean hasFocus
) {
407 // avoids that the 'connect' button can be clicked if the test was previously passed
408 mOkButton
.setEnabled(false
);
413 private void checkOcServer() {
414 String uri
= mHostUrlInput
.getText().toString().trim();
415 if (uri
.length() != 0) {
416 mStatusText
= R
.string
.auth_testing_connection
;
417 mStatusIcon
= R
.drawable
.progress_small
;
419 /** TODO cancel previous connection check if the user tries to ammend a wrong URL
420 if(mConnChkOperation != null) {
421 mConnChkOperation.cancel();
423 mOcServerChkOperation
= new OwnCloudServerCheckOperation(uri
, this);
424 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(uri
), this);
426 mDiscoveredVersion
= null
;
427 mOperationThread
= mOcServerChkOperation
.execute(client
, this, mHandler
);
429 mHostUrlInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
438 * Handles changes in focus on the text input for the password (basic authorization).
440 * When (hasFocus), the button to toggle password visibility is shown.
442 * When (!hasFocus), the button is made invisible and the password is hidden.
444 * @param passwordInput TextView with the password input field receiving the change of focus.
445 * @param hasFocus 'True' if focus is received, 'false' if is lost
447 private void onPasswordFocusChanged(TextView passwordInput
, boolean hasFocus
) {
449 mViewPasswordButton
.setVisibility(View
.VISIBLE
);
451 int input_type
= InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
;
452 passwordInput
.setInputType(input_type
);
453 mViewPasswordButton
.setVisibility(View
.INVISIBLE
);
460 * Cancels the authenticator activity
462 * IMPORTANT ENTRY POINT 3: Never underestimate the importance of cancellation
464 * This method is bound in the layout/acceoun_setup.xml resource file.
466 * @param view Cancel button
468 public void onCancelClick(View view
) {
469 setResult(RESULT_CANCELED
); // TODO review how is this related to AccountAuthenticator (debugging)
476 * Checks the credentials of the user in the root of the ownCloud server
477 * before creating a new local account.
479 * For basic authorization, a check of existence of the root folder is
482 * For OAuth, starts the flow to get an access token; the credentials test
483 * is postponed until it is available.
485 * IMPORTANT ENTRY POINT 4
487 * @param view OK button
489 public void onOkClick(View view
) {
490 // this check should be unnecessary
491 if (mDiscoveredVersion
== null
|| !mDiscoveredVersion
.isVersionValid() || mHostBaseUrl
== null
|| mHostBaseUrl
.length() == 0) {
492 mStatusIcon
= R
.drawable
.common_error
;
493 mStatusText
= R
.string
.auth_wtf_reenter_URL
;
495 mOkButton
.setEnabled(false
);
496 Log_OC
.wtf(TAG
, "The user was allowed to click 'connect' to an unchecked server!!");
500 if (mOAuth2Check
.isChecked()) {
501 startOauthorization();
504 checkBasicAuthorization();
510 * Tests the credentials entered by the user performing a check of existence on
511 * the root folder of the ownCloud server.
513 private void checkBasicAuthorization() {
514 /// get the path to the root folder through WebDAV from the version server
515 String webdav_path
= AccountUtils
.getWebdavPath(mDiscoveredVersion
, false
);
517 /// get basic credentials entered by user
518 String username
= mUsernameInput
.getText().toString();
519 String password
= mPasswordInput
.getText().toString();
521 /// be gentle with the user
522 showDialog(DIALOG_LOGIN_PROGRESS
);
524 /// test credentials accessing the root folder
525 mAuthCheckOperation
= new ExistenceCheckOperation("", this, false
);
526 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(mHostBaseUrl
+ webdav_path
), this);
527 client
.setBasicCredentials(username
, password
);
528 mOperationThread
= mAuthCheckOperation
.execute(client
, this, mHandler
);
533 * Starts the OAuth 'grant type' flow to get an access token, with
534 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
536 private void startOauthorization() {
537 // be gentle with the user
538 mStatusIcon
= R
.drawable
.progress_small
;
539 mStatusText
= R
.string
.oauth_login_connection
;
542 // GET AUTHORIZATION request
543 //Uri uri = Uri.parse(getString(R.string.oauth2_url_endpoint_auth));
544 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
545 Uri
.Builder uriBuilder
= uri
.buildUpon();
546 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
));
547 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
));
548 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
));
549 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
));
550 //uriBuilder.appendQueryParameter(OAuth2Constants.KEY_STATE, whateverwewant);
551 uri
= uriBuilder
.build();
552 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
553 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
559 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
561 * Dispatches the operation flow to the right method.
564 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
566 if (operation
instanceof OwnCloudServerCheckOperation
) {
567 onOcServerCheckFinish((OwnCloudServerCheckOperation
) operation
, result
);
569 } else if (operation
instanceof OAuth2GetAccessToken
) {
570 onGetOAuthAccessTokenFinish((OAuth2GetAccessToken
)operation
, result
);
572 } else if (operation
instanceof ExistenceCheckOperation
) {
573 onAuthorizationCheckFinish((ExistenceCheckOperation
)operation
, result
);
580 * Processes the result of the server check performed when the user finishes the enter of the
583 * @param operation Server check performed.
584 * @param result Result of the check.
586 private void onOcServerCheckFinish(OwnCloudServerCheckOperation operation
, RemoteOperationResult result
) {
587 /// update status icon and text
588 updateStatusIconAndText(result
);
591 /// save result state
592 mStatusCorrect
= result
.isSuccess();
593 mIsSslConn
= (result
.getCode() == ResultCode
.OK_SSL
);
595 /// very special case (TODO: move to a common place for all the remote operations)
596 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
597 mLastSslUntrustedServerResult
= result
;
598 showDialog(DIALOG_SSL_VALIDATOR
);
601 /// update the visibility of the 'retry connection' button
602 if (!mStatusCorrect
) {
603 mHostUrlInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, R
.drawable
.ic_action_refresh_black
, 0);
605 mHostUrlInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
608 /// retrieve discovered version and normalize server URL
609 mDiscoveredVersion
= operation
.getDiscoveredVersion();
610 mHostBaseUrl
= mHostUrlInput
.getText().toString().trim();
611 if (!mHostBaseUrl
.toLowerCase().startsWith("http://") &&
612 !mHostBaseUrl
.toLowerCase().startsWith("https://")) {
615 mHostBaseUrl
= "https://" + mHostBaseUrl
;
617 mHostBaseUrl
= "http://" + mHostBaseUrl
;
621 if (mHostBaseUrl
.endsWith("/"))
622 mHostBaseUrl
= mHostBaseUrl
.substring(0, mHostBaseUrl
.length() - 1);
624 /// allow or not the user try to access the server
625 mOkButton
.setEnabled(mStatusCorrect
);
630 * Chooses the right icon and text to show to the user for the received operation result.
632 * @param result Result of a remote operation performed in this activity
634 private void updateStatusIconAndText(RemoteOperationResult result
) {
635 mStatusText
= mStatusIcon
= 0;
637 switch (result
.getCode()) {
639 mStatusIcon
= android
.R
.drawable
.ic_secure
;
640 mStatusText
= R
.string
.auth_secure_connection
;
645 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
646 mStatusText
= R
.string
.auth_connection_established
;
647 mStatusIcon
= R
.drawable
.ic_ok
;
649 mStatusText
= R
.string
.auth_nossl_plain_ok_title
;
650 mStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
654 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
655 mStatusIcon
= R
.drawable
.common_error
;
656 mStatusText
= R
.string
.auth_ssl_unverified_server_title
;
660 mStatusIcon
= R
.drawable
.common_error
;
661 mStatusText
= R
.string
.auth_bad_oc_version_title
;
663 case WRONG_CONNECTION
:
664 mStatusIcon
= R
.drawable
.common_error
;
665 mStatusText
= R
.string
.auth_wrong_connection_title
;
668 mStatusIcon
= R
.drawable
.common_error
;
669 mStatusText
= R
.string
.auth_timeout_title
;
671 case INCORRECT_ADDRESS
:
672 mStatusIcon
= R
.drawable
.common_error
;
673 mStatusText
= R
.string
.auth_incorrect_address_title
;
677 mStatusIcon
= R
.drawable
.common_error
;
678 mStatusText
= R
.string
.auth_ssl_general_error_title
;
682 mStatusIcon
= R
.drawable
.common_error
;
683 mStatusText
= R
.string
.auth_unauthorized
;
685 case HOST_NOT_AVAILABLE
:
686 mStatusIcon
= R
.drawable
.common_error
;
687 mStatusText
= R
.string
.auth_unknown_host_title
;
689 case NO_NETWORK_CONNECTION
:
690 mStatusIcon
= R
.drawable
.no_network
;
691 mStatusText
= R
.string
.auth_no_net_conn_title
;
693 case INSTANCE_NOT_CONFIGURED
:
694 mStatusIcon
= R
.drawable
.common_error
;
695 mStatusText
= R
.string
.auth_not_configured_title
;
698 mStatusIcon
= R
.drawable
.common_error
;
699 mStatusText
= R
.string
.auth_incorrect_path_title
;
702 mStatusIcon
= R
.drawable
.common_error
;
703 mStatusText
= R
.string
.auth_oauth_error
;
705 case OAUTH2_ERROR_ACCESS_DENIED
:
706 mStatusIcon
= R
.drawable
.common_error
;
707 mStatusText
= R
.string
.auth_oauth_error_access_denied
;
709 case UNHANDLED_HTTP_CODE
:
711 mStatusIcon
= R
.drawable
.common_error
;
712 mStatusText
= R
.string
.auth_unknown_error_title
;
722 * Processes the result of the request for and access token send
723 * to an OAuth authorization server.
725 * @param operation Operation performed requesting the access token.
726 * @param result Result of the operation.
728 private void onGetOAuthAccessTokenFinish(OAuth2GetAccessToken operation
, RemoteOperationResult result
) {
730 dismissDialog(DIALOG_OAUTH2_LOGIN_PROGRESS
);
731 } catch (IllegalArgumentException e
) {
732 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
735 String webdav_path
= AccountUtils
.getWebdavPath(mDiscoveredVersion
, true
);
736 if (result
.isSuccess() && webdav_path
!= null
) {
737 /// be gentle with the user
738 showDialog(DIALOG_LOGIN_PROGRESS
);
740 /// time to test the retrieved access token on the ownCloud server
741 mOAuthAccessToken
= ((OAuth2GetAccessToken
)operation
).getResultTokenMap().get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
742 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mOAuthAccessToken
);
743 mAuthCheckOperation
= new ExistenceCheckOperation("", this, false
);
744 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(mHostBaseUrl
+ webdav_path
), this);
745 client
.setBearerCredentials(mOAuthAccessToken
);
746 mAuthCheckOperation
.execute(client
, this, mHandler
);
749 updateStatusIconAndText(result
);
751 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
757 * Processes the result of the access check performed to try the user credentials.
759 * Creates a new account through the AccountManager.
761 * @param operation Access check performed.
762 * @param result Result of the operation.
764 private void onAuthorizationCheckFinish(ExistenceCheckOperation operation
, RemoteOperationResult result
) {
766 dismissDialog(DIALOG_LOGIN_PROGRESS
);
767 } catch (IllegalArgumentException e
) {
768 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
771 if (result
.isSuccess()) {
772 Log_OC
.d(TAG
, "Successful access - time to save the account");
774 if (mAction
== ACTION_CREATE
) {
784 updateStatusIconAndText(result
);
786 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
792 * Sets the proper response to get that the Account Authenticator that started this activity saves
793 * a new authorization token for mAccount.
795 private void updateToken() {
796 Bundle response
= new Bundle();
797 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
798 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
799 boolean isOAuth
= mOAuth2Check
.isChecked();
801 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mOAuthAccessToken
);
802 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
803 mAccountMgr
.setAuthToken(mAccount
, AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
, mOAuthAccessToken
);
805 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
806 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
808 setAccountAuthenticatorResult(response
);
813 * Creates a new account through the Account Authenticator that started this activity.
815 * This makes the account permanent.
817 * TODO Decide how to name the OAuth accounts
819 private void createAccount() {
820 /// create and save new ownCloud account
821 boolean isOAuth
= mOAuth2Check
.isChecked();
823 Uri uri
= Uri
.parse(mHostBaseUrl
);
824 String username
= mUsernameInput
.getText().toString().trim();
826 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
828 String accountName
= username
+ "@" + uri
.getHost();
829 if (uri
.getPort() >= 0) {
830 accountName
+= ":" + uri
.getPort();
832 mAccount
= new Account(accountName
, AccountAuthenticator
.ACCOUNT_TYPE
);
834 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
); // with our implementation, the password is never input in the app
836 mAccountMgr
.addAccountExplicitly(mAccount
, mPasswordInput
.getText().toString(), null
);
839 /// add the new account as default in preferences, if there is none already
840 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
841 if (defaultAccount
== null
) {
842 SharedPreferences
.Editor editor
= PreferenceManager
843 .getDefaultSharedPreferences(this).edit();
844 editor
.putString("select_oc_account", accountName
);
848 /// prepare result to return to the Authenticator
849 // TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done
850 final Intent intent
= new Intent();
851 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, AccountAuthenticator
.ACCOUNT_TYPE
);
852 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
854 intent
.putExtra(AccountManager
.KEY_AUTHTOKEN
, AccountAuthenticator
.ACCOUNT_TYPE
); // TODO check this; not sure it's right; maybe
855 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
857 mAccountMgr
.setAuthToken(mAccount
, AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
, mOAuthAccessToken
);
859 /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
860 mAccountMgr
.setUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
, mDiscoveredVersion
.toString());
861 mAccountMgr
.setUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
, mHostBaseUrl
);
863 mAccountMgr
.setUserData(mAccount
, AccountAuthenticator
.KEY_SUPPORTS_OAUTH2
, "TRUE"); // TODO this flag should be unnecessary
865 setAccountAuthenticatorResult(intent
.getExtras());
866 setResult(RESULT_OK
, intent
);
868 /// immediately request for the synchronization of the new account
869 Bundle bundle
= new Bundle();
870 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
871 ContentResolver
.requestSync(mAccount
, AccountAuthenticator
.AUTHORITY
, bundle
);
878 * Necessary to update the contents of the SSL Dialog
880 * TODO move to some common place for all possible untrusted SSL failures
883 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
885 case DIALOG_LOGIN_PROGRESS
:
886 case DIALOG_CERT_NOT_SAVED
:
887 case DIALOG_OAUTH2_LOGIN_PROGRESS
:
889 case DIALOG_SSL_VALIDATOR
: {
890 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
894 Log_OC
.e(TAG
, "Incorrect dialog called with id = " + id
);
903 protected Dialog
onCreateDialog(int id
) {
904 Dialog dialog
= null
;
906 case DIALOG_LOGIN_PROGRESS
: {
907 /// simple progress dialog
908 ProgressDialog working_dialog
= new ProgressDialog(this);
909 working_dialog
.setMessage(getResources().getString(R
.string
.auth_trying_to_login
));
910 working_dialog
.setIndeterminate(true
);
911 working_dialog
.setCancelable(true
);
913 .setOnCancelListener(new DialogInterface
.OnCancelListener() {
915 public void onCancel(DialogInterface dialog
) {
916 /// TODO study if this is enough
917 Log_OC
.i(TAG
, "Login canceled");
918 if (mOperationThread
!= null
) {
919 mOperationThread
.interrupt();
924 dialog
= working_dialog
;
927 case DIALOG_OAUTH2_LOGIN_PROGRESS
: {
928 ProgressDialog working_dialog
= new ProgressDialog(this);
929 working_dialog
.setMessage(String
.format("Getting authorization"));
930 working_dialog
.setIndeterminate(true
);
931 working_dialog
.setCancelable(true
);
933 .setOnCancelListener(new DialogInterface
.OnCancelListener() {
935 public void onCancel(DialogInterface dialog
) {
936 Log_OC
.i(TAG
, "Login canceled");
940 dialog
= working_dialog
;
943 case DIALOG_SSL_VALIDATOR
: {
944 /// TODO start to use new dialog interface, at least for this (it is a FragmentDialog already)
945 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
948 case DIALOG_CERT_NOT_SAVED
: {
949 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
950 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
951 builder
.setCancelable(false
);
952 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
954 public void onClick(DialogInterface dialog
, int which
) {
958 dialog
= builder
.create();
962 Log_OC
.e(TAG
, "Incorrect dialog called with id = " + id
);
969 * Starts and activity to open the 'new account' page in the ownCloud web site
971 * @param view 'Account register' button
973 public void onRegisterClick(View view
) {
974 Intent register
= new Intent(Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.url_account_register
)));
975 setResult(RESULT_CANCELED
);
976 startActivity(register
);
981 * Updates the content and visibility state of the icon and text associated
982 * to the last check on the ownCloud server.
984 private void updateConnStatus() {
985 TextView tv
= (TextView
) findViewById(R
.id
.server_status_text
);
987 if (mStatusIcon
== 0 && mStatusText
== 0) {
988 tv
.setVisibility(View
.INVISIBLE
);
990 tv
.setText(mStatusText
);
991 tv
.setCompoundDrawablesWithIntrinsicBounds(mStatusIcon
, 0, 0, 0);
992 tv
.setVisibility(View
.VISIBLE
);
998 * Updates the content and visibility state of the icon and text associated
999 * to the interactions with the OAuth authorization server.
1001 private void updateAuthStatus() {
1002 if (mStatusIcon
== 0 && mStatusText
== 0) {
1003 mAuthStatusLayout
.setVisibility(View
.INVISIBLE
);
1005 mAuthStatusLayout
.setText(mStatusText
);
1006 mAuthStatusLayout
.setCompoundDrawablesWithIntrinsicBounds(mStatusIcon
, 0, 0, 0);
1007 mAuthStatusLayout
.setVisibility(View
.VISIBLE
);
1013 * Called when the refresh button in the input field for ownCloud host is clicked.
1015 * Performs a new check on the URL in the input field.
1017 * @param view Refresh 'button'
1019 public void onRefreshClick(View view
) {
1020 onFocusChange(mHostUrlInput
, false
);
1025 * Called when the eye icon in the password field is clicked.
1027 * Toggles the visibility of the password in the field.
1029 * @param view 'View password' 'button'
1031 public void onViewPasswordClick(View view
) {
1032 int selectionStart
= mPasswordInput
.getSelectionStart();
1033 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1034 int input_type
= mPasswordInput
.getInputType();
1035 if ((input_type
& InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) == InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) {
1036 input_type
= InputType
.TYPE_CLASS_TEXT
1037 | InputType
.TYPE_TEXT_VARIATION_PASSWORD
;
1039 input_type
= InputType
.TYPE_CLASS_TEXT
1040 | InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
;
1042 mPasswordInput
.setInputType(input_type
);
1043 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1048 * Called when the checkbox for OAuth authorization is clicked.
1050 * Hides or shows the input fields for user & password.
1052 * @param view 'View password' 'button'
1054 public void onCheckClick(View view
) {
1055 CheckBox oAuth2Check
= (CheckBox
)view
;
1056 changeViewByOAuth2Check(oAuth2Check
.isChecked());
1061 * Changes the visibility of input elements depending upon the kind of authorization
1062 * chosen by the user: basic or OAuth
1064 * @param checked 'True' when OAuth is selected.
1066 public void changeViewByOAuth2Check(Boolean checked
) {
1069 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
1070 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
1071 mUsernameInput
.setVisibility(View
.GONE
);
1072 mPasswordInput
.setVisibility(View
.GONE
);
1073 mViewPasswordButton
.setVisibility(View
.GONE
);
1075 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
1076 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
1077 mUsernameInput
.setVisibility(View
.VISIBLE
);
1078 mPasswordInput
.setVisibility(View
.VISIBLE
);
1079 mViewPasswordButton
.setVisibility(View
.INVISIBLE
);
1085 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1087 public void onSavedCertificate() {
1088 mOperationThread
= mOcServerChkOperation
.retry(this, mHandler
);
1092 * Called from SslValidatorDialog when a new server certificate could not be saved
1093 * when the user requested it.
1096 public void onFailedSavingCertificate() {
1097 showDialog(DIALOG_CERT_NOT_SAVED
);
1102 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1104 * Used to trigger the authorization check when the user presses 'enter' after writing the password.
1107 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1108 if (inputField
!= null
&& inputField
.equals(mPasswordInput
) &&
1109 actionId
== EditorInfo
.IME_ACTION_DONE
) {
1110 if (mOkButton
.isEnabled()) {
1111 mOkButton
.performClick();
1114 return false
; // always return false to grant that the software keyboard is hidden anyway
1118 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1120 private int fuzz
= 10;
1126 public boolean onTouch(View view
, MotionEvent event
) {
1127 if (event
.getAction() == MotionEvent
.ACTION_DOWN
) {
1128 Drawable rightDrawable
= null
;
1129 if (view
instanceof TextView
) {
1130 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1131 if (drawables
.length
> 2) {
1132 rightDrawable
= drawables
[2];
1135 if (rightDrawable
!= null
) {
1136 final int x
= (int) event
.getX();
1137 final int y
= (int) event
.getY();
1138 final Rect bounds
= rightDrawable
.getBounds();
1139 if (x
>= (view
.getRight() - bounds
.width() - fuzz
) && x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
)
1140 && y
>= (view
.getPaddingTop() - fuzz
) && y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1142 return onDrawableTouch(event
);
1149 public abstract boolean onDrawableTouch(final MotionEvent event
);