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 java
.net
.URLDecoder
;
23 import android
.accounts
.Account
;
24 import android
.accounts
.AccountManager
;
25 import android
.app
.AlertDialog
;
26 import android
.app
.Dialog
;
27 import android
.app
.ProgressDialog
;
28 import android
.content
.ContentResolver
;
29 import android
.content
.DialogInterface
;
30 import android
.content
.Intent
;
31 import android
.content
.SharedPreferences
;
32 import android
.graphics
.Rect
;
33 import android
.graphics
.drawable
.Drawable
;
34 import android
.net
.Uri
;
35 import android
.os
.Bundle
;
36 import android
.os
.Handler
;
37 import android
.preference
.PreferenceManager
;
38 import android
.support
.v4
.app
.Fragment
;
39 import android
.text
.Editable
;
40 import android
.text
.InputType
;
41 import android
.text
.TextWatcher
;
42 import android
.view
.KeyEvent
;
43 import android
.view
.MotionEvent
;
44 import android
.view
.View
;
45 import android
.view
.View
.OnFocusChangeListener
;
46 import android
.view
.View
.OnTouchListener
;
47 import android
.view
.Window
;
48 import android
.view
.inputmethod
.EditorInfo
;
49 import android
.widget
.Button
;
50 import android
.widget
.CheckBox
;
51 import android
.widget
.EditText
;
52 import android
.widget
.TextView
;
53 import android
.widget
.TextView
.OnEditorActionListener
;
54 import android
.widget
.Toast
;
56 import com
.actionbarsherlock
.app
.SherlockDialogFragment
;
57 import com
.owncloud
.android
.Log_OC
;
58 import com
.owncloud
.android
.R
;
59 import com
.owncloud
.android
.authentication
.SsoWebViewClient
.SsoWebViewClientListener
;
60 import com
.owncloud
.android
.network
.OwnCloudClientUtils
;
61 import com
.owncloud
.android
.operations
.ExistenceCheckOperation
;
62 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
63 import com
.owncloud
.android
.operations
.OnRemoteOperationListener
;
64 import com
.owncloud
.android
.operations
.OwnCloudServerCheckOperation
;
65 import com
.owncloud
.android
.operations
.RemoteOperation
;
66 import com
.owncloud
.android
.operations
.RemoteOperationResult
;
67 import com
.owncloud
.android
.operations
.RemoteOperationResult
.ResultCode
;
68 import com
.owncloud
.android
.ui
.dialog
.SamlWebViewDialog
;
69 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
;
70 import com
.owncloud
.android
.ui
.dialog
.SslValidatorDialog
.OnSslValidatorListener
;
71 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
73 import eu
.alefzero
.webdav
.WebdavClient
;
76 * This Activity is used to add an ownCloud account to the App
78 * @author Bartek Przybylski
79 * @author David A. Velasco
81 public class AuthenticatorActivity
extends AccountAuthenticatorActivity
82 implements OnRemoteOperationListener
, OnSslValidatorListener
, OnFocusChangeListener
, OnEditorActionListener
, SsoWebViewClientListener
{
84 private static final String TAG
= AuthenticatorActivity
.class.getSimpleName();
86 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
87 public static final String EXTRA_USER_NAME
= "USER_NAME";
88 public static final String EXTRA_HOST_NAME
= "HOST_NAME";
89 public static final String EXTRA_ACTION
= "ACTION";
90 public static final String EXTRA_ENFORCED_UPDATE
= "ENFORCE_UPDATE";
92 private static final String KEY_AUTH_MESSAGE_VISIBILITY
= "AUTH_MESSAGE_VISIBILITY";
93 private static final String KEY_AUTH_MESSAGE_TEXT
= "AUTH_MESSAGE_TEXT";
94 private static final String KEY_HOST_URL_TEXT
= "HOST_URL_TEXT";
95 private static final String KEY_OC_VERSION
= "OC_VERSION";
96 private static final String KEY_ACCOUNT
= "ACCOUNT";
97 private static final String KEY_SERVER_VALID
= "SERVER_VALID";
98 private static final String KEY_SERVER_CHECKED
= "SERVER_CHECKED";
99 private static final String KEY_SERVER_CHECK_IN_PROGRESS
= "SERVER_CHECK_IN_PROGRESS";
100 private static final String KEY_SERVER_STATUS_TEXT
= "SERVER_STATUS_TEXT";
101 private static final String KEY_SERVER_STATUS_ICON
= "SERVER_STATUS_ICON";
102 private static final String KEY_IS_SSL_CONN
= "IS_SSL_CONN";
103 private static final String KEY_PASSWORD_VISIBLE
= "PASSWORD_VISIBLE";
104 private static final String KEY_AUTH_STATUS_TEXT
= "AUTH_STATUS_TEXT";
105 private static final String KEY_AUTH_STATUS_ICON
= "AUTH_STATUS_ICON";
106 private static final String KEY_REFRESH_BUTTON_ENABLED
= "KEY_REFRESH_BUTTON_ENABLED";
108 private static final String KEY_OC_USERNAME_EQUALS
= "oc_username=";
110 private static final String AUTH_ON
= "on";
111 private static final String AUTH_OFF
= "off";
112 private static final String AUTH_OPTIONAL
= "optional";
114 private static final int DIALOG_LOGIN_PROGRESS
= 0;
115 private static final int DIALOG_SSL_VALIDATOR
= 1;
116 private static final int DIALOG_CERT_NOT_SAVED
= 2;
117 private static final int DIALOG_OAUTH2_LOGIN_PROGRESS
= 3;
119 public static final byte ACTION_CREATE
= 0;
120 public static final byte ACTION_UPDATE_TOKEN
= 1;
122 private static final String TAG_SAML_DIALOG
= "samlWebViewDialog";
124 private String mHostBaseUrl
;
125 private OwnCloudVersion mDiscoveredVersion
;
127 private String mAuthMessageText
;
128 private int mAuthMessageVisibility
, mServerStatusText
, mServerStatusIcon
;
129 private boolean mServerIsChecked
, mServerIsValid
, mIsSslConn
;
130 private int mAuthStatusText
, mAuthStatusIcon
;
131 private TextView mAuthStatusLayout
;
133 private final Handler mHandler
= new Handler();
134 private Thread mOperationThread
;
135 private OwnCloudServerCheckOperation mOcServerChkOperation
;
136 private ExistenceCheckOperation mAuthCheckOperation
;
137 private RemoteOperationResult mLastSslUntrustedServerResult
;
139 private Uri mNewCapturedUriFromOAuth2Redirection
;
141 private AccountManager mAccountMgr
;
142 private boolean mJustCreated
;
143 private byte mAction
;
144 private Account mAccount
;
146 private TextView mAuthMessage
;
148 private EditText mHostUrlInput
;
149 private boolean mHostUrlInputEnabled
;
150 private View mRefreshButton
;
152 private String mCurrentAuthTokenType
;
154 private EditText mUsernameInput
;
155 private EditText mPasswordInput
;
157 private CheckBox mOAuth2Check
;
159 private TextView mOAuthAuthEndpointText
;
160 private TextView mOAuthTokenEndpointText
;
162 private SamlWebViewDialog mSamlDialog
;
164 private View mOkButton
;
166 private String mAuthToken
;
172 * IMPORTANT ENTRY POINT 1: activity is shown to the user
175 protected void onCreate(Bundle savedInstanceState
) {
176 super.onCreate(savedInstanceState
);
177 getWindow().requestFeature(Window
.FEATURE_NO_TITLE
);
179 /// set view and get references to view elements
180 setContentView(R
.layout
.account_setup
);
181 mAuthMessage
= (TextView
) findViewById(R
.id
.auth_message
);
182 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
183 mHostUrlInput
.setText(getString(R
.string
.server_url
)); // valid although R.string.server_url is an empty string
184 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
185 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
186 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
187 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
188 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
189 mOkButton
= findViewById(R
.id
.buttonOK
);
190 mAuthStatusLayout
= (TextView
) findViewById(R
.id
.auth_status_text
);
192 /// set Host Url Input Enabled
193 mHostUrlInputEnabled
= getResources().getBoolean(R
.bool
.show_server_url_input
);
196 /// complete label for 'register account' button
197 Button b
= (Button
) findViewById(R
.id
.account_register
);
199 b
.setText(String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
203 mAccountMgr
= AccountManager
.get(this);
204 mNewCapturedUriFromOAuth2Redirection
= null
;
205 mAction
= getIntent().getByteExtra(EXTRA_ACTION
, ACTION_CREATE
);
208 boolean refreshButtonEnabled
= false
;
210 // URL input configuration applied
211 if (!mHostUrlInputEnabled
)
213 findViewById(R
.id
.hostUrlFrame
).setVisibility(View
.GONE
);
214 mRefreshButton
= findViewById(R
.id
.centeredRefreshButton
);
217 mRefreshButton
= findViewById(R
.id
.embeddedRefreshButton
);
220 if (savedInstanceState
== null
) {
221 /// connection state and info
222 mAuthMessageVisibility
= View
.GONE
;
223 mServerStatusText
= mServerStatusIcon
= 0;
224 mServerIsValid
= false
;
225 mServerIsChecked
= false
;
227 mAuthStatusText
= mAuthStatusIcon
= 0;
229 /// retrieve extras from intent
230 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
231 if (mAccount
!= null
) {
232 String ocVersion
= mAccountMgr
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
);
233 if (ocVersion
!= null
) {
234 mDiscoveredVersion
= new OwnCloudVersion(ocVersion
);
236 mHostBaseUrl
= normalizeUrl(mAccountMgr
.getUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
));
237 mHostUrlInput
.setText(mHostBaseUrl
);
238 String userName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
239 mUsernameInput
.setText(userName
);
241 initAuthorizationMethod(); // checks intent and setup.xml to determine mCurrentAuthorizationMethod
244 if (mAction
== ACTION_UPDATE_TOKEN
|| !mHostUrlInputEnabled
) {
249 /// connection state and info
250 mAuthMessageVisibility
= savedInstanceState
.getInt(KEY_AUTH_MESSAGE_VISIBILITY
);
251 mAuthMessageText
= savedInstanceState
.getString(KEY_AUTH_MESSAGE_TEXT
);
252 mServerIsValid
= savedInstanceState
.getBoolean(KEY_SERVER_VALID
);
253 mServerIsChecked
= savedInstanceState
.getBoolean(KEY_SERVER_CHECKED
);
254 mServerStatusText
= savedInstanceState
.getInt(KEY_SERVER_STATUS_TEXT
);
255 mServerStatusIcon
= savedInstanceState
.getInt(KEY_SERVER_STATUS_ICON
);
256 mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
257 mAuthStatusText
= savedInstanceState
.getInt(KEY_AUTH_STATUS_TEXT
);
258 mAuthStatusIcon
= savedInstanceState
.getInt(KEY_AUTH_STATUS_ICON
);
259 if (savedInstanceState
.getBoolean(KEY_PASSWORD_VISIBLE
, false
)) {
264 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
265 if (ocVersion
!= null
) {
266 mDiscoveredVersion
= new OwnCloudVersion(ocVersion
);
268 mHostBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
270 // account data, if updating
271 mAccount
= savedInstanceState
.getParcelable(KEY_ACCOUNT
);
272 mCurrentAuthTokenType
= savedInstanceState
.getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
273 if (mCurrentAuthTokenType
== null
) {
274 mCurrentAuthTokenType
= AccountAuthenticator
.AUTH_TOKEN_TYPE_PASSWORD
;
278 // check if server check was interrupted by a configuration change
279 if (savedInstanceState
.getBoolean(KEY_SERVER_CHECK_IN_PROGRESS
, false
)) {
283 // refresh button enabled
284 refreshButtonEnabled
= savedInstanceState
.getBoolean(KEY_REFRESH_BUTTON_ENABLED
);
289 if (mAuthMessageVisibility
== View
.VISIBLE
) {
290 showAuthMessage(mAuthMessageText
);
295 adaptViewAccordingToAuthenticationMethod();
299 if (mAction
== ACTION_UPDATE_TOKEN
) {
300 /// lock things that should not change
301 mHostUrlInput
.setEnabled(false
);
302 mHostUrlInput
.setFocusable(false
);
303 mUsernameInput
.setEnabled(false
);
304 mUsernameInput
.setFocusable(false
);
305 mOAuth2Check
.setVisibility(View
.GONE
);
308 //if (mServerIsChecked && !mServerIsValid && mRefreshButtonEnabled) showRefreshButton();
309 if (mServerIsChecked
&& !mServerIsValid
&& refreshButtonEnabled
) showRefreshButton();
310 mOkButton
.setEnabled(mServerIsValid
); // state not automatically recovered in configuration changes
312 if (AccountAuthenticator
.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE
.equals(mCurrentAuthTokenType
) ||
313 !AUTH_OPTIONAL
.equals(getString(R
.string
.auth_method_oauth2
))) {
314 mOAuth2Check
.setVisibility(View
.GONE
);
317 mPasswordInput
.setText(""); // clean password to avoid social hacking (disadvantage: password in removed if the device is turned aside)
319 /// bind view elements to listeners and other friends
320 mHostUrlInput
.setOnFocusChangeListener(this);
321 mHostUrlInput
.setImeOptions(EditorInfo
.IME_ACTION_NEXT
);
322 mHostUrlInput
.setOnEditorActionListener(this);
323 mHostUrlInput
.addTextChangedListener(new TextWatcher() {
326 public void afterTextChanged(Editable s
) {
327 if (!mHostBaseUrl
.equals(normalizeUrl(mHostUrlInput
.getText().toString()))) {
328 mOkButton
.setEnabled(false
);
333 public void beforeTextChanged(CharSequence s
, int start
, int count
, int after
) {}
336 public void onTextChanged(CharSequence s
, int start
, int before
, int count
) {}
339 mPasswordInput
.setOnFocusChangeListener(this);
340 mPasswordInput
.setImeOptions(EditorInfo
.IME_ACTION_DONE
);
341 mPasswordInput
.setOnEditorActionListener(this);
342 mPasswordInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
344 public boolean onDrawableTouch(final MotionEvent event
) {
345 if (event
.getAction() == MotionEvent
.ACTION_UP
) {
346 AuthenticatorActivity
.this.onViewPasswordClick();
356 private void initAuthorizationMethod() {
357 boolean oAuthRequired
= false
;
358 boolean samlWebSsoRequired
= false
;
360 mCurrentAuthTokenType
= getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
361 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
363 // TODO could be a good moment to validate the received token type, if not null
365 if (mCurrentAuthTokenType
== null
) {
366 if (mAccount
!= null
) {
367 /// same authentication method than the one used to create the account to update
368 oAuthRequired
= (mAccountMgr
.getUserData(mAccount
, AccountAuthenticator
.KEY_SUPPORTS_OAUTH2
) != null
);
369 samlWebSsoRequired
= (mAccountMgr
.getUserData(mAccount
, AccountAuthenticator
.KEY_SUPPORTS_SAML_WEB_SSO
) != null
);
372 /// use the one set in setup.xml
373 oAuthRequired
= AUTH_ON
.equals(getString(R
.string
.auth_method_oauth2
));
374 samlWebSsoRequired
= AUTH_ON
.equals(getString(R
.string
.auth_method_saml_web_sso
));
377 mCurrentAuthTokenType
= AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
;
378 } else if (samlWebSsoRequired
) {
379 mCurrentAuthTokenType
= AccountAuthenticator
.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE
;
381 mCurrentAuthTokenType
= AccountAuthenticator
.AUTH_TOKEN_TYPE_PASSWORD
;
385 if (mAccount
!= null
) {
386 String userName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
387 mUsernameInput
.setText(userName
);
390 mOAuth2Check
.setChecked(AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
.equals(mCurrentAuthTokenType
));
395 * Saves relevant state before {@link #onPause()}
397 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag, intended to defer the
398 * processing of the redirection caught in {@link #onNewIntent(Intent)} until {@link #onResume()}
400 * See {@link #loadSavedInstanceState(Bundle)}
403 protected void onSaveInstanceState(Bundle outState
) {
404 super.onSaveInstanceState(outState
);
406 /// connection state and info
407 outState
.putInt(KEY_AUTH_MESSAGE_VISIBILITY
, mAuthMessage
.getVisibility());
408 outState
.putString(KEY_AUTH_MESSAGE_TEXT
, mAuthMessage
.getText().toString());
409 outState
.putInt(KEY_SERVER_STATUS_TEXT
, mServerStatusText
);
410 outState
.putInt(KEY_SERVER_STATUS_ICON
, mServerStatusIcon
);
411 outState
.putBoolean(KEY_SERVER_VALID
, mServerIsValid
);
412 outState
.putBoolean(KEY_SERVER_CHECKED
, mServerIsChecked
);
413 outState
.putBoolean(KEY_SERVER_CHECK_IN_PROGRESS
, (!mServerIsValid
&& mOcServerChkOperation
!= null
));
414 outState
.putBoolean(KEY_IS_SSL_CONN
, mIsSslConn
);
415 outState
.putBoolean(KEY_PASSWORD_VISIBLE
, isPasswordVisible());
416 outState
.putInt(KEY_AUTH_STATUS_ICON
, mAuthStatusIcon
);
417 outState
.putInt(KEY_AUTH_STATUS_TEXT
, mAuthStatusText
);
420 if (mDiscoveredVersion
!= null
) {
421 outState
.putString(KEY_OC_VERSION
, mDiscoveredVersion
.toString());
423 outState
.putString(KEY_HOST_URL_TEXT
, mHostBaseUrl
);
425 /// account data, if updating
426 if (mAccount
!= null
) {
427 outState
.putParcelable(KEY_ACCOUNT
, mAccount
);
429 outState
.putString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
, mCurrentAuthTokenType
);
431 // refresh button enabled
432 outState
.putBoolean(KEY_REFRESH_BUTTON_ENABLED
, (mRefreshButton
.getVisibility() == View
.VISIBLE
));
439 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION request
442 * To make this possible, this activity needs to be qualified with android:launchMode = "singleTask" in the
443 * AndroidManifest.xml file.
446 protected void onNewIntent (Intent intent
) {
447 Log_OC
.d(TAG
, "onNewIntent()");
448 Uri data
= intent
.getData();
449 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
450 mNewCapturedUriFromOAuth2Redirection
= data
;
456 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION, and
457 * deferred in {@link #onNewIntent(Intent)}, is processed here.
460 protected void onResume() {
462 if (mAction
== ACTION_UPDATE_TOKEN
&& mJustCreated
&& getIntent().getBooleanExtra(EXTRA_ENFORCED_UPDATE
, false
)) {
463 if (AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
.equals(mCurrentAuthTokenType
)) {
464 //Toast.makeText(this, R.string.auth_expired_oauth_token_toast, Toast.LENGTH_LONG).show();
465 showAuthMessage(getString(R
.string
.auth_expired_oauth_token_toast
));
466 } else if (AccountAuthenticator
.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE
.equals(mCurrentAuthTokenType
)) {
467 //Toast.makeText(this, R.string.auth_expired_saml_sso_token_toast, Toast.LENGTH_LONG).show();
468 showAuthMessage(getString(R
.string
.auth_expired_saml_sso_token_toast
));
470 //Toast.makeText(this, R.string.auth_expired_basic_auth_toast, Toast.LENGTH_LONG).show();
471 showAuthMessage(getString(R
.string
.auth_expired_basic_auth_toast
));
475 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
476 getOAuth2AccessTokenFromCapturedRedirection();
479 mJustCreated
= false
;
485 * Parses the redirection with the response to the GET AUTHORIZATION request to the
486 * oAuth server and requests for the access token (GET ACCESS TOKEN)
488 private void getOAuth2AccessTokenFromCapturedRedirection() {
489 /// Parse data from OAuth redirection
490 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
491 mNewCapturedUriFromOAuth2Redirection
= null
;
493 /// Showing the dialog with instructions for the user.
494 showDialog(DIALOG_OAUTH2_LOGIN_PROGRESS
);
496 /// GET ACCESS TOKEN to the oAuth server
497 RemoteOperation operation
= new OAuth2GetAccessToken( getString(R
.string
.oauth2_client_id
),
498 getString(R
.string
.oauth2_redirect_uri
),
499 getString(R
.string
.oauth2_grant_type
),
501 //WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(getString(R.string.oauth2_url_endpoint_access)), getApplicationContext());
502 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(mOAuthTokenEndpointText
.getText().toString().trim()), getApplicationContext(), true
);
503 operation
.execute(client
, this, mHandler
);
509 * Handles the change of focus on the text inputs for the server URL and the password
511 public void onFocusChange(View view
, boolean hasFocus
) {
512 if (view
.getId() == R
.id
.hostUrlInput
) {
514 onUrlInputFocusLost((TextView
) view
);
520 } else if (view
.getId() == R
.id
.account_password
) {
521 onPasswordFocusChanged((TextView
) view
, hasFocus
);
527 * Handles changes in focus on the text input for the server URL.
529 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
530 * other field. The operation to check the existence of the server in the entered URL is
533 * When hasFocus: user 'comes back' to write again the server URL.
535 * @param hostInput TextView with the URL input field receiving the change of focus.
537 private void onUrlInputFocusLost(TextView hostInput
) {
538 if (!mHostBaseUrl
.equals(normalizeUrl(mHostUrlInput
.getText().toString()))) {
541 mOkButton
.setEnabled(mServerIsValid
);
542 if (!mServerIsValid
) {
549 private void checkOcServer() {
550 String uri
= trimUrlWebdav(mHostUrlInput
.getText().toString().trim());
552 if (!mHostUrlInputEnabled
){
553 uri
= getString(R
.string
.server_url
);
556 mServerIsValid
= false
;
557 mServerIsChecked
= false
;
558 mOkButton
.setEnabled(false
);
559 mDiscoveredVersion
= null
;
561 if (uri
.length() != 0) {
562 mServerStatusText
= R
.string
.auth_testing_connection
;
563 mServerStatusIcon
= R
.drawable
.progress_small
;
565 mOcServerChkOperation
= new OwnCloudServerCheckOperation(uri
, this);
566 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(uri
), this, true
);
567 mOperationThread
= mOcServerChkOperation
.execute(client
, this, mHandler
);
569 mServerStatusText
= 0;
570 mServerStatusIcon
= 0;
577 * Handles changes in focus on the text input for the password (basic authorization).
579 * When (hasFocus), the button to toggle password visibility is shown.
581 * When (!hasFocus), the button is made invisible and the password is hidden.
583 * @param passwordInput TextView with the password input field receiving the change of focus.
584 * @param hasFocus 'True' if focus is received, 'false' if is lost
586 private void onPasswordFocusChanged(TextView passwordInput
, boolean hasFocus
) {
588 showViewPasswordButton();
591 hidePasswordButton();
596 private void showViewPasswordButton() {
597 //int drawable = android.R.drawable.ic_menu_view;
598 int drawable
= R
.drawable
.ic_view
;
599 if (isPasswordVisible()) {
600 //drawable = android.R.drawable.ic_secure;
601 drawable
= R
.drawable
.ic_hide
;
603 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable
, 0);
606 private boolean isPasswordVisible() {
607 return ((mPasswordInput
.getInputType() & InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) == InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
610 private void hidePasswordButton() {
611 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
614 private void showPassword() {
615 mPasswordInput
.setInputType(InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
616 showViewPasswordButton();
619 private void hidePassword() {
620 mPasswordInput
.setInputType(InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
);
621 showViewPasswordButton();
626 * Cancels the authenticator activity
628 * IMPORTANT ENTRY POINT 3: Never underestimate the importance of cancellation
630 * This method is bound in the layout/acceoun_setup.xml resource file.
632 * @param view Cancel button
634 public void onCancelClick(View view
) {
635 setResult(RESULT_CANCELED
); // TODO review how is this related to AccountAuthenticator (debugging)
642 * Checks the credentials of the user in the root of the ownCloud server
643 * before creating a new local account.
645 * For basic authorization, a check of existence of the root folder is
648 * For OAuth, starts the flow to get an access token; the credentials test
649 * is postponed until it is available.
651 * IMPORTANT ENTRY POINT 4
653 * @param view OK button
655 public void onOkClick(View view
) {
656 // this check should be unnecessary
657 if (mDiscoveredVersion
== null
|| !mDiscoveredVersion
.isVersionValid() || mHostBaseUrl
== null
|| mHostBaseUrl
.length() == 0) {
658 mServerStatusIcon
= R
.drawable
.common_error
;
659 mServerStatusText
= R
.string
.auth_wtf_reenter_URL
;
661 mOkButton
.setEnabled(false
);
662 Log_OC
.wtf(TAG
, "The user was allowed to click 'connect' to an unchecked server!!");
667 if (AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
.equals(mCurrentAuthTokenType
)) {
668 startOauthorization();
669 } else if (AccountAuthenticator
.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE
.equals(mCurrentAuthTokenType
)) {
670 startSamlBasedFederatedSingleSignOnAuthorization();
672 checkBasicAuthorization();
678 * Tests the credentials entered by the user performing a check of existence on
679 * the root folder of the ownCloud server.
681 private void checkBasicAuthorization() {
682 /// get the path to the root folder through WebDAV from the version server
683 String webdav_path
= AccountUtils
.getWebdavPath(mDiscoveredVersion
, mCurrentAuthTokenType
);
685 /// get basic credentials entered by user
686 String username
= mUsernameInput
.getText().toString();
687 String password
= mPasswordInput
.getText().toString();
689 /// be gentle with the user
690 showDialog(DIALOG_LOGIN_PROGRESS
);
692 /// test credentials accessing the root folder
693 mAuthCheckOperation
= new ExistenceCheckOperation("", this, false
);
694 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(mHostBaseUrl
+ webdav_path
), this, true
);
695 client
.setBasicCredentials(username
, password
);
696 mOperationThread
= mAuthCheckOperation
.execute(client
, this, mHandler
);
701 * Starts the OAuth 'grant type' flow to get an access token, with
702 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
704 private void startOauthorization() {
705 // be gentle with the user
706 mAuthStatusIcon
= R
.drawable
.progress_small
;
707 mAuthStatusText
= R
.string
.oauth_login_connection
;
711 // GET AUTHORIZATION request
712 //Uri uri = Uri.parse(getString(R.string.oauth2_url_endpoint_auth));
713 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
714 Uri
.Builder uriBuilder
= uri
.buildUpon();
715 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
));
716 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
));
717 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
));
718 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
));
719 //uriBuilder.appendQueryParameter(OAuth2Constants.KEY_STATE, whateverwewant);
720 uri
= uriBuilder
.build();
721 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
722 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
728 * Starts the Web Single Sign On flow to get access to the root folder
731 private void startSamlBasedFederatedSingleSignOnAuthorization() {
732 // be gentle with the user
733 mAuthStatusIcon
= R
.drawable
.progress_small
;
734 mAuthStatusText
= R
.string
.auth_connecting_auth_server
;
736 showDialog(DIALOG_LOGIN_PROGRESS
);
738 /// get the path to the root folder through WebDAV from the version server
739 String webdav_path
= AccountUtils
.getWebdavPath(mDiscoveredVersion
, mCurrentAuthTokenType
);
741 /// test credentials accessing the root folder
742 mAuthCheckOperation
= new ExistenceCheckOperation("", this, false
);
743 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(mHostBaseUrl
+ webdav_path
), this, false
);
744 mOperationThread
= mAuthCheckOperation
.execute(client
, this, mHandler
);
748 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
750 * Dispatches the operation flow to the right method.
753 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
755 if (operation
instanceof OwnCloudServerCheckOperation
) {
756 onOcServerCheckFinish((OwnCloudServerCheckOperation
) operation
, result
);
758 } else if (operation
instanceof OAuth2GetAccessToken
) {
759 onGetOAuthAccessTokenFinish((OAuth2GetAccessToken
)operation
, result
);
761 } else if (operation
instanceof ExistenceCheckOperation
) {
762 if (AccountAuthenticator
.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE
.equals(mCurrentAuthTokenType
)) {
763 onSamlBasedFederatedSingleSignOnAuthorizationStart(operation
, result
);
766 onAuthorizationCheckFinish((ExistenceCheckOperation
)operation
, result
);
772 private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperation operation
, RemoteOperationResult result
) {
774 dismissDialog(DIALOG_LOGIN_PROGRESS
);
775 } catch (IllegalArgumentException e
) {
776 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
779 if (result
.isTemporalRedirection() || result
.isIdPRedirection()) {
780 String url
= result
.getRedirectedLocation();
781 String targetUrl
= mHostBaseUrl
+ AccountUtils
.getWebdavPath(mDiscoveredVersion
, mCurrentAuthTokenType
);
784 mSamlDialog
= SamlWebViewDialog
.newInstance(url
, targetUrl
);
785 mSamlDialog
.show(getSupportFragmentManager(), TAG_SAML_DIALOG
);
787 mAuthStatusIcon
= android
.R
.drawable
.ic_secure
;
788 mAuthStatusText
= R
.string
.auth_follow_auth_server
;
791 mAuthStatusIcon
= R
.drawable
.common_error
;
792 mAuthStatusText
= R
.string
.auth_unsupported_auth_method
;
800 * Processes the result of the server check performed when the user finishes the enter of the
803 * @param operation Server check performed.
804 * @param result Result of the check.
806 private void onOcServerCheckFinish(OwnCloudServerCheckOperation operation
, RemoteOperationResult result
) {
807 if (operation
.equals(mOcServerChkOperation
)) {
808 /// save result state
809 mServerIsChecked
= true
;
810 mServerIsValid
= result
.isSuccess();
811 mIsSslConn
= (result
.getCode() == ResultCode
.OK_SSL
);
812 mOcServerChkOperation
= null
;
814 /// update status icon and text
815 if (mServerIsValid
) {
820 updateServerStatusIconAndText(result
);
823 /// very special case (TODO: move to a common place for all the remote operations)
824 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
825 mLastSslUntrustedServerResult
= result
;
826 showDialog(DIALOG_SSL_VALIDATOR
);
829 /// retrieve discovered version and normalize server URL
830 mDiscoveredVersion
= operation
.getDiscoveredVersion();
831 mHostBaseUrl
= normalizeUrl(mHostUrlInput
.getText().toString());
833 /// allow or not the user try to access the server
834 mOkButton
.setEnabled(mServerIsValid
);
836 } // else nothing ; only the last check operation is considered;
837 // multiple can be triggered if the user amends a URL before a previous check can be triggered
841 private String
normalizeUrl(String url
) {
842 if (url
!= null
&& url
.length() > 0) {
844 if (!url
.toLowerCase().startsWith("http://") &&
845 !url
.toLowerCase().startsWith("https://")) {
847 url
= "https://" + url
;
849 url
= "http://" + url
;
853 // OC-208: Add suffix remote.php/webdav to normalize (OC-34)
854 url
= trimUrlWebdav(url
);
856 if (url
.endsWith("/")) {
857 url
= url
.substring(0, url
.length() - 1);
861 Log_OC
.d(TAG
, "URL Normalize " + url
);
862 return (url
!= null ? url
: "");
866 private String
trimUrlWebdav(String url
){
867 if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_4_0
)){
868 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_4_0
.length());
869 } else if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_2_0
)){
870 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_2_0
.length());
871 } else if (url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_1_2
)){
872 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_1_2
.length());
874 return (url
!= null ? url
: "");
879 * Chooses the right icon and text to show to the user for the received operation result.
881 * @param result Result of a remote operation performed in this activity
883 private void updateServerStatusIconAndText(RemoteOperationResult result
) {
884 mServerStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
886 switch (result
.getCode()) {
888 mServerStatusIcon
= android
.R
.drawable
.ic_secure
;
889 mServerStatusText
= R
.string
.auth_secure_connection
;
894 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
895 mServerStatusText
= R
.string
.auth_connection_established
;
896 mServerStatusIcon
= R
.drawable
.ic_ok
;
898 mServerStatusText
= R
.string
.auth_nossl_plain_ok_title
;
899 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
903 case NO_NETWORK_CONNECTION
:
904 mServerStatusIcon
= R
.drawable
.no_network
;
905 mServerStatusText
= R
.string
.auth_no_net_conn_title
;
908 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
909 mServerStatusText
= R
.string
.auth_ssl_unverified_server_title
;
912 mServerStatusText
= R
.string
.auth_bad_oc_version_title
;
914 case WRONG_CONNECTION
:
915 mServerStatusText
= R
.string
.auth_wrong_connection_title
;
918 mServerStatusText
= R
.string
.auth_timeout_title
;
920 case INCORRECT_ADDRESS
:
921 mServerStatusText
= R
.string
.auth_incorrect_address_title
;
924 mServerStatusText
= R
.string
.auth_ssl_general_error_title
;
927 mServerStatusText
= R
.string
.auth_unauthorized
;
929 case HOST_NOT_AVAILABLE
:
930 mServerStatusText
= R
.string
.auth_unknown_host_title
;
932 case INSTANCE_NOT_CONFIGURED
:
933 mServerStatusText
= R
.string
.auth_not_configured_title
;
936 mServerStatusText
= R
.string
.auth_incorrect_path_title
;
939 mServerStatusText
= R
.string
.auth_oauth_error
;
941 case OAUTH2_ERROR_ACCESS_DENIED
:
942 mServerStatusText
= R
.string
.auth_oauth_error_access_denied
;
944 case UNHANDLED_HTTP_CODE
:
946 mServerStatusText
= R
.string
.auth_unknown_error_title
;
949 mServerStatusText
= 0;
950 mServerStatusIcon
= 0;
956 * Chooses the right icon and text to show to the user for the received operation result.
958 * @param result Result of a remote operation performed in this activity
960 private void updateAuthStatusIconAndText(RemoteOperationResult result
) {
961 mAuthStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
963 switch (result
.getCode()) {
965 mAuthStatusIcon
= android
.R
.drawable
.ic_secure
;
966 mAuthStatusText
= R
.string
.auth_secure_connection
;
971 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
972 mAuthStatusText
= R
.string
.auth_connection_established
;
973 mAuthStatusIcon
= R
.drawable
.ic_ok
;
975 mAuthStatusText
= R
.string
.auth_nossl_plain_ok_title
;
976 mAuthStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
980 case NO_NETWORK_CONNECTION
:
981 mAuthStatusIcon
= R
.drawable
.no_network
;
982 mAuthStatusText
= R
.string
.auth_no_net_conn_title
;
985 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
986 mAuthStatusText
= R
.string
.auth_ssl_unverified_server_title
;
989 mAuthStatusText
= R
.string
.auth_bad_oc_version_title
;
991 case WRONG_CONNECTION
:
992 mAuthStatusText
= R
.string
.auth_wrong_connection_title
;
995 mAuthStatusText
= R
.string
.auth_timeout_title
;
997 case INCORRECT_ADDRESS
:
998 mAuthStatusText
= R
.string
.auth_incorrect_address_title
;
1001 mAuthStatusText
= R
.string
.auth_ssl_general_error_title
;
1004 mAuthStatusText
= R
.string
.auth_unauthorized
;
1006 case HOST_NOT_AVAILABLE
:
1007 mAuthStatusText
= R
.string
.auth_unknown_host_title
;
1009 case INSTANCE_NOT_CONFIGURED
:
1010 mAuthStatusText
= R
.string
.auth_not_configured_title
;
1012 case FILE_NOT_FOUND
:
1013 mAuthStatusText
= R
.string
.auth_incorrect_path_title
;
1016 mAuthStatusText
= R
.string
.auth_oauth_error
;
1018 case OAUTH2_ERROR_ACCESS_DENIED
:
1019 mAuthStatusText
= R
.string
.auth_oauth_error_access_denied
;
1021 case ACCOUNT_NOT_NEW
:
1022 mAuthStatusText
= R
.string
.auth_account_not_new
;
1024 case ACCOUNT_NOT_THE_SAME
:
1025 mAuthStatusText
= R
.string
.auth_account_not_the_same
;
1027 case UNHANDLED_HTTP_CODE
:
1029 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
1032 mAuthStatusText
= 0;
1033 mAuthStatusIcon
= 0;
1039 * Processes the result of the request for and access token send
1040 * to an OAuth authorization server.
1042 * @param operation Operation performed requesting the access token.
1043 * @param result Result of the operation.
1045 private void onGetOAuthAccessTokenFinish(OAuth2GetAccessToken operation
, RemoteOperationResult result
) {
1047 dismissDialog(DIALOG_OAUTH2_LOGIN_PROGRESS
);
1048 } catch (IllegalArgumentException e
) {
1049 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
1052 String webdav_path
= AccountUtils
.getWebdavPath(mDiscoveredVersion
, mCurrentAuthTokenType
);
1053 if (result
.isSuccess() && webdav_path
!= null
) {
1054 /// be gentle with the user
1055 showDialog(DIALOG_LOGIN_PROGRESS
);
1057 /// time to test the retrieved access token on the ownCloud server
1058 mAuthToken
= ((OAuth2GetAccessToken
)operation
).getResultTokenMap().get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
1059 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mAuthToken
);
1060 mAuthCheckOperation
= new ExistenceCheckOperation("", this, false
);
1061 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(mHostBaseUrl
+ webdav_path
), this, true
);
1062 client
.setBearerCredentials(mAuthToken
);
1063 mAuthCheckOperation
.execute(client
, this, mHandler
);
1066 updateAuthStatusIconAndText(result
);
1068 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1074 * Processes the result of the access check performed to try the user credentials.
1076 * Creates a new account through the AccountManager.
1078 * @param operation Access check performed.
1079 * @param result Result of the operation.
1081 private void onAuthorizationCheckFinish(ExistenceCheckOperation operation
, RemoteOperationResult result
) {
1083 dismissDialog(DIALOG_LOGIN_PROGRESS
);
1084 } catch (IllegalArgumentException e
) {
1085 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
1088 if (result
.isSuccess()) {
1089 Log_OC
.d(TAG
, "Successful access - time to save the account");
1091 boolean success
= false
;
1092 if (mAction
== ACTION_CREATE
) {
1093 success
= createAccount();
1096 success
= updateToken();
1103 } else if (result
.isServerFail() || result
.isException()) {
1104 /// if server fail or exception in authorization, the UI is updated as when a server check failed
1105 mServerIsChecked
= true
;
1106 mServerIsValid
= false
;
1108 mOcServerChkOperation
= null
;
1109 mDiscoveredVersion
= null
;
1110 mHostBaseUrl
= normalizeUrl(mHostUrlInput
.getText().toString());
1112 // update status icon and text
1113 updateServerStatusIconAndText(result
);
1115 mAuthStatusIcon
= 0;
1116 mAuthStatusText
= 0;
1119 // update input controls state
1120 showRefreshButton();
1121 mOkButton
.setEnabled(false
);
1123 // very special case (TODO: move to a common place for all the remote operations) (dangerous here?)
1124 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1125 mLastSslUntrustedServerResult
= result
;
1126 showDialog(DIALOG_SSL_VALIDATOR
);
1129 } else { // authorization fail due to client side - probably wrong credentials
1130 updateAuthStatusIconAndText(result
);
1132 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1138 * Sets the proper response to get that the Account Authenticator that started this activity saves
1139 * a new authorization token for mAccount.
1141 private boolean updateToken() {
1142 Bundle response
= new Bundle();
1143 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1144 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
1146 if (AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
.equals(mCurrentAuthTokenType
)) {
1147 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1148 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1149 mAccountMgr
.setAuthToken(mAccount
, mCurrentAuthTokenType
, mAuthToken
);
1151 } else if (AccountAuthenticator
.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE
.equals(mCurrentAuthTokenType
)) {
1152 String username
= getUserNameForSamlSso();
1153 if (!mUsernameInput
.getText().toString().equals(username
)) {
1154 // fail - not a new account, but an existing one; disallow
1155 RemoteOperationResult result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_THE_SAME
);
1156 updateAuthStatusIconAndText(result
);
1158 Log_OC
.d(TAG
, result
.getLogMessage());
1163 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1164 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1165 mAccountMgr
.setAuthToken(mAccount
, mCurrentAuthTokenType
, mAuthToken
);
1166 Log_OC
.e(TAG
, "saving auth token: " + mAuthToken
);
1169 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
1170 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
1172 setAccountAuthenticatorResult(response
);
1179 * Creates a new account through the Account Authenticator that started this activity.
1181 * This makes the account permanent.
1183 * TODO Decide how to name the OAuth accounts
1185 private boolean createAccount() {
1186 /// create and save new ownCloud account
1187 boolean isOAuth
= AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
.equals(mCurrentAuthTokenType
);
1188 boolean isSaml
= AccountAuthenticator
.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE
.equals(mCurrentAuthTokenType
);
1190 Uri uri
= Uri
.parse(mHostBaseUrl
);
1191 String username
= mUsernameInput
.getText().toString().trim();
1193 username
= getUserNameForSamlSso();
1195 } else if (isOAuth
) {
1196 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1198 String accountName
= username
+ "@" + uri
.getHost();
1199 if (uri
.getPort() >= 0) {
1200 accountName
+= ":" + uri
.getPort();
1202 mAccount
= new Account(accountName
, AccountAuthenticator
.ACCOUNT_TYPE
);
1203 if (AccountUtils
.exists(mAccount
, getApplicationContext())) {
1204 // fail - not a new account, but an existing one; disallow
1205 RemoteOperationResult result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_NEW
);
1206 updateAuthStatusIconAndText(result
);
1208 Log_OC
.d(TAG
, result
.getLogMessage());
1213 if (isOAuth
|| isSaml
) {
1214 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
); // with external authorizations, the password is never input in the app
1216 mAccountMgr
.addAccountExplicitly(mAccount
, mPasswordInput
.getText().toString(), null
);
1219 /// add the new account as default in preferences, if there is none already
1220 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1221 if (defaultAccount
== null
) {
1222 SharedPreferences
.Editor editor
= PreferenceManager
1223 .getDefaultSharedPreferences(this).edit();
1224 editor
.putString("select_oc_account", accountName
);
1228 /// prepare result to return to the Authenticator
1229 // TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done
1230 final Intent intent
= new Intent();
1231 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, AccountAuthenticator
.ACCOUNT_TYPE
);
1232 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1234 intent.putExtra(AccountManager.KEY_AUTHTOKEN, AccountAuthenticator.ACCOUNT_TYPE); */
1235 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1236 if (isOAuth
|| isSaml
) {
1237 mAccountMgr
.setAuthToken(mAccount
, mCurrentAuthTokenType
, mAuthToken
);
1238 Log_OC
.e(TAG
, "saving auth token: " + mAuthToken
);
1240 /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
1241 mAccountMgr
.setUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
, mDiscoveredVersion
.toString());
1242 mAccountMgr
.setUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
, mHostBaseUrl
);
1244 mAccountMgr
.setUserData(mAccount
, AccountAuthenticator
.KEY_SUPPORTS_SAML_WEB_SSO
, "TRUE");
1245 } else if (isOAuth
) {
1246 mAccountMgr
.setUserData(mAccount
, AccountAuthenticator
.KEY_SUPPORTS_OAUTH2
, "TRUE");
1249 setAccountAuthenticatorResult(intent
.getExtras());
1250 setResult(RESULT_OK
, intent
);
1252 /// immediately request for the synchronization of the new account
1253 Bundle bundle
= new Bundle();
1254 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
1255 ContentResolver
.requestSync(mAccount
, AccountAuthenticator
.AUTHORITY
, bundle
);
1257 // Bundle bundle = new Bundle();
1258 // bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
1259 // ContentResolver.requestSync(mAccount, AccountAuthenticator.AUTHORITY, bundle);
1265 private String
getUserNameForSamlSso() {
1266 if (mAuthToken
!= null
) {
1267 String
[] cookies
= mAuthToken
.split(";");
1268 for (int i
=0; i
<cookies
.length
; i
++) {
1269 if (cookies
[i
].startsWith(KEY_OC_USERNAME_EQUALS
)) {
1270 String value
= Uri
.decode(cookies
[i
].substring(KEY_OC_USERNAME_EQUALS
.length()));
1282 * Necessary to update the contents of the SSL Dialog
1284 * TODO move to some common place for all possible untrusted SSL failures
1287 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
1289 case DIALOG_LOGIN_PROGRESS
:
1290 case DIALOG_CERT_NOT_SAVED
:
1291 case DIALOG_OAUTH2_LOGIN_PROGRESS
:
1293 case DIALOG_SSL_VALIDATOR
: {
1294 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
1298 Log_OC
.e(TAG
, "Incorrect dialog called with id = " + id
);
1307 protected Dialog
onCreateDialog(int id
) {
1308 Dialog dialog
= null
;
1310 case DIALOG_LOGIN_PROGRESS
: {
1311 /// simple progress dialog
1312 ProgressDialog working_dialog
= new ProgressDialog(this);
1313 working_dialog
.setMessage(getResources().getString(R
.string
.auth_trying_to_login
));
1314 working_dialog
.setIndeterminate(true
);
1315 working_dialog
.setCancelable(true
);
1317 .setOnCancelListener(new DialogInterface
.OnCancelListener() {
1319 public void onCancel(DialogInterface dialog
) {
1320 /// TODO study if this is enough
1321 Log_OC
.i(TAG
, "Login canceled");
1322 if (mOperationThread
!= null
) {
1323 mOperationThread
.interrupt();
1328 dialog
= working_dialog
;
1331 case DIALOG_OAUTH2_LOGIN_PROGRESS
: {
1332 ProgressDialog working_dialog
= new ProgressDialog(this);
1333 working_dialog
.setMessage(String
.format("Getting authorization"));
1334 working_dialog
.setIndeterminate(true
);
1335 working_dialog
.setCancelable(true
);
1337 .setOnCancelListener(new DialogInterface
.OnCancelListener() {
1339 public void onCancel(DialogInterface dialog
) {
1340 Log_OC
.i(TAG
, "Login canceled");
1344 dialog
= working_dialog
;
1347 case DIALOG_SSL_VALIDATOR
: {
1348 /// TODO start to use new dialog interface, at least for this (it is a FragmentDialog already)
1349 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
1352 case DIALOG_CERT_NOT_SAVED
: {
1353 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
1354 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
1355 builder
.setCancelable(false
);
1356 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
1358 public void onClick(DialogInterface dialog
, int which
) {
1362 dialog
= builder
.create();
1366 Log_OC
.e(TAG
, "Incorrect dialog called with id = " + id
);
1373 * Starts and activity to open the 'new account' page in the ownCloud web site
1375 * @param view 'Account register' button
1377 public void onRegisterClick(View view
) {
1378 Intent register
= new Intent(Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.url_account_register
)));
1379 setResult(RESULT_CANCELED
);
1380 startActivity(register
);
1385 * Updates the content and visibility state of the icon and text associated
1386 * to the last check on the ownCloud server.
1388 private void showServerStatus() {
1389 TextView tv
= (TextView
) findViewById(R
.id
.server_status_text
);
1391 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1392 tv
.setVisibility(View
.INVISIBLE
);
1395 tv
.setText(mServerStatusText
);
1396 tv
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1397 tv
.setVisibility(View
.VISIBLE
);
1404 * Updates the content and visibility state of the icon and text associated
1405 * to the interactions with the OAuth authorization server.
1407 private void showAuthStatus() {
1408 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1409 mAuthStatusLayout
.setVisibility(View
.INVISIBLE
);
1412 mAuthStatusLayout
.setText(mAuthStatusText
);
1413 mAuthStatusLayout
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1414 mAuthStatusLayout
.setVisibility(View
.VISIBLE
);
1419 private void showRefreshButton() {
1420 mRefreshButton
.setVisibility(View
.VISIBLE
);
1423 private void hideRefreshButton() {
1424 mRefreshButton
.setVisibility(View
.GONE
);
1428 * Called when the refresh button in the input field for ownCloud host is clicked.
1430 * Performs a new check on the URL in the input field.
1432 * @param view Refresh 'button'
1434 public void onRefreshClick(View view
) {
1440 * Called when the eye icon in the password field is clicked.
1442 * Toggles the visibility of the password in the field.
1444 public void onViewPasswordClick() {
1445 int selectionStart
= mPasswordInput
.getSelectionStart();
1446 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1447 if (isPasswordVisible()) {
1452 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1457 * Called when the checkbox for OAuth authorization is clicked.
1459 * Hides or shows the input fields for user & password.
1461 * @param view 'View password' 'button'
1463 public void onCheckClick(View view
) {
1464 CheckBox oAuth2Check
= (CheckBox
)view
;
1465 if (oAuth2Check
.isChecked()) {
1466 mCurrentAuthTokenType
= AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
;
1468 mCurrentAuthTokenType
= AccountAuthenticator
.AUTH_TOKEN_TYPE_PASSWORD
;
1470 adaptViewAccordingToAuthenticationMethod();
1475 * Changes the visibility of input elements depending on
1476 * the current authorization method.
1478 private void adaptViewAccordingToAuthenticationMethod () {
1479 if (AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
.equals(mCurrentAuthTokenType
)) {
1480 // OAuth 2 authorization
1481 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
1482 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
1483 mUsernameInput
.setVisibility(View
.GONE
);
1484 mPasswordInput
.setVisibility(View
.GONE
);
1486 } else if (AccountAuthenticator
.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE
.equals(mCurrentAuthTokenType
)) {
1487 // SAML-based web Single Sign On
1488 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
1489 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
1490 mUsernameInput
.setVisibility(View
.GONE
);
1491 mPasswordInput
.setVisibility(View
.GONE
);
1493 // basic HTTP authorization
1494 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
1495 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
1496 mUsernameInput
.setVisibility(View
.VISIBLE
);
1497 mPasswordInput
.setVisibility(View
.VISIBLE
);
1502 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1504 public void onSavedCertificate() {
1509 * Called from SslValidatorDialog when a new server certificate could not be saved
1510 * when the user requested it.
1513 public void onFailedSavingCertificate() {
1514 showDialog(DIALOG_CERT_NOT_SAVED
);
1519 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1521 * Used to trigger the authentication check when the user presses 'enter' after writing the password,
1522 * or to throw the server test when the only field on screen is the URL input field.
1525 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1526 if (actionId
== EditorInfo
.IME_ACTION_DONE
&& inputField
!= null
&& inputField
.equals(mPasswordInput
)) {
1527 if (mOkButton
.isEnabled()) {
1528 mOkButton
.performClick();
1531 } else if (actionId
== EditorInfo
.IME_ACTION_NEXT
&& inputField
!= null
&& inputField
.equals(mHostUrlInput
)) {
1532 if (AccountAuthenticator
.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE
.equals(mCurrentAuthTokenType
)) {
1536 return false
; // always return false to grant that the software keyboard is hidden anyway
1540 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1542 private int fuzz
= 75;
1548 public boolean onTouch(View view
, MotionEvent event
) {
1549 Drawable rightDrawable
= null
;
1550 if (view
instanceof TextView
) {
1551 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1552 if (drawables
.length
> 2) {
1553 rightDrawable
= drawables
[2];
1556 if (rightDrawable
!= null
) {
1557 final int x
= (int) event
.getX();
1558 final int y
= (int) event
.getY();
1559 final Rect bounds
= rightDrawable
.getBounds();
1560 if (x
>= (view
.getRight() - bounds
.width() - fuzz
) && x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
)
1561 && y
>= (view
.getPaddingTop() - fuzz
) && y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1563 return onDrawableTouch(event
);
1569 public abstract boolean onDrawableTouch(final MotionEvent event
);
1573 public void onSamlDialogSuccess(String sessionCookie
){
1574 mAuthToken
= sessionCookie
;
1576 if (sessionCookie
!= null
&& sessionCookie
.length() > 0) {
1577 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1578 mAuthToken
= sessionCookie
;
1579 boolean success
= false
;
1580 if (mAction
== ACTION_CREATE
) {
1581 success
= createAccount();
1584 success
= updateToken();
1595 public void onSsoFinished(String sessionCookies
) {
1596 //Toast.makeText(this, "got cookies: " + sessionCookie, Toast.LENGTH_LONG).show();
1598 if (sessionCookies
!= null
&& sessionCookies
.length() > 0) {
1599 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1600 onSamlDialogSuccess(sessionCookies
);
1601 Fragment fd
= getSupportFragmentManager().findFragmentByTag(TAG_SAML_DIALOG
);
1602 if (fd
!= null
&& fd
instanceof SherlockDialogFragment
) {
1603 Dialog d
= ((SherlockDialogFragment
)fd
).getDialog();
1604 if (d
!= null
&& d
.isShowing()) {
1611 Log_OC
.d(TAG
, "SSO failed");
1616 /** Show auth_message
1620 private void showAuthMessage(String message
) {
1621 mAuthMessage
.setVisibility(View
.VISIBLE
);
1622 mAuthMessage
.setText(message
);
1625 private void hideAuthMessage() {
1626 mAuthMessage
.setVisibility(View
.GONE
);
1630 private void syncAccount(){
1631 /// immediately request for the synchronization of the new account
1632 Bundle bundle
= new Bundle();
1633 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
1634 ContentResolver
.requestSync(mAccount
, AccountAuthenticator
.AUTHORITY
, bundle
);