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
.widget
.CheckBox
;
61 import android
.widget
.EditText
;
62 import android
.widget
.Button
;
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_SERVER_VALID
= "SERVER_VALID";
91 private static final String KEY_SERVER_CHECKED
= "SERVER_CHECKED";
92 private static final String KEY_SERVER_CHECK_IN_PROGRESS
= "SERVER_CHECK_IN_PROGRESS";
93 private static final String KEY_SERVER_STATUS_TEXT
= "SERVER_STATUS_TEXT";
94 private static final String KEY_SERVER_STATUS_ICON
= "SERVER_STATUS_ICON";
95 private static final String KEY_IS_SSL_CONN
= "IS_SSL_CONN";
96 private static final String KEY_PASSWORD_VISIBLE
= "PASSWORD_VISIBLE";
97 private static final String KEY_AUTH_STATUS_TEXT
= "AUTH_STATUS_TEXT";
98 private static final String KEY_AUTH_STATUS_ICON
= "AUTH_STATUS_ICON";
99 private static final String KEY_REFRESH_BUTTON_ENABLED
= "KEY_REFRESH_BUTTON_ENABLED";
101 private static final String OAUTH_MODE_ON
= "on";
102 private static final String OAUTH_MODE_OFF
= "off";
103 private static final String OAUTH_MODE_OPTIONAL
= "optional";
105 private static final int DIALOG_LOGIN_PROGRESS
= 0;
106 private static final int DIALOG_SSL_VALIDATOR
= 1;
107 private static final int DIALOG_CERT_NOT_SAVED
= 2;
108 private static final int DIALOG_OAUTH2_LOGIN_PROGRESS
= 3;
110 public static final byte ACTION_CREATE
= 0;
111 public static final byte ACTION_UPDATE_TOKEN
= 1;
113 private String mHostBaseUrl
;
114 private OwnCloudVersion mDiscoveredVersion
;
116 private int mServerStatusText
, mServerStatusIcon
;
117 private boolean mServerIsChecked
, mServerIsValid
, mIsSslConn
;
118 private int mAuthStatusText
, mAuthStatusIcon
;
120 private final Handler mHandler
= new Handler();
121 private Thread mOperationThread
;
122 private OwnCloudServerCheckOperation mOcServerChkOperation
;
123 private ExistenceCheckOperation mAuthCheckOperation
;
124 private RemoteOperationResult mLastSslUntrustedServerResult
;
126 private Uri mNewCapturedUriFromOAuth2Redirection
;
128 private AccountManager mAccountMgr
;
129 private boolean mJustCreated
;
130 private byte mAction
;
131 private Account mAccount
;
133 private EditText mHostUrlInput
;
134 private EditText mUsernameInput
;
135 private EditText mPasswordInput
;
136 private CheckBox mOAuth2Check
;
137 private String mOAuthAccessToken
;
138 private View mOkButton
;
139 private TextView mAuthStatusLayout
;
141 private TextView mOAuthAuthEndpointText
;
142 private TextView mOAuthTokenEndpointText
;
144 private boolean mRefreshButtonEnabled
;
150 * IMPORTANT ENTRY POINT 1: activity is shown to the user
153 protected void onCreate(Bundle savedInstanceState
) {
154 super.onCreate(savedInstanceState
);
155 getWindow().requestFeature(Window
.FEATURE_NO_TITLE
);
157 /// set view and get references to view elements
158 setContentView(R
.layout
.account_setup
);
159 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
160 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
161 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
162 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
163 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
164 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
165 mOkButton
= findViewById(R
.id
.buttonOK
);
166 mAuthStatusLayout
= (TextView
) findViewById(R
.id
.auth_status_text
);
168 /// complete label for 'register account' button
169 Button b
= (Button
) findViewById(R
.id
.account_register
);
171 b
.setText(String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
175 mAccountMgr
= AccountManager
.get(this);
176 mNewCapturedUriFromOAuth2Redirection
= null
;
177 mAction
= getIntent().getByteExtra(EXTRA_ACTION
, ACTION_CREATE
);
181 if (savedInstanceState
== null
) {
182 /// connection state and info
183 mServerStatusText
= mServerStatusIcon
= 0;
184 mServerIsValid
= false
;
185 mServerIsChecked
= false
;
187 mAuthStatusText
= mAuthStatusIcon
= 0;
189 /// retrieve extras from intent
190 String tokenType
= getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
191 boolean oAuthRequired
= AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
.equals(tokenType
) || OAUTH_MODE_ON
.equals(getString(R
.string
.oauth2_mode
));
193 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
194 if (mAccount
!= null
) {
195 String ocVersion
= mAccountMgr
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
);
196 if (ocVersion
!= null
) {
197 mDiscoveredVersion
= new OwnCloudVersion(ocVersion
);
199 mHostBaseUrl
= normalizeUrl(mAccountMgr
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
));
200 mHostUrlInput
.setText(mHostBaseUrl
);
201 String userName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
202 mUsernameInput
.setText(userName
);
203 oAuthRequired
= (mAccountMgr
.getUserData(mAccount
, AccountAuthenticator
.KEY_SUPPORTS_OAUTH2
) != null
);
205 mOAuth2Check
.setChecked(oAuthRequired
);
206 changeViewByOAuth2Check(oAuthRequired
);
210 /// connection state and info
211 mServerIsValid
= savedInstanceState
.getBoolean(KEY_SERVER_VALID
);
212 mServerIsChecked
= savedInstanceState
.getBoolean(KEY_SERVER_CHECKED
);
213 mServerStatusText
= savedInstanceState
.getInt(KEY_SERVER_STATUS_TEXT
);
214 mServerStatusIcon
= savedInstanceState
.getInt(KEY_SERVER_STATUS_ICON
);
215 mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
216 mAuthStatusText
= savedInstanceState
.getInt(KEY_AUTH_STATUS_TEXT
);
217 mAuthStatusIcon
= savedInstanceState
.getInt(KEY_AUTH_STATUS_ICON
);
218 if (savedInstanceState
.getBoolean(KEY_PASSWORD_VISIBLE
, false
)) {
223 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
224 if (ocVersion
!= null
) {
225 mDiscoveredVersion
= new OwnCloudVersion(ocVersion
);
227 mHostBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
229 // account data, if updating
230 mAccount
= savedInstanceState
.getParcelable(KEY_ACCOUNT
);
232 // check if server check was interrupted by a configuration change
233 if (savedInstanceState
.getBoolean(KEY_SERVER_CHECK_IN_PROGRESS
, false
)) {
237 // refresh button enabled
238 mRefreshButtonEnabled
= savedInstanceState
.getBoolean(KEY_REFRESH_BUTTON_ENABLED
);
244 if (mServerIsChecked
&& !mServerIsValid
&& mRefreshButtonEnabled
) showRefreshButton();
245 mOkButton
.setEnabled(mServerIsValid
); // state not automatically recovered in configuration changes
247 if (!OAUTH_MODE_OPTIONAL
.equals(getString(R
.string
.oauth2_mode
))) {
248 mOAuth2Check
.setVisibility(View
.GONE
);
251 if (mAction
== ACTION_UPDATE_TOKEN
) {
252 /// lock things that should not change
253 mHostUrlInput
.setEnabled(false
);
254 mUsernameInput
.setEnabled(false
);
255 mOAuth2Check
.setVisibility(View
.GONE
);
256 if (!mServerIsValid
&& mOcServerChkOperation
== null
) {
261 mPasswordInput
.setText(""); // clean password to avoid social hacking (disadvantage: password in removed if the device is turned aside)
264 /// bind view elements to listeners
265 mHostUrlInput
.setOnFocusChangeListener(this);
266 mHostUrlInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
268 public boolean onDrawableTouch(final MotionEvent event
) {
269 if (event
.getAction() == MotionEvent
.ACTION_UP
) {
270 AuthenticatorActivity
.this.onRefreshClick();
275 mHostUrlInput
.addTextChangedListener(new TextWatcher() {
278 public void afterTextChanged(Editable s
) {
279 if (!mHostBaseUrl
.equals(normalizeUrl(mHostUrlInput
.getText().toString()))) {
280 mOkButton
.setEnabled(false
);
285 public void beforeTextChanged(CharSequence s
, int start
, int count
, int after
) {}
288 public void onTextChanged(CharSequence s
, int start
, int before
, int count
) {}
291 mPasswordInput
.setOnFocusChangeListener(this);
292 mPasswordInput
.setImeOptions(EditorInfo
.IME_ACTION_DONE
);
293 mPasswordInput
.setOnEditorActionListener(this);
294 mPasswordInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
296 public boolean onDrawableTouch(final MotionEvent event
) {
297 if (event
.getAction() == MotionEvent
.ACTION_UP
) {
298 AuthenticatorActivity
.this.onViewPasswordClick();
306 * Saves relevant state before {@link #onPause()}
308 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag, intended to defer the
309 * processing of the redirection caught in {@link #onNewIntent(Intent)} until {@link #onResume()}
311 * See {@link #loadSavedInstanceState(Bundle)}
314 protected void onSaveInstanceState(Bundle outState
) {
315 super.onSaveInstanceState(outState
);
317 /// connection state and info
318 outState
.putInt(KEY_SERVER_STATUS_TEXT
, mServerStatusText
);
319 outState
.putInt(KEY_SERVER_STATUS_ICON
, mServerStatusIcon
);
320 outState
.putBoolean(KEY_SERVER_VALID
, mServerIsValid
);
321 outState
.putBoolean(KEY_SERVER_CHECKED
, mServerIsChecked
);
322 outState
.putBoolean(KEY_SERVER_CHECK_IN_PROGRESS
, (!mServerIsValid
&& mOcServerChkOperation
!= null
));
323 outState
.putBoolean(KEY_IS_SSL_CONN
, mIsSslConn
);
324 outState
.putBoolean(KEY_PASSWORD_VISIBLE
, isPasswordVisible());
325 outState
.putInt(KEY_AUTH_STATUS_ICON
, mAuthStatusIcon
);
326 outState
.putInt(KEY_AUTH_STATUS_TEXT
, mAuthStatusText
);
329 if (mDiscoveredVersion
!= null
) {
330 outState
.putString(KEY_OC_VERSION
, mDiscoveredVersion
.toString());
332 outState
.putString(KEY_HOST_URL_TEXT
, mHostBaseUrl
);
334 /// account data, if updating
335 if (mAccount
!= null
) {
336 outState
.putParcelable(KEY_ACCOUNT
, mAccount
);
339 // refresh button enabled
340 outState
.putBoolean(KEY_REFRESH_BUTTON_ENABLED
, mRefreshButtonEnabled
);
346 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION request
349 * To make this possible, this activity needs to be qualified with android:launchMode = "singleTask" in the
350 * AndroidManifest.xml file.
353 protected void onNewIntent (Intent intent
) {
354 Log_OC
.d(TAG
, "onNewIntent()");
355 Uri data
= intent
.getData();
356 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
357 mNewCapturedUriFromOAuth2Redirection
= data
;
363 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION, and
364 * deferred in {@link #onNewIntent(Intent)}, is processed here.
367 protected void onResume() {
369 // the state of mOAuth2Check is automatically recovered between configuration changes, but not before onCreate() finishes; so keep the next lines here
370 changeViewByOAuth2Check(mOAuth2Check
.isChecked());
371 if (mAction
== ACTION_UPDATE_TOKEN
&& mJustCreated
) {
372 if (mOAuth2Check
.isChecked())
373 Toast
.makeText(this, R
.string
.auth_expired_oauth_token_toast
, Toast
.LENGTH_LONG
).show();
375 Toast
.makeText(this, R
.string
.auth_expired_basic_auth_toast
, Toast
.LENGTH_LONG
).show();
378 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
379 getOAuth2AccessTokenFromCapturedRedirection();
382 mJustCreated
= false
;
387 * Parses the redirection with the response to the GET AUTHORIZATION request to the
388 * oAuth server and requests for the access token (GET ACCESS TOKEN)
390 private void getOAuth2AccessTokenFromCapturedRedirection() {
391 /// Parse data from OAuth redirection
392 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
393 mNewCapturedUriFromOAuth2Redirection
= null
;
395 /// Showing the dialog with instructions for the user.
396 showDialog(DIALOG_OAUTH2_LOGIN_PROGRESS
);
398 /// GET ACCESS TOKEN to the oAuth server
399 RemoteOperation operation
= new OAuth2GetAccessToken( getString(R
.string
.oauth2_client_id
),
400 getString(R
.string
.oauth2_redirect_uri
),
401 getString(R
.string
.oauth2_grant_type
),
403 //WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(getString(R.string.oauth2_url_endpoint_access)), getApplicationContext());
404 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(mOAuthTokenEndpointText
.getText().toString().trim()), getApplicationContext());
405 operation
.execute(client
, this, mHandler
);
411 * Handles the change of focus on the text inputs for the server URL and the password
413 public void onFocusChange(View view
, boolean hasFocus
) {
414 if (view
.getId() == R
.id
.hostUrlInput
) {
416 onUrlInputFocusLost((TextView
) view
);
417 if (!mServerIsValid
) {
425 } else if (view
.getId() == R
.id
.account_password
) {
426 onPasswordFocusChanged((TextView
) view
, hasFocus
);
432 * Handles changes in focus on the text input for the server URL.
434 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
435 * other field. The operation to check the existence of the server in the entered URL is
438 * When hasFocus: user 'comes back' to write again the server URL.
440 * @param hostInput TextView with the URL input field receiving the change of focus.
442 private void onUrlInputFocusLost(TextView hostInput
) {
443 if (!mHostBaseUrl
.equals(normalizeUrl(mHostUrlInput
.getText().toString()))) {
446 mOkButton
.setEnabled(mServerIsValid
);
451 private void checkOcServer() {
452 String uri
= trimUrlWebdav(mHostUrlInput
.getText().toString().trim());
453 mServerIsValid
= false
;
454 mServerIsChecked
= false
;
455 mOkButton
.setEnabled(false
);
456 mDiscoveredVersion
= null
;
458 if (uri
.length() != 0) {
459 mServerStatusText
= R
.string
.auth_testing_connection
;
460 mServerStatusIcon
= R
.drawable
.progress_small
;
462 mOcServerChkOperation
= new OwnCloudServerCheckOperation(uri
, this);
463 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(uri
), this);
464 mOperationThread
= mOcServerChkOperation
.execute(client
, this, mHandler
);
466 mServerStatusText
= 0;
467 mServerStatusIcon
= 0;
474 * Handles changes in focus on the text input for the password (basic authorization).
476 * When (hasFocus), the button to toggle password visibility is shown.
478 * When (!hasFocus), the button is made invisible and the password is hidden.
480 * @param passwordInput TextView with the password input field receiving the change of focus.
481 * @param hasFocus 'True' if focus is received, 'false' if is lost
483 private void onPasswordFocusChanged(TextView passwordInput
, boolean hasFocus
) {
485 showViewPasswordButton();
488 hidePasswordButton();
493 private void showViewPasswordButton() {
494 //int drawable = android.R.drawable.ic_menu_view;
495 int drawable
= R
.drawable
.ic_view
;
496 if (isPasswordVisible()) {
497 //drawable = android.R.drawable.ic_secure;
498 drawable
= R
.drawable
.ic_hide
;
500 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable
, 0);
503 private boolean isPasswordVisible() {
504 return ((mPasswordInput
.getInputType() & InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) == InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
507 private void hidePasswordButton() {
508 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
511 private void showPassword() {
512 mPasswordInput
.setInputType(InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
513 showViewPasswordButton();
516 private void hidePassword() {
517 mPasswordInput
.setInputType(InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
);
518 showViewPasswordButton();
523 * Cancels the authenticator activity
525 * IMPORTANT ENTRY POINT 3: Never underestimate the importance of cancellation
527 * This method is bound in the layout/acceoun_setup.xml resource file.
529 * @param view Cancel button
531 public void onCancelClick(View view
) {
532 setResult(RESULT_CANCELED
); // TODO review how is this related to AccountAuthenticator (debugging)
539 * Checks the credentials of the user in the root of the ownCloud server
540 * before creating a new local account.
542 * For basic authorization, a check of existence of the root folder is
545 * For OAuth, starts the flow to get an access token; the credentials test
546 * is postponed until it is available.
548 * IMPORTANT ENTRY POINT 4
550 * @param view OK button
552 public void onOkClick(View view
) {
553 // this check should be unnecessary
554 if (mDiscoveredVersion
== null
|| !mDiscoveredVersion
.isVersionValid() || mHostBaseUrl
== null
|| mHostBaseUrl
.length() == 0) {
555 mServerStatusIcon
= R
.drawable
.common_error
;
556 mServerStatusText
= R
.string
.auth_wtf_reenter_URL
;
558 mOkButton
.setEnabled(false
);
559 Log_OC
.wtf(TAG
, "The user was allowed to click 'connect' to an unchecked server!!");
563 if (mOAuth2Check
.isChecked()) {
564 startOauthorization();
567 checkBasicAuthorization();
573 * Tests the credentials entered by the user performing a check of existence on
574 * the root folder of the ownCloud server.
576 private void checkBasicAuthorization() {
577 /// get the path to the root folder through WebDAV from the version server
578 String webdav_path
= AccountUtils
.getWebdavPath(mDiscoveredVersion
, false
);
580 /// get basic credentials entered by user
581 String username
= mUsernameInput
.getText().toString();
582 String password
= mPasswordInput
.getText().toString();
584 /// be gentle with the user
585 showDialog(DIALOG_LOGIN_PROGRESS
);
587 /// test credentials accessing the root folder
588 mAuthCheckOperation
= new ExistenceCheckOperation("", this, false
);
589 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(mHostBaseUrl
+ webdav_path
), this);
590 client
.setBasicCredentials(username
, password
);
591 mOperationThread
= mAuthCheckOperation
.execute(client
, this, mHandler
);
596 * Starts the OAuth 'grant type' flow to get an access token, with
597 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
599 private void startOauthorization() {
600 // be gentle with the user
601 mAuthStatusIcon
= R
.drawable
.progress_small
;
602 mAuthStatusText
= R
.string
.oauth_login_connection
;
605 // GET AUTHORIZATION request
606 //Uri uri = Uri.parse(getString(R.string.oauth2_url_endpoint_auth));
607 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
608 Uri
.Builder uriBuilder
= uri
.buildUpon();
609 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
));
610 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
));
611 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
));
612 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
));
613 //uriBuilder.appendQueryParameter(OAuth2Constants.KEY_STATE, whateverwewant);
614 uri
= uriBuilder
.build();
615 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
616 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
622 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
624 * Dispatches the operation flow to the right method.
627 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
629 if (operation
instanceof OwnCloudServerCheckOperation
) {
630 onOcServerCheckFinish((OwnCloudServerCheckOperation
) operation
, result
);
632 } else if (operation
instanceof OAuth2GetAccessToken
) {
633 onGetOAuthAccessTokenFinish((OAuth2GetAccessToken
)operation
, result
);
635 } else if (operation
instanceof ExistenceCheckOperation
) {
636 onAuthorizationCheckFinish((ExistenceCheckOperation
)operation
, result
);
643 * Processes the result of the server check performed when the user finishes the enter of the
646 * @param operation Server check performed.
647 * @param result Result of the check.
649 private void onOcServerCheckFinish(OwnCloudServerCheckOperation operation
, RemoteOperationResult result
) {
650 if (operation
.equals(mOcServerChkOperation
)) {
651 /// save result state
652 mServerIsChecked
= true
;
653 mServerIsValid
= result
.isSuccess();
654 mIsSslConn
= (result
.getCode() == ResultCode
.OK_SSL
);
655 mOcServerChkOperation
= null
;
657 /// update status icon and text
658 if (mServerIsValid
) {
663 updateServerStatusIconAndText(result
);
666 /// very special case (TODO: move to a common place for all the remote operations)
667 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
668 mLastSslUntrustedServerResult
= result
;
669 showDialog(DIALOG_SSL_VALIDATOR
);
672 /// retrieve discovered version and normalize server URL
673 mDiscoveredVersion
= operation
.getDiscoveredVersion();
674 mHostBaseUrl
= normalizeUrl(mHostUrlInput
.getText().toString());
676 /// allow or not the user try to access the server
677 mOkButton
.setEnabled(mServerIsValid
);
679 } // else nothing ; only the last check operation is considered;
680 // multiple can be triggered if the user amends a URL before a previous check can be triggered
684 private String
normalizeUrl(String url
) {
685 if (url
!= null
&& url
.length() > 0) {
687 if (!url
.toLowerCase().startsWith("http://") &&
688 !url
.toLowerCase().startsWith("https://")) {
690 url
= "https://" + url
;
692 url
= "http://" + url
;
696 // OC-208: Add suffix remote.php/webdav to normalize (OC-34)
697 url
= trimUrlWebdav(url
);
699 if (url
.endsWith("/")) {
700 url
= url
.substring(0, url
.length() - 1);
704 Log_OC
.d(TAG
, "URL Normalize " + url
);
705 return (url
!= null ? url
: "");
709 private String
trimUrlWebdav(String url
){
710 if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_4_0
)){
711 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_4_0
.length());
712 } else if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_2_0
)){
713 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_2_0
.length());
714 } else if (url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_1_2
)){
715 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_1_2
.length());
717 return (url
!= null ? url
: "");
722 * Chooses the right icon and text to show to the user for the received operation result.
724 * @param result Result of a remote operation performed in this activity
726 private void updateServerStatusIconAndText(RemoteOperationResult result
) {
727 mServerStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
729 switch (result
.getCode()) {
731 mServerStatusIcon
= android
.R
.drawable
.ic_secure
;
732 mServerStatusText
= R
.string
.auth_secure_connection
;
737 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
738 mServerStatusText
= R
.string
.auth_connection_established
;
739 mServerStatusIcon
= R
.drawable
.ic_ok
;
741 mServerStatusText
= R
.string
.auth_nossl_plain_ok_title
;
742 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
746 case NO_NETWORK_CONNECTION
:
747 mServerStatusIcon
= R
.drawable
.no_network
;
748 mServerStatusText
= R
.string
.auth_no_net_conn_title
;
751 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
752 mServerStatusText
= R
.string
.auth_ssl_unverified_server_title
;
755 mServerStatusText
= R
.string
.auth_bad_oc_version_title
;
757 case WRONG_CONNECTION
:
758 mServerStatusText
= R
.string
.auth_wrong_connection_title
;
761 mServerStatusText
= R
.string
.auth_timeout_title
;
763 case INCORRECT_ADDRESS
:
764 mServerStatusText
= R
.string
.auth_incorrect_address_title
;
767 mServerStatusText
= R
.string
.auth_ssl_general_error_title
;
770 mServerStatusText
= R
.string
.auth_unauthorized
;
772 case HOST_NOT_AVAILABLE
:
773 mServerStatusText
= R
.string
.auth_unknown_host_title
;
775 case INSTANCE_NOT_CONFIGURED
:
776 mServerStatusText
= R
.string
.auth_not_configured_title
;
779 mServerStatusText
= R
.string
.auth_incorrect_path_title
;
782 mServerStatusText
= R
.string
.auth_oauth_error
;
784 case OAUTH2_ERROR_ACCESS_DENIED
:
785 mServerStatusText
= R
.string
.auth_oauth_error_access_denied
;
787 case UNHANDLED_HTTP_CODE
:
789 mServerStatusText
= R
.string
.auth_unknown_error_title
;
792 mServerStatusText
= 0;
793 mServerStatusIcon
= 0;
799 * Chooses the right icon and text to show to the user for the received operation result.
801 * @param result Result of a remote operation performed in this activity
803 private void updateAuthStatusIconAndText(RemoteOperationResult result
) {
804 mAuthStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
806 switch (result
.getCode()) {
808 mAuthStatusIcon
= android
.R
.drawable
.ic_secure
;
809 mAuthStatusText
= R
.string
.auth_secure_connection
;
814 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
815 mAuthStatusText
= R
.string
.auth_connection_established
;
816 mAuthStatusIcon
= R
.drawable
.ic_ok
;
818 mAuthStatusText
= R
.string
.auth_nossl_plain_ok_title
;
819 mAuthStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
823 case NO_NETWORK_CONNECTION
:
824 mAuthStatusIcon
= R
.drawable
.no_network
;
825 mAuthStatusText
= R
.string
.auth_no_net_conn_title
;
828 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
829 mAuthStatusText
= R
.string
.auth_ssl_unverified_server_title
;
832 mAuthStatusText
= R
.string
.auth_bad_oc_version_title
;
834 case WRONG_CONNECTION
:
835 mAuthStatusText
= R
.string
.auth_wrong_connection_title
;
838 mAuthStatusText
= R
.string
.auth_timeout_title
;
840 case INCORRECT_ADDRESS
:
841 mAuthStatusText
= R
.string
.auth_incorrect_address_title
;
844 mAuthStatusText
= R
.string
.auth_ssl_general_error_title
;
847 mAuthStatusText
= R
.string
.auth_unauthorized
;
849 case HOST_NOT_AVAILABLE
:
850 mAuthStatusText
= R
.string
.auth_unknown_host_title
;
852 case INSTANCE_NOT_CONFIGURED
:
853 mAuthStatusText
= R
.string
.auth_not_configured_title
;
856 mAuthStatusText
= R
.string
.auth_incorrect_path_title
;
859 mAuthStatusText
= R
.string
.auth_oauth_error
;
861 case OAUTH2_ERROR_ACCESS_DENIED
:
862 mAuthStatusText
= R
.string
.auth_oauth_error_access_denied
;
864 case UNHANDLED_HTTP_CODE
:
866 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
876 * Processes the result of the request for and access token send
877 * to an OAuth authorization server.
879 * @param operation Operation performed requesting the access token.
880 * @param result Result of the operation.
882 private void onGetOAuthAccessTokenFinish(OAuth2GetAccessToken operation
, RemoteOperationResult result
) {
884 dismissDialog(DIALOG_OAUTH2_LOGIN_PROGRESS
);
885 } catch (IllegalArgumentException e
) {
886 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
889 String webdav_path
= AccountUtils
.getWebdavPath(mDiscoveredVersion
, true
);
890 if (result
.isSuccess() && webdav_path
!= null
) {
891 /// be gentle with the user
892 showDialog(DIALOG_LOGIN_PROGRESS
);
894 /// time to test the retrieved access token on the ownCloud server
895 mOAuthAccessToken
= ((OAuth2GetAccessToken
)operation
).getResultTokenMap().get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
896 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mOAuthAccessToken
);
897 mAuthCheckOperation
= new ExistenceCheckOperation("", this, false
);
898 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(mHostBaseUrl
+ webdav_path
), this);
899 client
.setBearerCredentials(mOAuthAccessToken
);
900 mAuthCheckOperation
.execute(client
, this, mHandler
);
903 updateAuthStatusIconAndText(result
);
905 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
911 * Processes the result of the access check performed to try the user credentials.
913 * Creates a new account through the AccountManager.
915 * @param operation Access check performed.
916 * @param result Result of the operation.
918 private void onAuthorizationCheckFinish(ExistenceCheckOperation operation
, RemoteOperationResult result
) {
920 dismissDialog(DIALOG_LOGIN_PROGRESS
);
921 } catch (IllegalArgumentException e
) {
922 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
925 if (result
.isSuccess()) {
926 Log_OC
.d(TAG
, "Successful access - time to save the account");
928 if (mAction
== ACTION_CREATE
) {
937 } else if (result
.isServerFail() || result
.isException()) {
938 /// if server fail or exception in authorization, the UI is updated as when a server check failed
939 mServerIsChecked
= true
;
940 mServerIsValid
= false
;
942 mOcServerChkOperation
= null
;
943 mDiscoveredVersion
= null
;
944 mHostBaseUrl
= normalizeUrl(mHostUrlInput
.getText().toString());
946 // update status icon and text
947 updateServerStatusIconAndText(result
);
953 // update input controls state
955 mOkButton
.setEnabled(false
);
957 // very special case (TODO: move to a common place for all the remote operations) (dangerous here?)
958 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
959 mLastSslUntrustedServerResult
= result
;
960 showDialog(DIALOG_SSL_VALIDATOR
);
963 } else { // authorization fail due to client side - probably wrong credentials
964 updateAuthStatusIconAndText(result
);
966 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
972 * Sets the proper response to get that the Account Authenticator that started this activity saves
973 * a new authorization token for mAccount.
975 private void updateToken() {
976 Bundle response
= new Bundle();
977 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
978 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
979 boolean isOAuth
= mOAuth2Check
.isChecked();
981 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mOAuthAccessToken
);
982 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
983 mAccountMgr
.setAuthToken(mAccount
, AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
, mOAuthAccessToken
);
985 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
986 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
988 setAccountAuthenticatorResult(response
);
993 * Creates a new account through the Account Authenticator that started this activity.
995 * This makes the account permanent.
997 * TODO Decide how to name the OAuth accounts
999 private void createAccount() {
1000 /// create and save new ownCloud account
1001 boolean isOAuth
= mOAuth2Check
.isChecked();
1003 Uri uri
= Uri
.parse(mHostBaseUrl
);
1004 String username
= mUsernameInput
.getText().toString().trim();
1006 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1008 String accountName
= username
+ "@" + uri
.getHost();
1009 if (uri
.getPort() >= 0) {
1010 accountName
+= ":" + uri
.getPort();
1012 mAccount
= new Account(accountName
, AccountAuthenticator
.ACCOUNT_TYPE
);
1014 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
); // with our implementation, the password is never input in the app
1016 mAccountMgr
.addAccountExplicitly(mAccount
, mPasswordInput
.getText().toString(), null
);
1019 /// add the new account as default in preferences, if there is none already
1020 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1021 if (defaultAccount
== null
) {
1022 SharedPreferences
.Editor editor
= PreferenceManager
1023 .getDefaultSharedPreferences(this).edit();
1024 editor
.putString("select_oc_account", accountName
);
1028 /// prepare result to return to the Authenticator
1029 // TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done
1030 final Intent intent
= new Intent();
1031 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, AccountAuthenticator
.ACCOUNT_TYPE
);
1032 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1034 intent
.putExtra(AccountManager
.KEY_AUTHTOKEN
, AccountAuthenticator
.ACCOUNT_TYPE
); // TODO check this; not sure it's right; maybe
1035 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1037 mAccountMgr
.setAuthToken(mAccount
, AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
, mOAuthAccessToken
);
1039 /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
1040 mAccountMgr
.setUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
, mDiscoveredVersion
.toString());
1041 mAccountMgr
.setUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
, mHostBaseUrl
);
1043 mAccountMgr
.setUserData(mAccount
, AccountAuthenticator
.KEY_SUPPORTS_OAUTH2
, "TRUE"); // TODO this flag should be unnecessary
1045 setAccountAuthenticatorResult(intent
.getExtras());
1046 setResult(RESULT_OK
, intent
);
1048 /// immediately request for the synchronization of the new account
1049 Bundle bundle
= new Bundle();
1050 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
1051 ContentResolver
.requestSync(mAccount
, AccountAuthenticator
.AUTHORITY
, bundle
);
1058 * Necessary to update the contents of the SSL Dialog
1060 * TODO move to some common place for all possible untrusted SSL failures
1063 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
1065 case DIALOG_LOGIN_PROGRESS
:
1066 case DIALOG_CERT_NOT_SAVED
:
1067 case DIALOG_OAUTH2_LOGIN_PROGRESS
:
1069 case DIALOG_SSL_VALIDATOR
: {
1070 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
1074 Log_OC
.e(TAG
, "Incorrect dialog called with id = " + id
);
1083 protected Dialog
onCreateDialog(int id
) {
1084 Dialog dialog
= null
;
1086 case DIALOG_LOGIN_PROGRESS
: {
1087 /// simple progress dialog
1088 ProgressDialog working_dialog
= new ProgressDialog(this);
1089 working_dialog
.setMessage(getResources().getString(R
.string
.auth_trying_to_login
));
1090 working_dialog
.setIndeterminate(true
);
1091 working_dialog
.setCancelable(true
);
1093 .setOnCancelListener(new DialogInterface
.OnCancelListener() {
1095 public void onCancel(DialogInterface dialog
) {
1096 /// TODO study if this is enough
1097 Log_OC
.i(TAG
, "Login canceled");
1098 if (mOperationThread
!= null
) {
1099 mOperationThread
.interrupt();
1104 dialog
= working_dialog
;
1107 case DIALOG_OAUTH2_LOGIN_PROGRESS
: {
1108 ProgressDialog working_dialog
= new ProgressDialog(this);
1109 working_dialog
.setMessage(String
.format("Getting authorization"));
1110 working_dialog
.setIndeterminate(true
);
1111 working_dialog
.setCancelable(true
);
1113 .setOnCancelListener(new DialogInterface
.OnCancelListener() {
1115 public void onCancel(DialogInterface dialog
) {
1116 Log_OC
.i(TAG
, "Login canceled");
1120 dialog
= working_dialog
;
1123 case DIALOG_SSL_VALIDATOR
: {
1124 /// TODO start to use new dialog interface, at least for this (it is a FragmentDialog already)
1125 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
1128 case DIALOG_CERT_NOT_SAVED
: {
1129 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
1130 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
1131 builder
.setCancelable(false
);
1132 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
1134 public void onClick(DialogInterface dialog
, int which
) {
1138 dialog
= builder
.create();
1142 Log_OC
.e(TAG
, "Incorrect dialog called with id = " + id
);
1149 * Starts and activity to open the 'new account' page in the ownCloud web site
1151 * @param view 'Account register' button
1153 public void onRegisterClick(View view
) {
1154 Intent register
= new Intent(Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.url_account_register
)));
1155 setResult(RESULT_CANCELED
);
1156 startActivity(register
);
1161 * Updates the content and visibility state of the icon and text associated
1162 * to the last check on the ownCloud server.
1164 private void showServerStatus() {
1165 TextView tv
= (TextView
) findViewById(R
.id
.server_status_text
);
1167 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1168 tv
.setVisibility(View
.INVISIBLE
);
1171 tv
.setText(mServerStatusText
);
1172 tv
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1173 tv
.setVisibility(View
.VISIBLE
);
1180 * Updates the content and visibility state of the icon and text associated
1181 * to the interactions with the OAuth authorization server.
1183 private void showAuthStatus() {
1184 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1185 mAuthStatusLayout
.setVisibility(View
.INVISIBLE
);
1188 mAuthStatusLayout
.setText(mAuthStatusText
);
1189 mAuthStatusLayout
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1190 mAuthStatusLayout
.setVisibility(View
.VISIBLE
);
1195 private void showRefreshButton() {
1196 mHostUrlInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, R
.drawable
.ic_action_refresh_black
, 0);
1197 mRefreshButtonEnabled
= true
;
1200 private void hideRefreshButton() {
1201 mHostUrlInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
1202 mRefreshButtonEnabled
= false
;
1206 * Called when the refresh button in the input field for ownCloud host is clicked.
1208 * Performs a new check on the URL in the input field.
1210 * @param view Refresh 'button'
1212 public void onRefreshClick() {
1218 * Called when the eye icon in the password field is clicked.
1220 * Toggles the visibility of the password in the field.
1222 public void onViewPasswordClick() {
1223 int selectionStart
= mPasswordInput
.getSelectionStart();
1224 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1225 if (isPasswordVisible()) {
1230 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1235 * Called when the checkbox for OAuth authorization is clicked.
1237 * Hides or shows the input fields for user & password.
1239 * @param view 'View password' 'button'
1241 public void onCheckClick(View view
) {
1242 CheckBox oAuth2Check
= (CheckBox
)view
;
1243 changeViewByOAuth2Check(oAuth2Check
.isChecked());
1248 * Changes the visibility of input elements depending upon the kind of authorization
1249 * chosen by the user: basic or OAuth
1251 * @param checked 'True' when OAuth is selected.
1253 public void changeViewByOAuth2Check(Boolean checked
) {
1256 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
1257 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
1258 mUsernameInput
.setVisibility(View
.GONE
);
1259 mPasswordInput
.setVisibility(View
.GONE
);
1261 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
1262 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
1263 mUsernameInput
.setVisibility(View
.VISIBLE
);
1264 mPasswordInput
.setVisibility(View
.VISIBLE
);
1270 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1272 public void onSavedCertificate() {
1277 * Called from SslValidatorDialog when a new server certificate could not be saved
1278 * when the user requested it.
1281 public void onFailedSavingCertificate() {
1282 showDialog(DIALOG_CERT_NOT_SAVED
);
1287 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1289 * Used to trigger the authorization check when the user presses 'enter' after writing the password.
1292 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1293 if (inputField
!= null
&& inputField
.equals(mPasswordInput
) &&
1294 actionId
== EditorInfo
.IME_ACTION_DONE
) {
1295 if (mOkButton
.isEnabled()) {
1296 mOkButton
.performClick();
1299 return false
; // always return false to grant that the software keyboard is hidden anyway
1303 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1305 private int fuzz
= 75;
1311 public boolean onTouch(View view
, MotionEvent event
) {
1312 Drawable rightDrawable
= null
;
1313 if (view
instanceof TextView
) {
1314 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1315 if (drawables
.length
> 2) {
1316 rightDrawable
= drawables
[2];
1319 if (rightDrawable
!= null
) {
1320 final int x
= (int) event
.getX();
1321 final int y
= (int) event
.getY();
1322 final Rect bounds
= rightDrawable
.getBounds();
1323 if (x
>= (view
.getRight() - bounds
.width() - fuzz
) && x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
)
1324 && y
>= (view
.getPaddingTop() - fuzz
) && y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1326 return onDrawableTouch(event
);
1332 public abstract boolean onDrawableTouch(final MotionEvent event
);