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 UNHANDLED_HTTP_CODE
:
1026 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
1029 mAuthStatusText
= 0;
1030 mAuthStatusIcon
= 0;
1036 * Processes the result of the request for and access token send
1037 * to an OAuth authorization server.
1039 * @param operation Operation performed requesting the access token.
1040 * @param result Result of the operation.
1042 private void onGetOAuthAccessTokenFinish(OAuth2GetAccessToken operation
, RemoteOperationResult result
) {
1044 dismissDialog(DIALOG_OAUTH2_LOGIN_PROGRESS
);
1045 } catch (IllegalArgumentException e
) {
1046 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
1049 String webdav_path
= AccountUtils
.getWebdavPath(mDiscoveredVersion
, mCurrentAuthTokenType
);
1050 if (result
.isSuccess() && webdav_path
!= null
) {
1051 /// be gentle with the user
1052 showDialog(DIALOG_LOGIN_PROGRESS
);
1054 /// time to test the retrieved access token on the ownCloud server
1055 mAuthToken
= ((OAuth2GetAccessToken
)operation
).getResultTokenMap().get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
1056 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mAuthToken
);
1057 mAuthCheckOperation
= new ExistenceCheckOperation("", this, false
);
1058 WebdavClient client
= OwnCloudClientUtils
.createOwnCloudClient(Uri
.parse(mHostBaseUrl
+ webdav_path
), this, true
);
1059 client
.setBearerCredentials(mAuthToken
);
1060 mAuthCheckOperation
.execute(client
, this, mHandler
);
1063 updateAuthStatusIconAndText(result
);
1065 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1071 * Processes the result of the access check performed to try the user credentials.
1073 * Creates a new account through the AccountManager.
1075 * @param operation Access check performed.
1076 * @param result Result of the operation.
1078 private void onAuthorizationCheckFinish(ExistenceCheckOperation operation
, RemoteOperationResult result
) {
1080 dismissDialog(DIALOG_LOGIN_PROGRESS
);
1081 } catch (IllegalArgumentException e
) {
1082 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
1085 if (result
.isSuccess()) {
1086 Log_OC
.d(TAG
, "Successful access - time to save the account");
1088 boolean success
= true
;
1089 if (mAction
== ACTION_CREATE
) {
1090 success
= createAccount();
1100 } else if (result
.isServerFail() || result
.isException()) {
1101 /// if server fail or exception in authorization, the UI is updated as when a server check failed
1102 mServerIsChecked
= true
;
1103 mServerIsValid
= false
;
1105 mOcServerChkOperation
= null
;
1106 mDiscoveredVersion
= null
;
1107 mHostBaseUrl
= normalizeUrl(mHostUrlInput
.getText().toString());
1109 // update status icon and text
1110 updateServerStatusIconAndText(result
);
1112 mAuthStatusIcon
= 0;
1113 mAuthStatusText
= 0;
1116 // update input controls state
1117 showRefreshButton();
1118 mOkButton
.setEnabled(false
);
1120 // very special case (TODO: move to a common place for all the remote operations) (dangerous here?)
1121 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1122 mLastSslUntrustedServerResult
= result
;
1123 showDialog(DIALOG_SSL_VALIDATOR
);
1126 } else { // authorization fail due to client side - probably wrong credentials
1127 updateAuthStatusIconAndText(result
);
1129 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1135 * Sets the proper response to get that the Account Authenticator that started this activity saves
1136 * a new authorization token for mAccount.
1138 private void updateToken() {
1139 Bundle response
= new Bundle();
1140 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1141 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
1143 if (AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
.equals(mCurrentAuthTokenType
)) {
1144 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1145 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1146 mAccountMgr
.setAuthToken(mAccount
, mCurrentAuthTokenType
, mAuthToken
);
1148 } else if (AccountAuthenticator
.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE
.equals(mCurrentAuthTokenType
)) {
1149 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1150 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1151 mAccountMgr
.setAuthToken(mAccount
, mCurrentAuthTokenType
, mAuthToken
);
1154 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
1155 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
1157 setAccountAuthenticatorResult(response
);
1165 * Creates a new account through the Account Authenticator that started this activity.
1167 * This makes the account permanent.
1169 * TODO Decide how to name the OAuth accounts
1171 private boolean createAccount() {
1172 /// create and save new ownCloud account
1173 boolean isOAuth
= AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
.equals(mCurrentAuthTokenType
);
1174 boolean isSaml
= AccountAuthenticator
.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE
.equals(mCurrentAuthTokenType
);
1176 Uri uri
= Uri
.parse(mHostBaseUrl
);
1177 String username
= mUsernameInput
.getText().toString().trim();
1179 username
= getUserNameForSamlSso();
1181 } else if (isOAuth
) {
1182 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1184 String accountName
= username
+ "@" + uri
.getHost();
1185 if (uri
.getPort() >= 0) {
1186 accountName
+= ":" + uri
.getPort();
1188 mAccount
= new Account(accountName
, AccountAuthenticator
.ACCOUNT_TYPE
);
1189 if (AccountUtils
.exists(mAccount
, getApplicationContext())) {
1190 // fail - not a new account, but an existing one; disallow
1191 RemoteOperationResult result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_NEW
);
1192 updateAuthStatusIconAndText(result
);
1194 Log_OC
.d(TAG
, result
.getLogMessage());
1200 if (isOAuth
|| isSaml
) {
1201 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
); // with external authorizations, the password is never input in the app
1203 mAccountMgr
.addAccountExplicitly(mAccount
, mPasswordInput
.getText().toString(), null
);
1206 /// add the new account as default in preferences, if there is none already
1207 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1208 if (defaultAccount
== null
) {
1209 SharedPreferences
.Editor editor
= PreferenceManager
1210 .getDefaultSharedPreferences(this).edit();
1211 editor
.putString("select_oc_account", accountName
);
1215 /// prepare result to return to the Authenticator
1216 // TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done
1217 final Intent intent
= new Intent();
1218 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, AccountAuthenticator
.ACCOUNT_TYPE
);
1219 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1221 intent.putExtra(AccountManager.KEY_AUTHTOKEN, AccountAuthenticator.ACCOUNT_TYPE); */
1222 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1223 if (isOAuth
|| isSaml
) {
1224 mAccountMgr
.setAuthToken(mAccount
, mCurrentAuthTokenType
, mAuthToken
);
1226 /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
1227 mAccountMgr
.setUserData(mAccount
, AccountAuthenticator
.KEY_OC_VERSION
, mDiscoveredVersion
.toString());
1228 mAccountMgr
.setUserData(mAccount
, AccountAuthenticator
.KEY_OC_BASE_URL
, mHostBaseUrl
);
1230 mAccountMgr
.setUserData(mAccount
, AccountAuthenticator
.KEY_SUPPORTS_SAML_WEB_SSO
, "TRUE");
1231 } else if (isOAuth
) {
1232 mAccountMgr
.setUserData(mAccount
, AccountAuthenticator
.KEY_SUPPORTS_OAUTH2
, "TRUE");
1235 setAccountAuthenticatorResult(intent
.getExtras());
1236 setResult(RESULT_OK
, intent
);
1238 /// immediately request for the synchronization of the new account
1239 Bundle bundle
= new Bundle();
1240 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
1241 ContentResolver
.requestSync(mAccount
, AccountAuthenticator
.AUTHORITY
, bundle
);
1243 // Bundle bundle = new Bundle();
1244 // bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
1245 // ContentResolver.requestSync(mAccount, AccountAuthenticator.AUTHORITY, bundle);
1251 private String
getUserNameForSamlSso() {
1252 if (mAuthToken
!= null
) {
1253 String
[] cookies
= mAuthToken
.split(";");
1254 for (int i
=0; i
<cookies
.length
; i
++) {
1255 if (cookies
[i
].startsWith(KEY_OC_USERNAME_EQUALS
)) {
1256 String value
= Uri
.decode(cookies
[i
].substring(KEY_OC_USERNAME_EQUALS
.length()));
1268 * Necessary to update the contents of the SSL Dialog
1270 * TODO move to some common place for all possible untrusted SSL failures
1273 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
1275 case DIALOG_LOGIN_PROGRESS
:
1276 case DIALOG_CERT_NOT_SAVED
:
1277 case DIALOG_OAUTH2_LOGIN_PROGRESS
:
1279 case DIALOG_SSL_VALIDATOR
: {
1280 ((SslValidatorDialog
)dialog
).updateResult(mLastSslUntrustedServerResult
);
1284 Log_OC
.e(TAG
, "Incorrect dialog called with id = " + id
);
1293 protected Dialog
onCreateDialog(int id
) {
1294 Dialog dialog
= null
;
1296 case DIALOG_LOGIN_PROGRESS
: {
1297 /// simple progress dialog
1298 ProgressDialog working_dialog
= new ProgressDialog(this);
1299 working_dialog
.setMessage(getResources().getString(R
.string
.auth_trying_to_login
));
1300 working_dialog
.setIndeterminate(true
);
1301 working_dialog
.setCancelable(true
);
1303 .setOnCancelListener(new DialogInterface
.OnCancelListener() {
1305 public void onCancel(DialogInterface dialog
) {
1306 /// TODO study if this is enough
1307 Log_OC
.i(TAG
, "Login canceled");
1308 if (mOperationThread
!= null
) {
1309 mOperationThread
.interrupt();
1314 dialog
= working_dialog
;
1317 case DIALOG_OAUTH2_LOGIN_PROGRESS
: {
1318 ProgressDialog working_dialog
= new ProgressDialog(this);
1319 working_dialog
.setMessage(String
.format("Getting authorization"));
1320 working_dialog
.setIndeterminate(true
);
1321 working_dialog
.setCancelable(true
);
1323 .setOnCancelListener(new DialogInterface
.OnCancelListener() {
1325 public void onCancel(DialogInterface dialog
) {
1326 Log_OC
.i(TAG
, "Login canceled");
1330 dialog
= working_dialog
;
1333 case DIALOG_SSL_VALIDATOR
: {
1334 /// TODO start to use new dialog interface, at least for this (it is a FragmentDialog already)
1335 dialog
= SslValidatorDialog
.newInstance(this, mLastSslUntrustedServerResult
, this);
1338 case DIALOG_CERT_NOT_SAVED
: {
1339 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
1340 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
1341 builder
.setCancelable(false
);
1342 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
1344 public void onClick(DialogInterface dialog
, int which
) {
1348 dialog
= builder
.create();
1352 Log_OC
.e(TAG
, "Incorrect dialog called with id = " + id
);
1359 * Starts and activity to open the 'new account' page in the ownCloud web site
1361 * @param view 'Account register' button
1363 public void onRegisterClick(View view
) {
1364 Intent register
= new Intent(Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.url_account_register
)));
1365 setResult(RESULT_CANCELED
);
1366 startActivity(register
);
1371 * Updates the content and visibility state of the icon and text associated
1372 * to the last check on the ownCloud server.
1374 private void showServerStatus() {
1375 TextView tv
= (TextView
) findViewById(R
.id
.server_status_text
);
1377 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1378 tv
.setVisibility(View
.INVISIBLE
);
1381 tv
.setText(mServerStatusText
);
1382 tv
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1383 tv
.setVisibility(View
.VISIBLE
);
1390 * Updates the content and visibility state of the icon and text associated
1391 * to the interactions with the OAuth authorization server.
1393 private void showAuthStatus() {
1394 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1395 mAuthStatusLayout
.setVisibility(View
.INVISIBLE
);
1398 mAuthStatusLayout
.setText(mAuthStatusText
);
1399 mAuthStatusLayout
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1400 mAuthStatusLayout
.setVisibility(View
.VISIBLE
);
1405 private void showRefreshButton() {
1406 mRefreshButton
.setVisibility(View
.VISIBLE
);
1409 private void hideRefreshButton() {
1410 mRefreshButton
.setVisibility(View
.GONE
);
1414 * Called when the refresh button in the input field for ownCloud host is clicked.
1416 * Performs a new check on the URL in the input field.
1418 * @param view Refresh 'button'
1420 public void onRefreshClick(View view
) {
1426 * Called when the eye icon in the password field is clicked.
1428 * Toggles the visibility of the password in the field.
1430 public void onViewPasswordClick() {
1431 int selectionStart
= mPasswordInput
.getSelectionStart();
1432 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1433 if (isPasswordVisible()) {
1438 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1443 * Called when the checkbox for OAuth authorization is clicked.
1445 * Hides or shows the input fields for user & password.
1447 * @param view 'View password' 'button'
1449 public void onCheckClick(View view
) {
1450 CheckBox oAuth2Check
= (CheckBox
)view
;
1451 if (oAuth2Check
.isChecked()) {
1452 mCurrentAuthTokenType
= AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
;
1454 mCurrentAuthTokenType
= AccountAuthenticator
.AUTH_TOKEN_TYPE_PASSWORD
;
1456 adaptViewAccordingToAuthenticationMethod();
1461 * Changes the visibility of input elements depending on
1462 * the current authorization method.
1464 private void adaptViewAccordingToAuthenticationMethod () {
1465 if (AccountAuthenticator
.AUTH_TOKEN_TYPE_ACCESS_TOKEN
.equals(mCurrentAuthTokenType
)) {
1466 // OAuth 2 authorization
1467 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
1468 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
1469 mUsernameInput
.setVisibility(View
.GONE
);
1470 mPasswordInput
.setVisibility(View
.GONE
);
1472 } else if (AccountAuthenticator
.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE
.equals(mCurrentAuthTokenType
)) {
1473 // SAML-based web Single Sign On
1474 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
1475 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
1476 mUsernameInput
.setVisibility(View
.GONE
);
1477 mPasswordInput
.setVisibility(View
.GONE
);
1479 // basic HTTP authorization
1480 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
1481 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
1482 mUsernameInput
.setVisibility(View
.VISIBLE
);
1483 mPasswordInput
.setVisibility(View
.VISIBLE
);
1488 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1490 public void onSavedCertificate() {
1495 * Called from SslValidatorDialog when a new server certificate could not be saved
1496 * when the user requested it.
1499 public void onFailedSavingCertificate() {
1500 showDialog(DIALOG_CERT_NOT_SAVED
);
1505 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1507 * Used to trigger the authentication check when the user presses 'enter' after writing the password,
1508 * or to throw the server test when the only field on screen is the URL input field.
1511 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1512 if (actionId
== EditorInfo
.IME_ACTION_DONE
&& inputField
!= null
&& inputField
.equals(mPasswordInput
)) {
1513 if (mOkButton
.isEnabled()) {
1514 mOkButton
.performClick();
1517 } else if (actionId
== EditorInfo
.IME_ACTION_NEXT
&& inputField
!= null
&& inputField
.equals(mHostUrlInput
)) {
1518 if (AccountAuthenticator
.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE
.equals(mCurrentAuthTokenType
)) {
1522 return false
; // always return false to grant that the software keyboard is hidden anyway
1526 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1528 private int fuzz
= 75;
1534 public boolean onTouch(View view
, MotionEvent event
) {
1535 Drawable rightDrawable
= null
;
1536 if (view
instanceof TextView
) {
1537 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1538 if (drawables
.length
> 2) {
1539 rightDrawable
= drawables
[2];
1542 if (rightDrawable
!= null
) {
1543 final int x
= (int) event
.getX();
1544 final int y
= (int) event
.getY();
1545 final Rect bounds
= rightDrawable
.getBounds();
1546 if (x
>= (view
.getRight() - bounds
.width() - fuzz
) && x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
)
1547 && y
>= (view
.getPaddingTop() - fuzz
) && y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1549 return onDrawableTouch(event
);
1555 public abstract boolean onDrawableTouch(final MotionEvent event
);
1559 public void onSamlDialogSuccess(String sessionCookie
){
1560 mAuthToken
= sessionCookie
;
1562 if (sessionCookie
!= null
&& sessionCookie
.length() > 0) {
1563 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1564 mAuthToken
= sessionCookie
;
1565 boolean success
= true
;
1566 if (mAction
== ACTION_CREATE
) {
1567 success
= createAccount();
1581 public void onSsoFinished(String sessionCookies
) {
1582 //Toast.makeText(this, "got cookies: " + sessionCookie, Toast.LENGTH_LONG).show();
1584 if (sessionCookies
!= null
&& sessionCookies
.length() > 0) {
1585 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1586 onSamlDialogSuccess(sessionCookies
);
1587 Fragment fd
= getSupportFragmentManager().findFragmentByTag(TAG_SAML_DIALOG
);
1588 if (fd
!= null
&& fd
instanceof SherlockDialogFragment
) {
1589 Dialog d
= ((SherlockDialogFragment
)fd
).getDialog();
1590 if (d
!= null
&& d
.isShowing()) {
1597 Log_OC
.d(TAG
, "SSO failed");
1602 /** Show auth_message
1606 private void showAuthMessage(String message
) {
1607 mAuthMessage
.setVisibility(View
.VISIBLE
);
1608 mAuthMessage
.setText(message
);
1611 private void hideAuthMessage() {
1612 mAuthMessage
.setVisibility(View
.GONE
);
1616 private void syncAccount(){
1617 /// immediately request for the synchronization of the new account
1618 Bundle bundle
= new Bundle();
1619 bundle
.putBoolean(ContentResolver
.SYNC_EXTRAS_MANUAL
, true
);
1620 ContentResolver
.requestSync(mAccount
, AccountAuthenticator
.AUTHORITY
, bundle
);