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
.Log_OC
;
22 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
;
23 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
.OnSslValidatorListener
;
24 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
25 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
26 import com
.owncloud
.android
.operations
.OwnCloudServerCheckOperation
;
27 import com
.owncloud
.android
.operations
.ExistenceCheckOperation
;
28 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
29 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
30 import com
.owncloud
.android
.operations
.RemoteOperation
;
31 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
32 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
34 import android
.accounts
.Account
;
35 import android
.accounts
.AccountAuthenticatorActivity
;
36 import android
.accounts
.AccountManager
;
37 import android
.app
.AlertDialog
;
38 import android
.app
.Dialog
;
39 import android
.app
.ProgressDialog
;
40 import android
.content
.ContentResolver
;
41 import android
.content
.DialogInterface
;
42 import android
.content
.Intent
;
43 import android
.content
.SharedPreferences
;
44 import android
.graphics
.Rect
;
45 import android
.graphics
.drawable
.Drawable
;
46 import android
.net
.Uri
;
47 import android
.os
.Bundle
;
48 import android
.os
.Handler
;
49 import android
.preference
.PreferenceManager
;
50 import android
.text
.Editable
;
51 import android
.text
.InputType
;
52 import android
.text
.TextWatcher
;
53 import android
.view
.KeyEvent
;
54 import android
.view
.MotionEvent
;
55 import android
.view
.View
;
56 import android
.view
.View
.OnFocusChangeListener
;
57 import android
.view
.View
.OnTouchListener
;
58 import android
.view
.Window
;
59 import android
.view
.inputmethod
.EditorInfo
;
60 import android
.webkit
.WebView
;
61 import android
.widget
.CheckBox
;
62 import android
.widget
.EditText
;
63 import android
.widget
.Button
;
64 import android
.widget
.TextView
;
65 import android
.widget
.Toast
;
66 import android
.widget
.TextView
.OnEditorActionListener
;
68 import com
.owncloud
.android
.R
;
70 import eu
.alefzero
.webdav
.WebdavClient
;
73 * This Activity is used to add an ownCloud account to the App
75 * @author Bartek Przybylski
76 * @author David A. Velasco
78 public class AuthenticatorActivity
extends AccountAuthenticatorActivity
79 implements OnRemoteOperationListener
, OnSslValidatorListener
, OnFocusChangeListener
, OnEditorActionListener
{
81 private static final String TAG
= AuthenticatorActivity
.class.getSimpleName();
83 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
84 public static final String EXTRA_USER_NAME
= "USER_NAME";
85 public static final String EXTRA_HOST_NAME
= "HOST_NAME";
86 public static final String EXTRA_ACTION
= "ACTION";
87 public static final String EXTRA_ENFORCED_UPDATE
= "ENFORCE_UPDATE";
89 private static final String KEY_HOST_URL_TEXT
= "HOST_URL_TEXT";
90 private static final String KEY_OC_VERSION
= "OC_VERSION";
91 private static final String KEY_ACCOUNT
= "ACCOUNT";
92 private static final String KEY_SERVER_VALID
= "SERVER_VALID";
93 private static final String KEY_SERVER_CHECKED
= "SERVER_CHECKED";
94 private static final String KEY_SERVER_CHECK_IN_PROGRESS
= "SERVER_CHECK_IN_PROGRESS";
95 private static final String KEY_SERVER_STATUS_TEXT
= "SERVER_STATUS_TEXT";
96 private static final String KEY_SERVER_STATUS_ICON
= "SERVER_STATUS_ICON";
97 private static final String KEY_IS_SSL_CONN
= "IS_SSL_CONN";
98 private static final String KEY_PASSWORD_VISIBLE
= "PASSWORD_VISIBLE";
99 private static final String KEY_AUTH_METHOD
= "AUTH_METHOD";
100 private static final String KEY_AUTH_STATUS_TEXT
= "AUTH_STATUS_TEXT";
101 private static final String KEY_AUTH_STATUS_ICON
= "AUTH_STATUS_ICON";
102 private static final String KEY_REFRESH_BUTTON_ENABLED
= "KEY_REFRESH_BUTTON_ENABLED";
104 private static final String AUTH_ON
= "on";
105 private static final String AUTH_OFF
= "off";
106 private static final String AUTH_OPTIONAL
= "optional";
108 private static final int AUTH_METHOD_BASIC_HTTP
= 0;
109 private static final int AUTH_METHOD_OAUTH2
= 1;
110 private static final int AUTH_METHOD_SAML_WEB_SSO
= 2;
112 private static final int DIALOG_LOGIN_PROGRESS
= 0;
113 private static final int DIALOG_SSL_VALIDATOR
= 1;
114 private static final int DIALOG_CERT_NOT_SAVED
= 2;
115 private static final int DIALOG_OAUTH2_LOGIN_PROGRESS
= 3;
117 public static final byte ACTION_CREATE
= 0;
118 public static final byte ACTION_UPDATE_TOKEN
= 1;
120 private String mHostBaseUrl
;
121 private OwnCloudVersion mDiscoveredVersion
;
123 private int mServerStatusText
, mServerStatusIcon
;
124 private boolean mServerIsChecked
, mServerIsValid
, mIsSslConn
;
125 private int mAuthStatusText
, mAuthStatusIcon
;
126 private TextView mAuthStatusLayout
;
128 private final Handler mHandler
= new Handler();
129 private Thread mOperationThread
;
130 private OwnCloudServerCheckOperation mOcServerChkOperation
;
131 private ExistenceCheckOperation mAuthCheckOperation
;
132 private RemoteOperationResult mLastSslUntrustedServerResult
;
134 private Uri mNewCapturedUriFromOAuth2Redirection
;
136 private AccountManager mAccountMgr
;
137 private boolean mJustCreated
;
138 private byte mAction
;
139 private Account mAccount
;
141 private EditText mHostUrlInput
;
142 private boolean mHostUrlInputEnabled
;
143 private View mRefreshButton
;
145 private int mCurrentAuthorizationMethod
;
147 private EditText mUsernameInput
;
148 private EditText mPasswordInput
;
150 private CheckBox mOAuth2Check
;
151 private String mOAuthAccessToken
;
153 private TextView mOAuthAuthEndpointText
;
154 private TextView mOAuthTokenEndpointText
;
156 private TextView mAccountNameInput
;
157 private WebView mWebSsoView
;
159 private View mOkButton
;
165 * IMPORTANT ENTRY POINT 1: activity is shown to the user
168 protected void onCreate(Bundle savedInstanceState
) {
169 super.onCreate(savedInstanceState
);
170 getWindow().requestFeature(Window
.FEATURE_NO_TITLE
);
172 /// set view and get references to view elements
173 setContentView(R
.layout
.account_setup
);
174 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
175 mHostUrlInput
.setText(getString(R
.string
.server_url
)); // valid although R.string.server_url is an empty string
176 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
177 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
178 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
179 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
180 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
181 mAccountNameInput
= (EditText
) findViewById(R
.id
.account_name
);
182 mWebSsoView
= (WebView
) findViewById(R
.id
.web_sso_view
);
183 mOkButton
= findViewById(R
.id
.buttonOK
);
184 mAuthStatusLayout
= (TextView
) findViewById(R
.id
.auth_status_text
);
186 /// set Host Url Input Enabled
187 mHostUrlInputEnabled
= getResources().getBoolean(R
.bool
.show_server_url_input
);
190 /// complete label for 'register account' button
191 Button b
= (Button
) findViewById(R
.id
.account_register
);
193 b
.setText(String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
197 mAccountMgr
= AccountManager
.get(this);
198 mNewCapturedUriFromOAuth2Redirection
= null
;
199 mAction
= getIntent().getByteExtra(EXTRA_ACTION
, ACTION_CREATE
);
202 boolean refreshButtonEnabled
= false
;
204 // URL input configuration applied
205 if (!mHostUrlInputEnabled
)
207 findViewById(R
.id
.hostUrlFrame
).setVisibility(View
.GONE
);
208 mRefreshButton
= findViewById(R
.id
.centeredRefreshButton
);
211 mRefreshButton
= findViewById(R
.id
.embeddedRefreshButton
);
214 if (savedInstanceState
== null
) {
215 /// connection state and info
216 mServerStatusText
= mServerStatusIcon
= 0;
217 mServerIsValid
= false
;
218 mServerIsChecked
= false
;
220 mAuthStatusText
= mAuthStatusIcon
= 0;
222 /// retrieve extras from intent
223 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
224 if (mAccount
!= null
) {
225 String ocVersion
= mAccountMgr
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
);
226 if (ocVersion
!= null
) {
227 mDiscoveredVersion
= new OwnCloudVersion(ocVersion
);
229 mHostBaseUrl
= normalizeUrl(mAccountMgr
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
));
230 mHostUrlInput
.setText(mHostBaseUrl
);
232 initAuthorizationMethod(); // checks intent and setup.xml to determine mCurrentAuthorizationMethod
233 mOAuth2Check
.setChecked(mCurrentAuthorizationMethod
== AUTH_METHOD_OAUTH2
);
236 if (mAction
== ACTION_UPDATE_TOKEN
|| !mHostUrlInputEnabled
) {
241 /// connection state and info
242 mServerIsValid
= savedInstanceState
.getBoolean(KEY_SERVER_VALID
);
243 mServerIsChecked
= savedInstanceState
.getBoolean(KEY_SERVER_CHECKED
);
244 mServerStatusText
= savedInstanceState
.getInt(KEY_SERVER_STATUS_TEXT
);
245 mServerStatusIcon
= savedInstanceState
.getInt(KEY_SERVER_STATUS_ICON
);
246 mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
247 mAuthStatusText
= savedInstanceState
.getInt(KEY_AUTH_STATUS_TEXT
);
248 mAuthStatusIcon
= savedInstanceState
.getInt(KEY_AUTH_STATUS_ICON
);
249 if (savedInstanceState
.getBoolean(KEY_PASSWORD_VISIBLE
, false
)) {
254 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
255 if (ocVersion
!= null
) {
256 mDiscoveredVersion
= new OwnCloudVersion(ocVersion
);
258 mHostBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
260 // account data, if updating
261 mAccount
= savedInstanceState
.getParcelable(KEY_ACCOUNT
);
262 mCurrentAuthorizationMethod
= savedInstanceState
.getInt(KEY_AUTH_METHOD
, AUTH_METHOD_BASIC_HTTP
);
264 // check if server check was interrupted by a configuration change
265 if (savedInstanceState
.getBoolean(KEY_SERVER_CHECK_IN_PROGRESS
, false
)) {
269 // refresh button enabled
270 refreshButtonEnabled
= savedInstanceState
.getBoolean(KEY_REFRESH_BUTTON_ENABLED
);
275 adaptViewAccordingToAuthenticationMethod();
279 if (mAction
== ACTION_UPDATE_TOKEN
) {
280 /// lock things that should not change
281 mHostUrlInput
.setEnabled(false
);
282 mHostUrlInput
.setFocusable(false
);
283 mUsernameInput
.setEnabled(false
);
284 mUsernameInput
.setFocusable(false
);
285 mOAuth2Check
.setVisibility(View
.GONE
);
288 //if (mServerIsChecked && !mServerIsValid && mRefreshButtonEnabled) showRefreshButton();
289 if (mServerIsChecked
&& !mServerIsValid
&& refreshButtonEnabled
) showRefreshButton();
290 mOkButton
.setEnabled(mServerIsValid
); // state not automatically recovered in configuration changes
292 if (mCurrentAuthorizationMethod
== AUTH_METHOD_SAML_WEB_SSO
|| !AUTH_OPTIONAL
.equals(getString(R
.string
.auth_method_oauth2
))) {
293 mOAuth2Check
.setVisibility(View
.GONE
);
296 mPasswordInput
.setText(""); // clean password to avoid social hacking (disadvantage: password in removed if the device is turned aside)
298 /// bind view elements to listeners
299 mHostUrlInput
.setOnFocusChangeListener(this);
300 mHostUrlInput
.addTextChangedListener(new TextWatcher() {
303 public void afterTextChanged(Editable s
) {
304 if (!mHostBaseUrl
.equals(normalizeUrl(mHostUrlInput
.getText().toString()))) {
305 mOkButton
.setEnabled(false
);
310 public void beforeTextChanged(CharSequence s
, int start
, int count
, int after
) {}
313 public void onTextChanged(CharSequence s
, int start
, int before
, int count
) {}
316 mPasswordInput
.setOnFocusChangeListener(this);
317 mPasswordInput
.setImeOptions(EditorInfo
.IME_ACTION_DONE
);
318 mPasswordInput
.setOnEditorActionListener(this);
319 mPasswordInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
321 public boolean onDrawableTouch(final MotionEvent event
) {
322 if (event
.getAction() == MotionEvent
.ACTION_UP
) {
323 AuthenticatorActivity
.this.onViewPasswordClick();
330 private void initAuthorizationMethod() {
331 boolean oAuthRequired
= false
;
332 boolean samlWebSsoRequired
= false
;
334 String tokenType
= getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
335 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
337 if (tokenType
!= null
) {
338 /// use the authentication method requested by caller
339 oAuthRequired
= AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
.equals(tokenType
);
340 samlWebSsoRequired
= AccountAuthenticator
.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE
.equals(tokenType
);
342 } else if (mAccount
!= null
) {
343 /// same authentication method than the one used to create the account to update
344 oAuthRequired
= (mAccountMgr
.getUserData(mAccount
, AccountAuthenticator
.KEY_SUPPORTS_OAUTH2
) != null
);
345 samlWebSsoRequired
= (mAccountMgr
.getUserData(mAccount
, AccountAuthenticator
.KEY_SUPPORTS_SAML_WEB_SSO
) != null
);
348 /// use the one set in setup.xml
349 oAuthRequired
= AUTH_ON
.equals(getString(R
.string
.auth_method_oauth2
));
350 samlWebSsoRequired
= AUTH_ON
.equals(getString(R
.string
.auth_method_saml_web_sso
));
354 mCurrentAuthorizationMethod
= AUTH_METHOD_OAUTH2
;
355 } else if (samlWebSsoRequired
) {
356 mCurrentAuthorizationMethod
= AUTH_METHOD_SAML_WEB_SSO
;
358 mCurrentAuthorizationMethod
= AUTH_METHOD_BASIC_HTTP
;
361 if (mAccount
!= null
) {
362 String userName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
363 mUsernameInput
.setText(userName
);
368 * Saves relevant state before {@link #onPause()}
370 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag, intended to defer the
371 * processing of the redirection caught in {@link #onNewIntent(Intent)} until {@link #onResume()}
373 * See {@link #loadSavedInstanceState(Bundle)}
376 protected void onSaveInstanceState(Bundle outState
) {
377 super.onSaveInstanceState(outState
);
379 /// connection state and info
380 outState
.putInt(KEY_SERVER_STATUS_TEXT
, mServerStatusText
);
381 outState
.putInt(KEY_SERVER_STATUS_ICON
, mServerStatusIcon
);
382 outState
.putBoolean(KEY_SERVER_VALID
, mServerIsValid
);
383 outState
.putBoolean(KEY_SERVER_CHECKED
, mServerIsChecked
);
384 outState
.putBoolean(KEY_SERVER_CHECK_IN_PROGRESS
, (!mServerIsValid
&& mOcServerChkOperation
!= null
));
385 outState
.putBoolean(KEY_IS_SSL_CONN
, mIsSslConn
);
386 outState
.putBoolean(KEY_PASSWORD_VISIBLE
, isPasswordVisible());
387 outState
.putInt(KEY_AUTH_STATUS_ICON
, mAuthStatusIcon
);
388 outState
.putInt(KEY_AUTH_STATUS_TEXT
, mAuthStatusText
);
391 if (mDiscoveredVersion
!= null
) {
392 outState
.putString(KEY_OC_VERSION
, mDiscoveredVersion
.toString());
394 outState
.putString(KEY_HOST_URL_TEXT
, mHostBaseUrl
);
396 /// account data, if updating
397 if (mAccount
!= null
) {
398 outState
.putParcelable(KEY_ACCOUNT
, mAccount
);
400 outState
.putInt(KEY_AUTH_METHOD
, mCurrentAuthorizationMethod
);
402 // refresh button enabled
403 outState
.putBoolean(KEY_REFRESH_BUTTON_ENABLED
, (mRefreshButton
.getVisibility() == View
.VISIBLE
));
409 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION request
412 * To make this possible, this activity needs to be qualified with android:launchMode = "singleTask" in the
413 * AndroidManifest.xml file.
416 protected void onNewIntent (Intent intent
) {
417 Log_OC
.d(TAG
, "onNewIntent()");
418 Uri data
= intent
.getData();
419 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
420 mNewCapturedUriFromOAuth2Redirection
= data
;
426 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION, and
427 * deferred in {@link #onNewIntent(Intent)}, is processed here.
430 protected void onResume() {
432 if (mAction
== ACTION_UPDATE_TOKEN
&& mJustCreated
&& getIntent().getBooleanExtra(EXTRA_ENFORCED_UPDATE
, false
)) {
433 if (mOAuth2Check
.isChecked())
434 Toast
.makeText(this, R
.string
.auth_expired_oauth_token_toast
, Toast
.LENGTH_LONG
).show();
436 Toast
.makeText(this, R
.string
.auth_expired_basic_auth_toast
, Toast
.LENGTH_LONG
).show();
439 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
440 getOAuth2AccessTokenFromCapturedRedirection();
443 mJustCreated
= false
;
448 * Parses the redirection with the response to the GET AUTHORIZATION request to the
449 * oAuth server and requests for the access token (GET ACCESS TOKEN)
451 private void getOAuth2AccessTokenFromCapturedRedirection() {
452 /// Parse data from OAuth redirection
453 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
454 mNewCapturedUriFromOAuth2Redirection
= null
;
456 /// Showing the dialog with instructions for the user.
457 showDialog(DIALOG_OAUTH2_LOGIN_PROGRESS
);
459 /// GET ACCESS TOKEN to the oAuth server
460 RemoteOperation operation
= new OAuth2GetAccessToken( getString(R
.string
.oauth2_client_id
),
461 getString(R
.string
.oauth2_redirect_uri
),
462 getString(R
.string
.oauth2_grant_type
),
464 //WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(getString(R.string.oauth2_url_endpoint_access)), getApplicationContext());
465 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(mOAuthTokenEndpointText
.getText().toString().trim()), getApplicationContext());
466 operation
.execute(client
, this, mHandler
);
472 * Handles the change of focus on the text inputs for the server URL and the password
474 public void onFocusChange(View view
, boolean hasFocus
) {
475 if (view
.getId() == R
.id
.hostUrlInput
) {
477 onUrlInputFocusLost((TextView
) view
);
483 } else if (view
.getId() == R
.id
.account_password
) {
484 onPasswordFocusChanged((TextView
) view
, hasFocus
);
490 * Handles changes in focus on the text input for the server URL.
492 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
493 * other field. The operation to check the existence of the server in the entered URL is
496 * When hasFocus: user 'comes back' to write again the server URL.
498 * @param hostInput TextView with the URL input field receiving the change of focus.
500 private void onUrlInputFocusLost(TextView hostInput
) {
501 if (!mHostBaseUrl
.equals(normalizeUrl(mHostUrlInput
.getText().toString()))) {
504 mOkButton
.setEnabled(mServerIsValid
);
505 if (!mServerIsValid
) {
512 private void checkOcServer() {
513 String uri
= trimUrlWebdav(mHostUrlInput
.getText().toString().trim());
515 if (!mHostUrlInputEnabled
){
516 uri
= getString(R
.string
.server_url
);
519 mServerIsValid
= false
;
520 mServerIsChecked
= false
;
521 mOkButton
.setEnabled(false
);
522 mDiscoveredVersion
= null
;
524 if (uri
.length() != 0) {
525 mServerStatusText
= R
.string
.auth_testing_connection
;
526 mServerStatusIcon
= R
.drawable
.progress_small
;
528 mOcServerChkOperation
= new OwnCloudServerCheckOperation(uri
, this);
529 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(uri
), this);
530 mOperationThread
= mOcServerChkOperation
.execute(client
, this, mHandler
);
532 mServerStatusText
= 0;
533 mServerStatusIcon
= 0;
540 * Handles changes in focus on the text input for the password (basic authorization).
542 * When (hasFocus), the button to toggle password visibility is shown.
544 * When (!hasFocus), the button is made invisible and the password is hidden.
546 * @param passwordInput TextView with the password input field receiving the change of focus.
547 * @param hasFocus 'True' if focus is received, 'false' if is lost
549 private void onPasswordFocusChanged(TextView passwordInput
, boolean hasFocus
) {
551 showViewPasswordButton();
554 hidePasswordButton();
559 private void showViewPasswordButton() {
560 //int drawable = android.R.drawable.ic_menu_view;
561 int drawable
= R
.drawable
.ic_view
;
562 if (isPasswordVisible()) {
563 //drawable = android.R.drawable.ic_secure;
564 drawable
= R
.drawable
.ic_hide
;
566 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable
, 0);
569 private boolean isPasswordVisible() {
570 return ((mPasswordInput
.getInputType() & InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) == InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
573 private void hidePasswordButton() {
574 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
577 private void showPassword() {
578 mPasswordInput
.setInputType(InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
579 showViewPasswordButton();
582 private void hidePassword() {
583 mPasswordInput
.setInputType(InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
);
584 showViewPasswordButton();
589 * Cancels the authenticator activity
591 * IMPORTANT ENTRY POINT 3: Never underestimate the importance of cancellation
593 * This method is bound in the layout/acceoun_setup.xml resource file.
595 * @param view Cancel button
597 public void onCancelClick(View view
) {
598 setResult(RESULT_CANCELED
); // TODO review how is this related to AccountAuthenticator (debugging)
605 * Checks the credentials of the user in the root of the ownCloud server
606 * before creating a new local account.
608 * For basic authorization, a check of existence of the root folder is
611 * For OAuth, starts the flow to get an access token; the credentials test
612 * is postponed until it is available.
614 * IMPORTANT ENTRY POINT 4
616 * @param view OK button
618 public void onOkClick(View view
) {
619 // this check should be unnecessary
620 if (mDiscoveredVersion
== null
|| !mDiscoveredVersion
.isVersionValid() || mHostBaseUrl
== null
|| mHostBaseUrl
.length() == 0) {
621 mServerStatusIcon
= R
.drawable
.common_error
;
622 mServerStatusText
= R
.string
.auth_wtf_reenter_URL
;
624 mOkButton
.setEnabled(false
);
625 Log_OC
.wtf(TAG
, "The user was allowed to click 'connect' to an unchecked server!!");
629 if (mOAuth2Check
.isChecked()) {
630 startOauthorization();
633 checkBasicAuthorization();
639 * Tests the credentials entered by the user performing a check of existence on
640 * the root folder of the ownCloud server.
642 private void checkBasicAuthorization() {
643 /// get the path to the root folder through WebDAV from the version server
644 String webdav_path
= AccountUtils
.getWebdavPath(mDiscoveredVersion
, false
);
646 /// get basic credentials entered by user
647 String username
= mUsernameInput
.getText().toString();
648 String password
= mPasswordInput
.getText().toString();
650 /// be gentle with the user
651 showDialog(DIALOG_LOGIN_PROGRESS
);
653 /// test credentials accessing the root folder
654 mAuthCheckOperation
= new ExistenceCheckOperation("", this, false
);
655 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(mHostBaseUrl
+ webdav_path
), this);
656 client
.setBasicCredentials(username
, password
);
657 mOperationThread
= mAuthCheckOperation
.execute(client
, this, mHandler
);
662 * Starts the OAuth 'grant type' flow to get an access token, with
663 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
665 private void startOauthorization() {
666 // be gentle with the user
667 mAuthStatusIcon
= R
.drawable
.progress_small
;
668 mAuthStatusText
= R
.string
.oauth_login_connection
;
671 // GET AUTHORIZATION request
672 //Uri uri = Uri.parse(getString(R.string.oauth2_url_endpoint_auth));
673 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
674 Uri
.Builder uriBuilder
= uri
.buildUpon();
675 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
));
676 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
));
677 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
));
678 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
));
679 //uriBuilder.appendQueryParameter(OAuth2Constants.KEY_STATE, whateverwewant);
680 uri
= uriBuilder
.build();
681 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
682 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
688 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
690 * Dispatches the operation flow to the right method.
693 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
695 if (operation
instanceof OwnCloudServerCheckOperation
) {
696 onOcServerCheckFinish((OwnCloudServerCheckOperation
) operation
, result
);
698 } else if (operation
instanceof OAuth2GetAccessToken
) {
699 onGetOAuthAccessTokenFinish((OAuth2GetAccessToken
)operation
, result
);
701 } else if (operation
instanceof ExistenceCheckOperation
) {
702 onAuthorizationCheckFinish((ExistenceCheckOperation
)operation
, result
);
709 * Processes the result of the server check performed when the user finishes the enter of the
712 * @param operation Server check performed.
713 * @param result Result of the check.
715 private void onOcServerCheckFinish(OwnCloudServerCheckOperation operation
, RemoteOperationResult result
) {
716 if (operation
.equals(mOcServerChkOperation
)) {
717 /// save result state
718 mServerIsChecked
= true
;
719 mServerIsValid
= result
.isSuccess();
720 mIsSslConn
= (result
.getCode() == ResultCode
.OK_SSL
);
721 mOcServerChkOperation
= null
;
723 /// update status icon and text
724 if (mServerIsValid
) {
729 updateServerStatusIconAndText(result
);
732 /// very special case (TODO: move to a common place for all the remote operations)
733 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
734 mLastSslUntrustedServerResult
= result
;
735 showDialog(DIALOG_SSL_VALIDATOR
);
738 /// retrieve discovered version and normalize server URL
739 mDiscoveredVersion
= operation
.getDiscoveredVersion();
740 mHostBaseUrl
= normalizeUrl(mHostUrlInput
.getText().toString());
742 /// allow or not the user try to access the server
743 mOkButton
.setEnabled(mServerIsValid
);
745 } // else nothing ; only the last check operation is considered;
746 // multiple can be triggered if the user amends a URL before a previous check can be triggered
750 private String
normalizeUrl(String url
) {
751 if (url
!= null
&& url
.length() > 0) {
753 if (!url
.toLowerCase().startsWith("http://") &&
754 !url
.toLowerCase().startsWith("https://")) {
756 url
= "https://" + url
;
758 url
= "http://" + url
;
762 // OC-208: Add suffix remote.php/webdav to normalize (OC-34)
763 url
= trimUrlWebdav(url
);
765 if (url
.endsWith("/")) {
766 url
= url
.substring(0, url
.length() - 1);
770 Log_OC
.d(TAG
, "URL Normalize " + url
);
771 return (url
!= null ? url
: "");
775 private String
trimUrlWebdav(String url
){
776 if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_4_0
)){
777 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_4_0
.length());
778 } else if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_2_0
)){
779 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_2_0
.length());
780 } else if (url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_1_2
)){
781 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_1_2
.length());
783 return (url
!= null ? url
: "");
788 * Chooses the right icon and text to show to the user for the received operation result.
790 * @param result Result of a remote operation performed in this activity
792 private void updateServerStatusIconAndText(RemoteOperationResult result
) {
793 mServerStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
795 switch (result
.getCode()) {
797 mServerStatusIcon
= android
.R
.drawable
.ic_secure
;
798 mServerStatusText
= R
.string
.auth_secure_connection
;
803 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
804 mServerStatusText
= R
.string
.auth_connection_established
;
805 mServerStatusIcon
= R
.drawable
.ic_ok
;
807 mServerStatusText
= R
.string
.auth_nossl_plain_ok_title
;
808 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
812 case NO_NETWORK_CONNECTION
:
813 mServerStatusIcon
= R
.drawable
.no_network
;
814 mServerStatusText
= R
.string
.auth_no_net_conn_title
;
817 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
818 mServerStatusText
= R
.string
.auth_ssl_unverified_server_title
;
821 mServerStatusText
= R
.string
.auth_bad_oc_version_title
;
823 case WRONG_CONNECTION
:
824 mServerStatusText
= R
.string
.auth_wrong_connection_title
;
827 mServerStatusText
= R
.string
.auth_timeout_title
;
829 case INCORRECT_ADDRESS
:
830 mServerStatusText
= R
.string
.auth_incorrect_address_title
;
833 mServerStatusText
= R
.string
.auth_ssl_general_error_title
;
836 mServerStatusText
= R
.string
.auth_unauthorized
;
838 case HOST_NOT_AVAILABLE
:
839 mServerStatusText
= R
.string
.auth_unknown_host_title
;
841 case INSTANCE_NOT_CONFIGURED
:
842 mServerStatusText
= R
.string
.auth_not_configured_title
;
845 mServerStatusText
= R
.string
.auth_incorrect_path_title
;
848 mServerStatusText
= R
.string
.auth_oauth_error
;
850 case OAUTH2_ERROR_ACCESS_DENIED
:
851 mServerStatusText
= R
.string
.auth_oauth_error_access_denied
;
853 case UNHANDLED_HTTP_CODE
:
855 mServerStatusText
= R
.string
.auth_unknown_error_title
;
858 mServerStatusText
= 0;
859 mServerStatusIcon
= 0;
865 * Chooses the right icon and text to show to the user for the received operation result.
867 * @param result Result of a remote operation performed in this activity
869 private void updateAuthStatusIconAndText(RemoteOperationResult result
) {
870 mAuthStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
872 switch (result
.getCode()) {
874 mAuthStatusIcon
= android
.R
.drawable
.ic_secure
;
875 mAuthStatusText
= R
.string
.auth_secure_connection
;
880 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
881 mAuthStatusText
= R
.string
.auth_connection_established
;
882 mAuthStatusIcon
= R
.drawable
.ic_ok
;
884 mAuthStatusText
= R
.string
.auth_nossl_plain_ok_title
;
885 mAuthStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
889 case NO_NETWORK_CONNECTION
:
890 mAuthStatusIcon
= R
.drawable
.no_network
;
891 mAuthStatusText
= R
.string
.auth_no_net_conn_title
;
894 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
895 mAuthStatusText
= R
.string
.auth_ssl_unverified_server_title
;
898 mAuthStatusText
= R
.string
.auth_bad_oc_version_title
;
900 case WRONG_CONNECTION
:
901 mAuthStatusText
= R
.string
.auth_wrong_connection_title
;
904 mAuthStatusText
= R
.string
.auth_timeout_title
;
906 case INCORRECT_ADDRESS
:
907 mAuthStatusText
= R
.string
.auth_incorrect_address_title
;
910 mAuthStatusText
= R
.string
.auth_ssl_general_error_title
;
913 mAuthStatusText
= R
.string
.auth_unauthorized
;
915 case HOST_NOT_AVAILABLE
:
916 mAuthStatusText
= R
.string
.auth_unknown_host_title
;
918 case INSTANCE_NOT_CONFIGURED
:
919 mAuthStatusText
= R
.string
.auth_not_configured_title
;
922 mAuthStatusText
= R
.string
.auth_incorrect_path_title
;
925 mAuthStatusText
= R
.string
.auth_oauth_error
;
927 case OAUTH2_ERROR_ACCESS_DENIED
:
928 mAuthStatusText
= R
.string
.auth_oauth_error_access_denied
;
930 case UNHANDLED_HTTP_CODE
:
932 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
942 * Processes the result of the request for and access token send
943 * to an OAuth authorization server.
945 * @param operation Operation performed requesting the access token.
946 * @param result Result of the operation.
948 private void onGetOAuthAccessTokenFinish(OAuth2GetAccessToken operation
, RemoteOperationResult result
) {
950 dismissDialog(DIALOG_OAUTH2_LOGIN_PROGRESS
);
951 } catch (IllegalArgumentException e
) {
952 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
955 String webdav_path
= AccountUtils
.getWebdavPath(mDiscoveredVersion
, true
);
956 if (result
.isSuccess() && webdav_path
!= null
) {
957 /// be gentle with the user
958 showDialog(DIALOG_LOGIN_PROGRESS
);
960 /// time to test the retrieved access token on the ownCloud server
961 mOAuthAccessToken
= ((OAuth2GetAccessToken
)operation
).getResultTokenMap().get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
962 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mOAuthAccessToken
);
963 mAuthCheckOperation
= new ExistenceCheckOperation("", this, false
);
964 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(mHostBaseUrl
+ webdav_path
), this);
965 client
.setBearerCredentials(mOAuthAccessToken
);
966 mAuthCheckOperation
.execute(client
, this, mHandler
);
969 updateAuthStatusIconAndText(result
);
971 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
977 * Processes the result of the access check performed to try the user credentials.
979 * Creates a new account through the AccountManager.
981 * @param operation Access check performed.
982 * @param result Result of the operation.
984 private void onAuthorizationCheckFinish(ExistenceCheckOperation operation
, RemoteOperationResult result
) {
986 dismissDialog(DIALOG_LOGIN_PROGRESS
);
987 } catch (IllegalArgumentException e
) {
988 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
991 if (result
.isSuccess()) {
992 Log_OC
.d(TAG
, "Successful access - time to save the account");
994 if (mAction
== ACTION_CREATE
) {
1003 } else if (result
.isServerFail() || result
.isException()) {
1004 /// if server fail or exception in authorization, the UI is updated as when a server check failed
1005 mServerIsChecked
= true
;
1006 mServerIsValid
= false
;
1008 mOcServerChkOperation
= null
;
1009 mDiscoveredVersion
= null
;
1010 mHostBaseUrl
= normalizeUrl(mHostUrlInput
.getText().toString());
1012 // update status icon and text
1013 updateServerStatusIconAndText(result
);
1015 mAuthStatusIcon
= 0;
1016 mAuthStatusText
= 0;
1019 // update input controls state
1020 showRefreshButton();
1021 mOkButton
.setEnabled(false
);
1023 // very special case (TODO: move to a common place for all the remote operations) (dangerous here?)
1024 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1025 mLastSslUntrustedServerResult
= result
;
1026 showDialog(DIALOG_SSL_VALIDATOR
);
1029 } else { // authorization fail due to client side - probably wrong credentials
1030 updateAuthStatusIconAndText(result
);
1032 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1038 * Sets the proper response to get that the Account Authenticator that started this activity saves
1039 * a new authorization token for mAccount.
1041 private void updateToken() {
1042 Bundle response
= new Bundle();
1043 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1044 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
1045 boolean isOAuth
= mOAuth2Check
.isChecked();
1047 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mOAuthAccessToken
);
1048 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1049 mAccountMgr
.setAuthToken(mAccount
, AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
, mOAuthAccessToken
);
1051 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
1052 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
1054 setAccountAuthenticatorResult(response
);
1059 * Creates a new account through the Account Authenticator that started this activity.
1061 * This makes the account permanent.
1063 * TODO Decide how to name the OAuth accounts
1065 private void createAccount() {
1066 /// create and save new ownCloud account
1067 boolean isOAuth
= mOAuth2Check
.isChecked();
1069 Uri uri
= Uri
.parse(mHostBaseUrl
);
1070 String username
= mUsernameInput
.getText().toString().trim();
1072 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1074 String accountName
= username
+ "@" + uri
.getHost();
1075 if (uri
.getPort() >= 0) {
1076 accountName
+= ":" + uri
.getPort();
1078 mAccount
= new Account(accountName
, AccountAuthenticator
.ACCOUNT_TYPE
);
1080 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
); // with our implementation, the password is never input in the app
1082 mAccountMgr
.addAccountExplicitly(mAccount
, mPasswordInput
.getText().toString(), null
);
1085 /// add the new account as default in preferences, if there is none already
1086 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1087 if (defaultAccount
== null
) {
1088 SharedPreferences
.Editor editor
= PreferenceManager
1089 .getDefaultSharedPreferences(this).edit();
1090 editor
.putString("select_oc_account", accountName
);
1094 /// prepare result to return to the Authenticator
1095 // TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done
1096 final Intent intent
= new Intent();
1097 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, AccountAuthenticator
.ACCOUNT_TYPE
);
1098 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1100 intent
.putExtra(AccountManager
.KEY_AUTHTOKEN
, AccountAuthenticator
.ACCOUNT_TYPE
); // TODO check this; not sure it's right; maybe
1101 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1103 mAccountMgr
.setAuthToken(mAccount
, AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
, mOAuthAccessToken
);
1105 /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
1106 mAccountMgr
.setUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
, mDiscoveredVersion
.toString());
1107 mAccountMgr
.setUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
, mHostBaseUrl
);
1109 mAccountMgr
.setUserData(mAccount
, AccountAuthenticator
.KEY_SUPPORTS_OAUTH2
, "TRUE"); // TODO this flag should be unnecessary
1111 setAccountAuthenticatorResult(intent
.getExtras());
1112 setResult(RESULT_OK
, intent
);
1114 /// immediately request for the synchronization of the new account
1115 Bundle bundle
= new Bundle();
1116 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
1117 ContentResolver
.requestSync(mAccount
, AccountAuthenticator
.AUTHORITY
, bundle
);
1124 * Necessary to update the contents of the SSL Dialog
1126 * TODO move to some common place for all possible untrusted SSL failures
1129 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
1131 case DIALOG_LOGIN_PROGRESS
:
1132 case DIALOG_CERT_NOT_SAVED
:
1133 case DIALOG_OAUTH2_LOGIN_PROGRESS
:
1135 case DIALOG_SSL_VALIDATOR
: {
1136 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
1140 Log_OC
.e(TAG
, "Incorrect dialog called with id = " + id
);
1149 protected Dialog
onCreateDialog(int id
) {
1150 Dialog dialog
= null
;
1152 case DIALOG_LOGIN_PROGRESS
: {
1153 /// simple progress dialog
1154 ProgressDialog working_dialog
= new ProgressDialog(this);
1155 working_dialog
.setMessage(getResources().getString(R
.string
.auth_trying_to_login
));
1156 working_dialog
.setIndeterminate(true
);
1157 working_dialog
.setCancelable(true
);
1159 .setOnCancelListener(new DialogInterface
.OnCancelListener() {
1161 public void onCancel(DialogInterface dialog
) {
1162 /// TODO study if this is enough
1163 Log_OC
.i(TAG
, "Login canceled");
1164 if (mOperationThread
!= null
) {
1165 mOperationThread
.interrupt();
1170 dialog
= working_dialog
;
1173 case DIALOG_OAUTH2_LOGIN_PROGRESS
: {
1174 ProgressDialog working_dialog
= new ProgressDialog(this);
1175 working_dialog
.setMessage(String
.format("Getting authorization"));
1176 working_dialog
.setIndeterminate(true
);
1177 working_dialog
.setCancelable(true
);
1179 .setOnCancelListener(new DialogInterface
.OnCancelListener() {
1181 public void onCancel(DialogInterface dialog
) {
1182 Log_OC
.i(TAG
, "Login canceled");
1186 dialog
= working_dialog
;
1189 case DIALOG_SSL_VALIDATOR
: {
1190 /// TODO start to use new dialog interface, at least for this (it is a FragmentDialog already)
1191 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
1194 case DIALOG_CERT_NOT_SAVED
: {
1195 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
1196 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
1197 builder
.setCancelable(false
);
1198 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
1200 public void onClick(DialogInterface dialog
, int which
) {
1204 dialog
= builder
.create();
1208 Log_OC
.e(TAG
, "Incorrect dialog called with id = " + id
);
1215 * Starts and activity to open the 'new account' page in the ownCloud web site
1217 * @param view 'Account register' button
1219 public void onRegisterClick(View view
) {
1220 Intent register
= new Intent(Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.url_account_register
)));
1221 setResult(RESULT_CANCELED
);
1222 startActivity(register
);
1227 * Updates the content and visibility state of the icon and text associated
1228 * to the last check on the ownCloud server.
1230 private void showServerStatus() {
1231 TextView tv
= (TextView
) findViewById(R
.id
.server_status_text
);
1233 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1234 tv
.setVisibility(View
.INVISIBLE
);
1237 tv
.setText(mServerStatusText
);
1238 tv
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1239 tv
.setVisibility(View
.VISIBLE
);
1246 * Updates the content and visibility state of the icon and text associated
1247 * to the interactions with the OAuth authorization server.
1249 private void showAuthStatus() {
1250 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1251 mAuthStatusLayout
.setVisibility(View
.INVISIBLE
);
1254 mAuthStatusLayout
.setText(mAuthStatusText
);
1255 mAuthStatusLayout
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1256 mAuthStatusLayout
.setVisibility(View
.VISIBLE
);
1261 private void showRefreshButton() {
1262 mRefreshButton
.setVisibility(View
.VISIBLE
);
1265 private void hideRefreshButton() {
1266 mRefreshButton
.setVisibility(View
.GONE
);
1270 * Called when the refresh button in the input field for ownCloud host is clicked.
1272 * Performs a new check on the URL in the input field.
1274 * @param view Refresh 'button'
1276 public void onRefreshClick(View view
) {
1282 * Called when the eye icon in the password field is clicked.
1284 * Toggles the visibility of the password in the field.
1286 public void onViewPasswordClick() {
1287 int selectionStart
= mPasswordInput
.getSelectionStart();
1288 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1289 if (isPasswordVisible()) {
1294 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1299 * Called when the checkbox for OAuth authorization is clicked.
1301 * Hides or shows the input fields for user & password.
1303 * @param view 'View password' 'button'
1305 public void onCheckClick(View view
) {
1306 CheckBox oAuth2Check
= (CheckBox
)view
;
1307 if (oAuth2Check
.isChecked()) {
1308 mCurrentAuthorizationMethod
= AUTH_METHOD_OAUTH2
;
1310 mCurrentAuthorizationMethod
= AUTH_METHOD_BASIC_HTTP
;
1312 adaptViewAccordingToAuthenticationMethod();
1317 * Changes the visibility of input elements depending on
1318 * the current authorization method.
1320 private void adaptViewAccordingToAuthenticationMethod () {
1321 switch (mCurrentAuthorizationMethod
) {
1322 case AUTH_METHOD_OAUTH2
:
1323 // OAuth 2 authorization
1324 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
1325 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
1326 mUsernameInput
.setVisibility(View
.GONE
);
1327 mPasswordInput
.setVisibility(View
.GONE
);
1328 mAccountNameInput
.setVisibility(View
.GONE
);
1329 mWebSsoView
.setVisibility(View
.GONE
);
1332 case AUTH_METHOD_SAML_WEB_SSO
:
1333 // SAML-based web Single Sign On
1334 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
1335 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
1336 mUsernameInput
.setVisibility(View
.GONE
);
1337 mPasswordInput
.setVisibility(View
.GONE
);
1338 mAccountNameInput
.setVisibility(View
.VISIBLE
);
1339 mWebSsoView
.setVisibility(View
.VISIBLE
);
1342 case AUTH_METHOD_BASIC_HTTP
:
1344 // basic HTTP authorization
1345 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
1346 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
1347 mUsernameInput
.setVisibility(View
.VISIBLE
);
1348 mPasswordInput
.setVisibility(View
.VISIBLE
);
1349 mAccountNameInput
.setVisibility(View
.GONE
);
1350 mWebSsoView
.setVisibility(View
.GONE
);
1355 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1357 public void onSavedCertificate() {
1362 * Called from SslValidatorDialog when a new server certificate could not be saved
1363 * when the user requested it.
1366 public void onFailedSavingCertificate() {
1367 showDialog(DIALOG_CERT_NOT_SAVED
);
1372 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1374 * Used to trigger the authorization check when the user presses 'enter' after writing the password.
1377 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1378 if (inputField
!= null
&& inputField
.equals(mPasswordInput
) &&
1379 actionId
== EditorInfo
.IME_ACTION_DONE
) {
1380 if (mOkButton
.isEnabled()) {
1381 mOkButton
.performClick();
1384 return false
; // always return false to grant that the software keyboard is hidden anyway
1388 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1390 private int fuzz
= 75;
1396 public boolean onTouch(View view
, MotionEvent event
) {
1397 Drawable rightDrawable
= null
;
1398 if (view
instanceof TextView
) {
1399 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1400 if (drawables
.length
> 2) {
1401 rightDrawable
= drawables
[2];
1404 if (rightDrawable
!= null
) {
1405 final int x
= (int) event
.getX();
1406 final int y
= (int) event
.getY();
1407 final Rect bounds
= rightDrawable
.getBounds();
1408 if (x
>= (view
.getRight() - bounds
.width() - fuzz
) && x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
)
1409 && y
>= (view
.getPaddingTop() - fuzz
) && y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1411 return onDrawableTouch(event
);
1417 public abstract boolean onDrawableTouch(final MotionEvent event
);