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
.security
.cert
.X509Certificate
;
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
.DialogInterface
;
29 import android
.content
.Intent
;
30 import android
.content
.SharedPreferences
;
31 import android
.graphics
.Rect
;
32 import android
.graphics
.drawable
.Drawable
;
33 import android
.net
.Uri
;
34 import android
.net
.http
.SslError
;
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
.support
.v4
.app
.FragmentManager
;
40 import android
.support
.v4
.app
.FragmentTransaction
;
41 import android
.text
.Editable
;
42 import android
.text
.InputType
;
43 import android
.text
.TextWatcher
;
44 import android
.view
.KeyEvent
;
45 import android
.view
.MotionEvent
;
46 import android
.view
.View
;
47 import android
.view
.View
.OnFocusChangeListener
;
48 import android
.view
.View
.OnTouchListener
;
49 import android
.view
.Window
;
50 import android
.view
.inputmethod
.EditorInfo
;
51 import android
.webkit
.SslErrorHandler
;
52 import android
.widget
.Button
;
53 import android
.widget
.CheckBox
;
54 import android
.widget
.EditText
;
55 import android
.widget
.TextView
;
56 import android
.widget
.TextView
.OnEditorActionListener
;
58 import com
.actionbarsherlock
.app
.SherlockDialogFragment
;
59 import com
.owncloud
.android
.MainApp
;
60 import com
.owncloud
.android
.R
;
61 import com
.owncloud
.android
.authentication
.SsoWebViewClient
.SsoWebViewClientListener
;
62 import com
.owncloud
.android
.lib
.common
.accounts
.AccountTypeUtils
;
63 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.Constants
;
64 import com
.owncloud
.android
.lib
.common
.OwnCloudClientFactory
;
65 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
66 import com
.owncloud
.android
.operations
.DetectAuthenticationMethodOperation
;
67 import com
.owncloud
.android
.operations
.DetectAuthenticationMethodOperation
.AuthenticationMethod
;
68 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
70 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
71 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
72 import com
.owncloud
.android
.lib
.resources
.status
.GetRemoteStatusOperation
;
73 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
74 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
75 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
76 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
77 import com
.owncloud
.android
.lib
.resources
.users
.GetRemoteUserNameOperation
;
79 import com
.owncloud
.android
.ui
.dialog
.SamlWebViewDialog
;
80 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
81 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
82 import com
.owncloud
.android
.utils
.Log_OC
;
83 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
86 * This Activity is used to add an ownCloud account to the App
88 * @author Bartek Przybylski
89 * @author David A. Velasco
91 public class AuthenticatorActivity
extends AccountAuthenticatorActivity
92 implements OnRemoteOperationListener
, OnFocusChangeListener
, OnEditorActionListener
,
93 SsoWebViewClientListener
, OnSslUntrustedCertListener
{
95 private static final String TAG
= AuthenticatorActivity
.class.getSimpleName();
97 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
98 public static final String EXTRA_USER_NAME
= "USER_NAME";
99 public static final String EXTRA_HOST_NAME
= "HOST_NAME";
100 public static final String EXTRA_ACTION
= "ACTION";
101 public static final String EXTRA_ENFORCED_UPDATE
= "ENFORCE_UPDATE";
103 private static final String KEY_AUTH_MESSAGE_VISIBILITY
= "AUTH_MESSAGE_VISIBILITY";
104 private static final String KEY_AUTH_MESSAGE_TEXT
= "AUTH_MESSAGE_TEXT";
105 private static final String KEY_HOST_URL_TEXT
= "HOST_URL_TEXT";
106 private static final String KEY_OC_VERSION
= "OC_VERSION";
107 private static final String KEY_OC_VERSION_STRING
= "OC_VERSION_STRING";
108 private static final String KEY_ACCOUNT
= "ACCOUNT";
109 private static final String KEY_SERVER_VALID
= "SERVER_VALID";
110 private static final String KEY_SERVER_CHECKED
= "SERVER_CHECKED";
111 private static final String KEY_SERVER_CHECK_IN_PROGRESS
= "SERVER_CHECK_IN_PROGRESS";
112 private static final String KEY_SERVER_STATUS_TEXT
= "SERVER_STATUS_TEXT";
113 private static final String KEY_SERVER_STATUS_ICON
= "SERVER_STATUS_ICON";
114 private static final String KEY_IS_SSL_CONN
= "IS_SSL_CONN";
115 private static final String KEY_PASSWORD_VISIBLE
= "PASSWORD_VISIBLE";
116 private static final String KEY_AUTH_STATUS_TEXT
= "AUTH_STATUS_TEXT";
117 private static final String KEY_AUTH_STATUS_ICON
= "AUTH_STATUS_ICON";
118 private static final String KEY_REFRESH_BUTTON_ENABLED
= "KEY_REFRESH_BUTTON_ENABLED";
119 //private static final String KEY_IS_SHARED_SUPPORTED = "KEY_IS_SHARE_SUPPORTED";
121 private static final String AUTH_ON
= "on";
122 private static final String AUTH_OFF
= "off";
123 private static final String AUTH_OPTIONAL
= "optional";
125 private static final int DIALOG_LOGIN_PROGRESS
= 0;
126 private static final int DIALOG_CERT_NOT_SAVED
= 1;
127 private static final int DIALOG_OAUTH2_LOGIN_PROGRESS
= 2;
129 public static final byte ACTION_CREATE
= 0;
130 public static final byte ACTION_UPDATE_TOKEN
= 1;
132 private static final String TAG_SAML_DIALOG
= "samlWebViewDialog";
134 private String mHostBaseUrl
;
135 private OwnCloudVersion mDiscoveredVersion
;
137 private String mAuthMessageText
;
138 private int mAuthMessageVisibility
, mServerStatusText
, mServerStatusIcon
;
139 private boolean mServerIsChecked
, mServerIsValid
, mIsSslConn
;
140 private int mAuthStatusText
, mAuthStatusIcon
;
141 private TextView mAuthStatusLayout
;
143 private final Handler mHandler
= new Handler();
144 private Thread mOperationThread
;
145 private GetRemoteStatusOperation mOcServerChkOperation
;
146 private ExistenceCheckRemoteOperation mAuthCheckOperation
;
148 private Uri mNewCapturedUriFromOAuth2Redirection
;
150 private AccountManager mAccountMgr
;
151 private boolean mJustCreated
;
152 private byte mAction
;
153 private Account mAccount
;
155 private TextView mAuthMessage
;
157 private EditText mHostUrlInput
;
158 private boolean mHostUrlInputEnabled
;
159 private View mRefreshButton
;
161 private String mAuthTokenType
;
163 private EditText mUsernameInput
;
164 private EditText mPasswordInput
;
166 private CheckBox mOAuth2Check
;
168 private TextView mOAuthAuthEndpointText
;
169 private TextView mOAuthTokenEndpointText
;
171 private SamlWebViewDialog mSamlDialog
;
173 private View mOkButton
;
175 private String mAuthToken
;
177 private boolean mResumed
; // Control if activity is resumed
179 public static String DIALOG_UNTRUSTED_CERT
= "DIALOG_UNTRUSTED_CERT";
181 private DetectAuthenticationMethodOperation mDetectAuthenticationOperation
;
187 * IMPORTANT ENTRY POINT 1: activity is shown to the user
190 protected void onCreate(Bundle savedInstanceState
) {
191 super.onCreate(savedInstanceState
);
192 getWindow().requestFeature(Window
.FEATURE_NO_TITLE
);
194 /// set view and get references to view elements
195 setContentView(R
.layout
.account_setup
);
196 mAuthMessage
= (TextView
) findViewById(R
.id
.auth_message
);
197 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
198 mHostUrlInput
.setText(getString(R
.string
.server_url
)); // valid although R.string.server_url is an empty string
199 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
200 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
201 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
202 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
203 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
204 mOkButton
= findViewById(R
.id
.buttonOK
);
205 mAuthStatusLayout
= (TextView
) findViewById(R
.id
.auth_status_text
);
207 /// set Host Url Input Enabled
208 mHostUrlInputEnabled
= getResources().getBoolean(R
.bool
.show_server_url_input
);
210 /// set visibility of link for new users
211 boolean accountRegisterVisibility
= getResources().getBoolean(R
.bool
.show_welcome_link
);
212 Button welcomeLink
= (Button
) findViewById(R
.id
.welcome_link
);
213 if (welcomeLink
!= null
) {
214 if (accountRegisterVisibility
) {
215 welcomeLink
.setVisibility(View
.VISIBLE
);
216 welcomeLink
.setText(String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
218 findViewById(R
.id
.welcome_link
).setVisibility(View
.GONE
);
223 mAccountMgr
= AccountManager
.get(this);
224 mNewCapturedUriFromOAuth2Redirection
= null
;
225 mAction
= getIntent().getByteExtra(EXTRA_ACTION
, ACTION_CREATE
);
228 boolean refreshButtonEnabled
= false
;
230 // URL input configuration applied
231 if (!mHostUrlInputEnabled
)
233 findViewById(R
.id
.hostUrlFrame
).setVisibility(View
.GONE
);
234 mRefreshButton
= findViewById(R
.id
.centeredRefreshButton
);
237 mRefreshButton
= findViewById(R
.id
.embeddedRefreshButton
);
240 if (savedInstanceState
== null
) {
242 /// connection state and info
243 mAuthMessageVisibility
= View
.GONE
;
244 mServerStatusText
= mServerStatusIcon
= 0;
245 mServerIsValid
= false
;
246 mServerIsChecked
= false
;
248 mAuthStatusText
= mAuthStatusIcon
= 0;
250 /// retrieve extras from intent
251 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
252 if (mAccount
!= null
) {
253 String ocVersion
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_VERSION
);
254 String ocVersionString
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_VERSION_STRING
);
255 if (ocVersion
!= null
) {
256 mDiscoveredVersion
= new OwnCloudVersion(ocVersion
, ocVersionString
);
258 mHostBaseUrl
= normalizeUrl(mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_BASE_URL
));
259 mHostUrlInput
.setText(mHostBaseUrl
);
260 String userName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
261 mUsernameInput
.setText(userName
);
264 initAuthorizationMethod(); // checks intent and setup.xml to determine mCurrentAuthorizationMethod
267 if (mAction
== ACTION_UPDATE_TOKEN
|| !mHostUrlInputEnabled
) {
273 /// connection state and info
274 mAuthMessageVisibility
= savedInstanceState
.getInt(KEY_AUTH_MESSAGE_VISIBILITY
);
275 mAuthMessageText
= savedInstanceState
.getString(KEY_AUTH_MESSAGE_TEXT
);
276 mServerIsValid
= savedInstanceState
.getBoolean(KEY_SERVER_VALID
);
277 mServerIsChecked
= savedInstanceState
.getBoolean(KEY_SERVER_CHECKED
);
278 mServerStatusText
= savedInstanceState
.getInt(KEY_SERVER_STATUS_TEXT
);
279 mServerStatusIcon
= savedInstanceState
.getInt(KEY_SERVER_STATUS_ICON
);
280 mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
281 mAuthStatusText
= savedInstanceState
.getInt(KEY_AUTH_STATUS_TEXT
);
282 mAuthStatusIcon
= savedInstanceState
.getInt(KEY_AUTH_STATUS_ICON
);
283 if (savedInstanceState
.getBoolean(KEY_PASSWORD_VISIBLE
, false
)) {
288 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
289 String ocVersionString
= savedInstanceState
.getString(KEY_OC_VERSION_STRING
);
290 if (ocVersion
!= null
) {
291 mDiscoveredVersion
= new OwnCloudVersion(ocVersion
, ocVersionString
);
293 mHostBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
295 // account data, if updating
296 mAccount
= savedInstanceState
.getParcelable(KEY_ACCOUNT
);
297 mAuthTokenType
= savedInstanceState
.getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
298 if (mAuthTokenType
== null
) {
299 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
303 // check if server check was interrupted by a configuration change
304 if (savedInstanceState
.getBoolean(KEY_SERVER_CHECK_IN_PROGRESS
, false
)) {
308 // refresh button enabled
309 refreshButtonEnabled
= savedInstanceState
.getBoolean(KEY_REFRESH_BUTTON_ENABLED
);
314 if (mAuthMessageVisibility
== View
.VISIBLE
) {
315 showAuthMessage(mAuthMessageText
);
320 adaptViewAccordingToAuthenticationMethod();
324 if (mAction
== ACTION_UPDATE_TOKEN
) {
325 /// lock things that should not change
326 mHostUrlInput
.setEnabled(false
);
327 mHostUrlInput
.setFocusable(false
);
328 mUsernameInput
.setEnabled(false
);
329 mUsernameInput
.setFocusable(false
);
330 mOAuth2Check
.setVisibility(View
.GONE
);
333 //if (mServerIsChecked && !mServerIsValid && mRefreshButtonEnabled) showRefreshButton();
334 if (mServerIsChecked
&& !mServerIsValid
&& refreshButtonEnabled
) showRefreshButton();
335 mOkButton
.setEnabled(mServerIsValid
); // state not automatically recovered in configuration changes
337 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
) ||
338 !AUTH_OPTIONAL
.equals(getString(R
.string
.auth_method_oauth2
))) {
339 mOAuth2Check
.setVisibility(View
.GONE
);
342 mPasswordInput
.setText(""); // clean password to avoid social hacking (disadvantage: password in removed if the device is turned aside)
344 /// bind view elements to listeners and other friends
345 mHostUrlInput
.setOnFocusChangeListener(this);
346 mHostUrlInput
.setImeOptions(EditorInfo
.IME_ACTION_NEXT
);
347 mHostUrlInput
.setOnEditorActionListener(this);
348 mHostUrlInput
.addTextChangedListener(new TextWatcher() {
351 public void afterTextChanged(Editable s
) {
352 if (!mHostBaseUrl
.equals(normalizeUrl(mHostUrlInput
.getText().toString()))) {
353 mOkButton
.setEnabled(false
);
358 public void beforeTextChanged(CharSequence s
, int start
, int count
, int after
) {
362 public void onTextChanged(CharSequence s
, int start
, int before
, int count
) {
372 mPasswordInput
.setOnFocusChangeListener(this);
373 mPasswordInput
.setImeOptions(EditorInfo
.IME_ACTION_DONE
);
374 mPasswordInput
.setOnEditorActionListener(this);
375 mPasswordInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
377 public boolean onDrawableTouch(final MotionEvent event
) {
378 if (event
.getAction() == MotionEvent
.ACTION_UP
) {
379 AuthenticatorActivity
.this.onViewPasswordClick();
385 findViewById(R
.id
.scroll
).setOnTouchListener(new OnTouchListener() {
387 public boolean onTouch(View view
, MotionEvent event
) {
388 if (event
.getAction() == MotionEvent
.ACTION_DOWN
) {
389 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
) &&
390 mHostUrlInput
.hasFocus()) {
401 private void initAuthorizationMethod() {
402 boolean oAuthRequired
= false
;
403 boolean samlWebSsoRequired
= false
;
405 mAuthTokenType
= getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
406 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
408 // TODO could be a good moment to validate the received token type, if not null
410 if (mAuthTokenType
== null
) {
411 if (mAccount
!= null
) {
412 /// same authentication method than the one used to create the account to update
413 oAuthRequired
= (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
) != null
);
414 samlWebSsoRequired
= (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
) != null
);
417 /// use the one set in setup.xml
418 oAuthRequired
= AUTH_ON
.equals(getString(R
.string
.auth_method_oauth2
));
419 samlWebSsoRequired
= AUTH_ON
.equals(getString(R
.string
.auth_method_saml_web_sso
));
422 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
423 } else if (samlWebSsoRequired
) {
424 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
426 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
430 if (mAccount
!= null
) {
431 String userName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
432 mUsernameInput
.setText(userName
);
435 mOAuth2Check
.setChecked(AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
));
440 * Saves relevant state before {@link #onPause()}
442 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag, intended to defer the
443 * processing of the redirection caught in {@link #onNewIntent(Intent)} until {@link #onResume()}
445 * See {@link #loadSavedInstanceState(Bundle)}
448 protected void onSaveInstanceState(Bundle outState
) {
449 super.onSaveInstanceState(outState
);
451 /// connection state and info
452 outState
.putInt(KEY_AUTH_MESSAGE_VISIBILITY
, mAuthMessage
.getVisibility());
453 outState
.putString(KEY_AUTH_MESSAGE_TEXT
, mAuthMessage
.getText().toString());
454 outState
.putInt(KEY_SERVER_STATUS_TEXT
, mServerStatusText
);
455 outState
.putInt(KEY_SERVER_STATUS_ICON
, mServerStatusIcon
);
456 outState
.putBoolean(KEY_SERVER_VALID
, mServerIsValid
);
457 outState
.putBoolean(KEY_SERVER_CHECKED
, mServerIsChecked
);
458 outState
.putBoolean(KEY_SERVER_CHECK_IN_PROGRESS
, (!mServerIsValid
&& mOcServerChkOperation
!= null
));
459 outState
.putBoolean(KEY_IS_SSL_CONN
, mIsSslConn
);
460 outState
.putBoolean(KEY_PASSWORD_VISIBLE
, isPasswordVisible());
461 outState
.putInt(KEY_AUTH_STATUS_ICON
, mAuthStatusIcon
);
462 outState
.putInt(KEY_AUTH_STATUS_TEXT
, mAuthStatusText
);
465 if (mDiscoveredVersion
!= null
) {
466 outState
.putString(KEY_OC_VERSION
, mDiscoveredVersion
.getVersion());
467 outState
.putString(KEY_OC_VERSION_STRING
, mDiscoveredVersion
.getVersionString());
469 outState
.putString(KEY_HOST_URL_TEXT
, mHostBaseUrl
);
471 /// account data, if updating
472 if (mAccount
!= null
) {
473 outState
.putParcelable(KEY_ACCOUNT
, mAccount
);
475 outState
.putString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
, mAuthTokenType
);
477 // refresh button enabled
478 outState
.putBoolean(KEY_REFRESH_BUTTON_ENABLED
, (mRefreshButton
.getVisibility() == View
.VISIBLE
));
485 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION request
488 * To make this possible, this activity needs to be qualified with android:launchMode = "singleTask" in the
489 * AndroidManifest.xml file.
492 protected void onNewIntent (Intent intent
) {
493 Log_OC
.d(TAG
, "onNewIntent()");
494 Uri data
= intent
.getData();
495 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
496 mNewCapturedUriFromOAuth2Redirection
= data
;
502 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION, and
503 * deferred in {@link #onNewIntent(Intent)}, is processed here.
506 protected void onResume() {
508 if (mAction
== ACTION_UPDATE_TOKEN
&& mJustCreated
&& getIntent().getBooleanExtra(EXTRA_ENFORCED_UPDATE
, false
)) {
509 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
510 //Toast.makeText(this, R.string.auth_expired_oauth_token_toast, Toast.LENGTH_LONG).show();
511 showAuthMessage(getString(R
.string
.auth_expired_oauth_token_toast
));
512 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
513 //Toast.makeText(this, R.string.auth_expired_saml_sso_token_toast, Toast.LENGTH_LONG).show();
514 showAuthMessage(getString(R
.string
.auth_expired_saml_sso_token_toast
));
516 //Toast.makeText(this, R.string.auth_expired_basic_auth_toast, Toast.LENGTH_LONG).show();
517 showAuthMessage(getString(R
.string
.auth_expired_basic_auth_toast
));
521 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
522 getOAuth2AccessTokenFromCapturedRedirection();
525 mJustCreated
= false
;
531 * Parses the redirection with the response to the GET AUTHORIZATION request to the
532 * oAuth server and requests for the access token (GET ACCESS TOKEN)
534 private void getOAuth2AccessTokenFromCapturedRedirection() {
535 /// Parse data from OAuth redirection
536 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
537 mNewCapturedUriFromOAuth2Redirection
= null
;
539 /// Showing the dialog with instructions for the user.
540 showDialog(DIALOG_OAUTH2_LOGIN_PROGRESS
);
542 /// GET ACCESS TOKEN to the oAuth server
543 RemoteOperation operation
= new OAuth2GetAccessToken( getString(R
.string
.oauth2_client_id
),
544 getString(R
.string
.oauth2_redirect_uri
),
545 getString(R
.string
.oauth2_grant_type
),
547 //OwnCloudClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(getString(R.string.oauth2_url_endpoint_access)), getApplicationContext());
548 OwnCloudClient client
= OwnCloudClientFactory
.createOwnCloudClient(Uri
.parse(mOAuthTokenEndpointText
.getText().toString().trim()), getApplicationContext(), true
);
549 operation
.execute(client
, this, mHandler
);
555 * Handles the change of focus on the text inputs for the server URL and the password
557 public void onFocusChange(View view
, boolean hasFocus
) {
558 if (view
.getId() == R
.id
.hostUrlInput
) {
560 onUrlInputFocusLost((TextView
) view
);
566 } else if (view
.getId() == R
.id
.account_password
) {
567 onPasswordFocusChanged((TextView
) view
, hasFocus
);
573 * Handles changes in focus on the text input for the server URL.
575 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
576 * other field. The operation to check the existence of the server in the entered URL is
579 * When hasFocus: user 'comes back' to write again the server URL.
581 * @param hostInput TextView with the URL input field receiving the change of focus.
583 private void onUrlInputFocusLost(TextView hostInput
) {
584 if (!mHostBaseUrl
.equals(normalizeUrl(mHostUrlInput
.getText().toString()))) {
587 mOkButton
.setEnabled(mServerIsValid
);
588 if (!mServerIsValid
) {
595 private void checkOcServer() {
596 String uri
= trimUrlWebdav(mHostUrlInput
.getText().toString().trim());
598 if (!mHostUrlInputEnabled
){
599 uri
= getString(R
.string
.server_url
);
602 mServerIsValid
= false
;
603 mServerIsChecked
= false
;
604 mOkButton
.setEnabled(false
);
605 mDiscoveredVersion
= null
;
607 if (uri
.length() != 0) {
608 mServerStatusText
= R
.string
.auth_testing_connection
;
609 mServerStatusIcon
= R
.drawable
.progress_small
;
611 mOcServerChkOperation
= new GetRemoteStatusOperation(uri
, this);
612 OwnCloudClient client
= OwnCloudClientFactory
.createOwnCloudClient(Uri
.parse(uri
), this, true
);
613 mOperationThread
= mOcServerChkOperation
.execute(client
, this, mHandler
);
615 mServerStatusText
= 0;
616 mServerStatusIcon
= 0;
623 * Handles changes in focus on the text input for the password (basic authorization).
625 * When (hasFocus), the button to toggle password visibility is shown.
627 * When (!hasFocus), the button is made invisible and the password is hidden.
629 * @param passwordInput TextView with the password input field receiving the change of focus.
630 * @param hasFocus 'True' if focus is received, 'false' if is lost
632 private void onPasswordFocusChanged(TextView passwordInput
, boolean hasFocus
) {
634 showViewPasswordButton();
637 hidePasswordButton();
642 private void showViewPasswordButton() {
643 //int drawable = android.R.drawable.ic_menu_view;
644 int drawable
= R
.drawable
.ic_view
;
645 if (isPasswordVisible()) {
646 //drawable = android.R.drawable.ic_secure;
647 drawable
= R
.drawable
.ic_hide
;
649 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable
, 0);
652 private boolean isPasswordVisible() {
653 return ((mPasswordInput
.getInputType() & InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) == InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
656 private void hidePasswordButton() {
657 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
660 private void showPassword() {
661 mPasswordInput
.setInputType(InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
662 showViewPasswordButton();
665 private void hidePassword() {
666 mPasswordInput
.setInputType(InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
);
667 showViewPasswordButton();
672 * Cancels the authenticator activity
674 * IMPORTANT ENTRY POINT 3: Never underestimate the importance of cancellation
676 * This method is bound in the layout/acceoun_setup.xml resource file.
678 * @param view Cancel button
680 public void onCancelClick(View view
) {
681 setResult(RESULT_CANCELED
); // TODO review how is this related to AccountAuthenticator (debugging)
688 * Checks the credentials of the user in the root of the ownCloud server
689 * before creating a new local account.
691 * For basic authorization, a check of existence of the root folder is
694 * For OAuth, starts the flow to get an access token; the credentials test
695 * is postponed until it is available.
697 * IMPORTANT ENTRY POINT 4
699 * @param view OK button
701 public void onOkClick(View view
) {
702 // this check should be unnecessary
703 if (mDiscoveredVersion
== null
|| !mDiscoveredVersion
.isVersionValid() || mHostBaseUrl
== null
|| mHostBaseUrl
.length() == 0) {
704 mServerStatusIcon
= R
.drawable
.common_error
;
705 mServerStatusText
= R
.string
.auth_wtf_reenter_URL
;
707 mOkButton
.setEnabled(false
);
708 Log_OC
.wtf(TAG
, "The user was allowed to click 'connect' to an unchecked server!!");
712 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
713 startOauthorization();
714 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
715 startSamlBasedFederatedSingleSignOnAuthorization();
717 checkBasicAuthorization();
723 * Tests the credentials entered by the user performing a check of existence on
724 * the root folder of the ownCloud server.
726 private void checkBasicAuthorization() {
727 /// get the path to the root folder through WebDAV from the version server
728 String webdav_path
= AccountUtils
.getWebdavPath(mDiscoveredVersion
, mAuthTokenType
);
730 /// get basic credentials entered by user
731 String username
= mUsernameInput
.getText().toString();
732 String password
= mPasswordInput
.getText().toString();
734 /// be gentle with the user
735 showDialog(DIALOG_LOGIN_PROGRESS
);
737 /// test credentials accessing the root folder
738 mAuthCheckOperation
= new ExistenceCheckRemoteOperation("", this, false
);
739 OwnCloudClient client
= OwnCloudClientFactory
.createOwnCloudClient(Uri
.parse(mHostBaseUrl
+ webdav_path
), this, true
);
740 client
.setBasicCredentials(username
, password
);
741 mOperationThread
= mAuthCheckOperation
.execute(client
, this, mHandler
);
746 * Starts the OAuth 'grant type' flow to get an access token, with
747 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
749 private void startOauthorization() {
750 // be gentle with the user
751 mAuthStatusIcon
= R
.drawable
.progress_small
;
752 mAuthStatusText
= R
.string
.oauth_login_connection
;
756 // GET AUTHORIZATION request
757 //Uri uri = Uri.parse(getString(R.string.oauth2_url_endpoint_auth));
758 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
759 Uri
.Builder uriBuilder
= uri
.buildUpon();
760 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
));
761 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
));
762 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
));
763 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
));
764 //uriBuilder.appendQueryParameter(OAuth2Constants.KEY_STATE, whateverwewant);
765 uri
= uriBuilder
.build();
766 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
767 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
773 * Starts the Web Single Sign On flow to get access to the root folder
776 private void startSamlBasedFederatedSingleSignOnAuthorization() {
777 // be gentle with the user
778 mAuthStatusIcon
= R
.drawable
.progress_small
;
779 mAuthStatusText
= R
.string
.auth_connecting_auth_server
;
781 showDialog(DIALOG_LOGIN_PROGRESS
);
783 /// get the path to the root folder through WebDAV from the version server
784 String webdav_path
= AccountUtils
.getWebdavPath(mDiscoveredVersion
, mAuthTokenType
);
786 /// test credentials accessing the root folder
787 mAuthCheckOperation
= new ExistenceCheckRemoteOperation("", this, false
);
788 OwnCloudClient client
= OwnCloudClientFactory
.createOwnCloudClient(Uri
.parse(mHostBaseUrl
+ webdav_path
), this, false
);
789 mOperationThread
= mAuthCheckOperation
.execute(client
, this, mHandler
);
794 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
796 * Dispatches the operation flow to the right method.
799 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
801 if (operation
instanceof GetRemoteStatusOperation
) {
802 onOcServerCheckFinish((GetRemoteStatusOperation
) operation
, result
);
804 } else if (operation
instanceof OAuth2GetAccessToken
) {
805 onGetOAuthAccessTokenFinish((OAuth2GetAccessToken
)operation
, result
);
807 } else if (operation
instanceof ExistenceCheckRemoteOperation
) {
808 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
809 onSamlBasedFederatedSingleSignOnAuthorizationStart(operation
, result
);
812 onAuthorizationCheckFinish((ExistenceCheckRemoteOperation
)operation
, result
);
814 } else if (operation
instanceof GetRemoteUserNameOperation
) {
815 onGetUserNameFinish((GetRemoteUserNameOperation
) operation
, result
);
817 } else if (operation
instanceof DetectAuthenticationMethodOperation
) {
818 onDetectAutheticationFinish((DetectAuthenticationMethodOperation
) operation
, result
);
823 private void onDetectAutheticationFinish(DetectAuthenticationMethodOperation operation
, RemoteOperationResult result
) {
824 // Read authentication method
825 if (result
.getData().size() > 0) {
826 AuthenticationMethod authMethod
= (AuthenticationMethod
) result
.getData().get(0);
827 String basic
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
828 String oAuth
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
829 String saml
= AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
831 if ( ( mAuthTokenType
.equals(basic
) && !authMethod
.equals(AuthenticationMethod
.BASIC_HTTP_AUTH
) ) ||
832 ( mAuthTokenType
.equals(oAuth
) && !authMethod
.equals(AuthenticationMethod
.BEARER_TOKEN
) ) ||
833 ( mAuthTokenType
.equals(saml
) && !authMethod
.equals(AuthenticationMethod
.SAML_WEB_SSO
) ) ) {
835 mOkButton
.setEnabled(false
);
836 mServerIsValid
= false
;
837 //show an alert message ( Server Status )
838 updateServerStatusIconNoRegularAuth();
842 mOkButton
.setEnabled(true
);
844 // Show server status
853 private void onGetUserNameFinish(GetRemoteUserNameOperation operation
, RemoteOperationResult result
) {
855 if (result
.isSuccess()) {
856 boolean success
= false
;
857 String username
= operation
.getUserName();
859 if ( mAction
== ACTION_CREATE
) {
860 mUsernameInput
.setText(username
);
861 success
= createAccount();
864 if (!mUsernameInput
.getText().toString().equals(username
)) {
865 // fail - not a new account, but an existing one; disallow
866 result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_THE_SAME
);
867 updateAuthStatusIconAndText(result
);
869 Log_OC
.d(TAG
, result
.getLogMessage());
879 updateStatusIconFailUserName();
881 Log_OC
.e(TAG
, "Access to user name failed: " + result
.getLogMessage());
886 private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperation operation
, RemoteOperationResult result
) {
888 dismissDialog(DIALOG_LOGIN_PROGRESS
);
889 } catch (IllegalArgumentException e
) {
890 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
893 //if (result.isTemporalRedirection() && result.isIdPRedirection()) {
894 if (result
.isIdPRedirection()) {
895 String url
= result
.getRedirectedLocation();
896 String targetUrl
= mHostBaseUrl
+ AccountUtils
.getWebdavPath(mDiscoveredVersion
, mAuthTokenType
);
899 mSamlDialog
= SamlWebViewDialog
.newInstance(url
, targetUrl
);
900 mSamlDialog
.show(getSupportFragmentManager(), TAG_SAML_DIALOG
);
906 mAuthStatusIcon
= R
.drawable
.common_error
;
907 mAuthStatusText
= R
.string
.auth_unsupported_auth_method
;
915 * Processes the result of the server check performed when the user finishes the enter of the
918 * @param operation Server check performed.
919 * @param result Result of the check.
921 private void onOcServerCheckFinish(GetRemoteStatusOperation operation
, RemoteOperationResult result
) {
922 if (operation
.equals(mOcServerChkOperation
)) {
923 /// save result state
924 mServerIsChecked
= true
;
925 mServerIsValid
= result
.isSuccess();
926 mIsSslConn
= (result
.getCode() == ResultCode
.OK_SSL
);
927 mOcServerChkOperation
= null
;
930 /// retrieve discovered version and normalize server URL
931 mDiscoveredVersion
= operation
.getDiscoveredVersion();
932 mHostBaseUrl
= normalizeUrl(mHostUrlInput
.getText().toString());
934 // Refresh server status, but don't show it
935 updateServerStatusIconAndText(result
);
937 /// update status icon and text
938 if (mServerIsValid
) {
940 // Try to create an account with user and pass "", to know if it is a regular server
941 // Update connect button in the answer of this method
942 detectAuthorizationMethod();
945 // Show server status
949 /// very special case (TODO: move to a common place for all the remote operations)
950 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
951 showUntrustedCertDialog(result
);
955 } // else nothing ; only the last check operation is considered;
956 // multiple can be triggered if the user amends a URL before a previous check can be triggered
961 * Try to access with user/pass ""/"", to know if it is a regular server
963 private void detectAuthorizationMethod() {
965 Log_OC
.d(TAG
, "Trying empty authorization to detect authentication method");
967 /// get the path to the root folder through WebDAV from the version server
968 String webdav_path
= AccountUtils
.getWebdavPath(mDiscoveredVersion
, mAuthTokenType
);
971 mDetectAuthenticationOperation
= new DetectAuthenticationMethodOperation(this);
972 OwnCloudClient client
= OwnCloudClientFactory
.createOwnCloudClient(Uri
.parse(mHostBaseUrl
+ webdav_path
), this, true
);
973 mOperationThread
= mDetectAuthenticationOperation
.execute(client
, this, mHandler
);
977 private String
normalizeUrl(String url
) {
978 if (url
!= null
&& url
.length() > 0) {
980 if (!url
.toLowerCase().startsWith("http://") &&
981 !url
.toLowerCase().startsWith("https://")) {
983 url
= "https://" + url
;
985 url
= "http://" + url
;
989 // OC-208: Add suffix remote.php/webdav to normalize (OC-34)
990 url
= trimUrlWebdav(url
);
992 if (url
.endsWith("/")) {
993 url
= url
.substring(0, url
.length() - 1);
997 return (url
!= null ? url
: "");
1001 private String
trimUrlWebdav(String url
){
1002 if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_4_0
)){
1003 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_4_0
.length());
1004 } else if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_2_0
)){
1005 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_2_0
.length());
1006 } else if (url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_1_2
)){
1007 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_1_2
.length());
1009 return (url
!= null ? url
: "");
1014 * Chooses the right icon and text to show to the user for the received operation result.
1016 * @param result Result of a remote operation performed in this activity
1018 private void updateServerStatusIconAndText(RemoteOperationResult result
) {
1019 mServerStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1021 switch (result
.getCode()) {
1023 mServerStatusIcon
= android
.R
.drawable
.ic_secure
;
1024 mServerStatusText
= R
.string
.auth_secure_connection
;
1029 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1030 mServerStatusText
= R
.string
.auth_connection_established
;
1031 mServerStatusIcon
= R
.drawable
.ic_ok
;
1033 mServerStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1034 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1038 case NO_NETWORK_CONNECTION
:
1039 mServerStatusIcon
= R
.drawable
.no_network
;
1040 mServerStatusText
= R
.string
.auth_no_net_conn_title
;
1043 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1044 mServerStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1046 case BAD_OC_VERSION
:
1047 mServerStatusText
= R
.string
.auth_bad_oc_version_title
;
1049 case WRONG_CONNECTION
:
1050 mServerStatusText
= R
.string
.auth_wrong_connection_title
;
1053 mServerStatusText
= R
.string
.auth_timeout_title
;
1055 case INCORRECT_ADDRESS
:
1056 mServerStatusText
= R
.string
.auth_incorrect_address_title
;
1059 mServerStatusText
= R
.string
.auth_ssl_general_error_title
;
1062 mServerStatusText
= R
.string
.auth_unauthorized
;
1064 case HOST_NOT_AVAILABLE
:
1065 mServerStatusText
= R
.string
.auth_unknown_host_title
;
1067 case INSTANCE_NOT_CONFIGURED
:
1068 mServerStatusText
= R
.string
.auth_not_configured_title
;
1070 case FILE_NOT_FOUND
:
1071 mServerStatusText
= R
.string
.auth_incorrect_path_title
;
1074 mServerStatusText
= R
.string
.auth_oauth_error
;
1076 case OAUTH2_ERROR_ACCESS_DENIED
:
1077 mServerStatusText
= R
.string
.auth_oauth_error_access_denied
;
1079 case UNHANDLED_HTTP_CODE
:
1081 mServerStatusText
= R
.string
.auth_unknown_error_title
;
1084 mServerStatusText
= 0;
1085 mServerStatusIcon
= 0;
1091 * Chooses the right icon and text to show to the user for the received operation result.
1093 * @param result Result of a remote operation performed in this activity
1095 private void updateAuthStatusIconAndText(RemoteOperationResult result
) {
1096 mAuthStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1098 switch (result
.getCode()) {
1100 mAuthStatusIcon
= android
.R
.drawable
.ic_secure
;
1101 mAuthStatusText
= R
.string
.auth_secure_connection
;
1106 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1107 mAuthStatusText
= R
.string
.auth_connection_established
;
1108 mAuthStatusIcon
= R
.drawable
.ic_ok
;
1110 mAuthStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1111 mAuthStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1115 case NO_NETWORK_CONNECTION
:
1116 mAuthStatusIcon
= R
.drawable
.no_network
;
1117 mAuthStatusText
= R
.string
.auth_no_net_conn_title
;
1120 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1121 mAuthStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1123 case BAD_OC_VERSION
:
1124 mAuthStatusText
= R
.string
.auth_bad_oc_version_title
;
1126 case WRONG_CONNECTION
:
1127 mAuthStatusText
= R
.string
.auth_wrong_connection_title
;
1130 mAuthStatusText
= R
.string
.auth_timeout_title
;
1132 case INCORRECT_ADDRESS
:
1133 mAuthStatusText
= R
.string
.auth_incorrect_address_title
;
1136 mAuthStatusText
= R
.string
.auth_ssl_general_error_title
;
1139 mAuthStatusText
= R
.string
.auth_unauthorized
;
1141 case HOST_NOT_AVAILABLE
:
1142 mAuthStatusText
= R
.string
.auth_unknown_host_title
;
1144 case INSTANCE_NOT_CONFIGURED
:
1145 mAuthStatusText
= R
.string
.auth_not_configured_title
;
1147 case FILE_NOT_FOUND
:
1148 mAuthStatusText
= R
.string
.auth_incorrect_path_title
;
1151 mAuthStatusText
= R
.string
.auth_oauth_error
;
1153 case OAUTH2_ERROR_ACCESS_DENIED
:
1154 mAuthStatusText
= R
.string
.auth_oauth_error_access_denied
;
1156 case ACCOUNT_NOT_NEW
:
1157 mAuthStatusText
= R
.string
.auth_account_not_new
;
1159 case ACCOUNT_NOT_THE_SAME
:
1160 mAuthStatusText
= R
.string
.auth_account_not_the_same
;
1162 case UNHANDLED_HTTP_CODE
:
1164 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
1167 mAuthStatusText
= 0;
1168 mAuthStatusIcon
= 0;
1173 private void updateStatusIconFailUserName(){
1174 mAuthStatusIcon
= R
.drawable
.common_error
;
1175 mAuthStatusText
= R
.string
.auth_fail_get_user_name
;
1178 private void updateServerStatusIconNoRegularAuth(){
1179 mServerStatusIcon
= R
.drawable
.common_error
;
1180 mServerStatusText
= R
.string
.auth_can_not_auth_against_server
;
1184 * Processes the result of the request for and access token send
1185 * to an OAuth authorization server.
1187 * @param operation Operation performed requesting the access token.
1188 * @param result Result of the operation.
1190 private void onGetOAuthAccessTokenFinish(OAuth2GetAccessToken operation
, RemoteOperationResult result
) {
1192 dismissDialog(DIALOG_OAUTH2_LOGIN_PROGRESS
);
1193 } catch (IllegalArgumentException e
) {
1194 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
1197 String webdav_path
= AccountUtils
.getWebdavPath(mDiscoveredVersion
, mAuthTokenType
);
1198 if (result
.isSuccess() && webdav_path
!= null
) {
1199 /// be gentle with the user
1200 showDialog(DIALOG_LOGIN_PROGRESS
);
1202 /// time to test the retrieved access token on the ownCloud server
1203 mAuthToken
= ((OAuth2GetAccessToken
)operation
).getResultTokenMap().get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
1204 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mAuthToken
);
1205 mAuthCheckOperation
= new ExistenceCheckRemoteOperation("", this, false
);
1206 OwnCloudClient client
= OwnCloudClientFactory
.createOwnCloudClient(Uri
.parse(mHostBaseUrl
+ webdav_path
), this, true
);
1207 client
.setBearerCredentials(mAuthToken
);
1208 mAuthCheckOperation
.execute(client
, this, mHandler
);
1211 updateAuthStatusIconAndText(result
);
1213 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1219 * Processes the result of the access check performed to try the user credentials.
1221 * Creates a new account through the AccountManager.
1223 * @param operation Access check performed.
1224 * @param result Result of the operation.
1226 private void onAuthorizationCheckFinish(ExistenceCheckRemoteOperation operation
, RemoteOperationResult result
) {
1228 dismissDialog(DIALOG_LOGIN_PROGRESS
);
1229 } catch (IllegalArgumentException e
) {
1230 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
1233 if (result
.isSuccess()) {
1234 Log_OC
.d(TAG
, "Successful access - time to save the account");
1236 boolean success
= false
;
1237 if (mAction
== ACTION_CREATE
) {
1238 success
= createAccount();
1249 } else if (result
.isServerFail() || result
.isException()) {
1250 /// if server fail or exception in authorization, the UI is updated as when a server check failed
1251 mServerIsChecked
= true
;
1252 mServerIsValid
= false
;
1254 mOcServerChkOperation
= null
;
1255 mDiscoveredVersion
= null
;
1256 mHostBaseUrl
= normalizeUrl(mHostUrlInput
.getText().toString());
1258 // update status icon and text
1259 updateServerStatusIconAndText(result
);
1261 mAuthStatusIcon
= 0;
1262 mAuthStatusText
= 0;
1265 // update input controls state
1266 showRefreshButton();
1267 mOkButton
.setEnabled(false
);
1269 // very special case (TODO: move to a common place for all the remote operations) (dangerous here?)
1270 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1271 showUntrustedCertDialog(result
);
1274 } else { // authorization fail due to client side - probably wrong credentials
1275 updateAuthStatusIconAndText(result
);
1277 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1285 * Sets the proper response to get that the Account Authenticator that started this activity saves
1286 * a new authorization token for mAccount.
1288 private void updateToken() {
1289 Bundle response
= new Bundle();
1290 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1291 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
1293 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
1294 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1295 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1296 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1298 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
1300 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1301 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1302 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1305 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
1306 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
1308 setAccountAuthenticatorResult(response
);
1314 * Creates a new account through the Account Authenticator that started this activity.
1316 * This makes the account permanent.
1318 * TODO Decide how to name the OAuth accounts
1320 private boolean createAccount() {
1321 /// create and save new ownCloud account
1322 boolean isOAuth
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
);
1323 boolean isSaml
= AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
);
1325 Uri uri
= Uri
.parse(mHostBaseUrl
);
1326 String username
= mUsernameInput
.getText().toString().trim();
1328 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1330 String accountName
= username
+ "@" + uri
.getHost();
1331 if (uri
.getPort() >= 0) {
1332 accountName
+= ":" + uri
.getPort();
1334 mAccount
= new Account(accountName
, MainApp
.getAccountType());
1335 if (AccountUtils
.exists(mAccount
, getApplicationContext())) {
1336 // fail - not a new account, but an existing one; disallow
1337 RemoteOperationResult result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_NEW
);
1338 updateAuthStatusIconAndText(result
);
1340 Log_OC
.d(TAG
, result
.getLogMessage());
1345 if (isOAuth
|| isSaml
) {
1346 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
); // with external authorizations, the password is never input in the app
1348 mAccountMgr
.addAccountExplicitly(mAccount
, mPasswordInput
.getText().toString(), null
);
1351 /// add the new account as default in preferences, if there is none already
1352 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1353 if (defaultAccount
== null
) {
1354 SharedPreferences
.Editor editor
= PreferenceManager
1355 .getDefaultSharedPreferences(this).edit();
1356 editor
.putString("select_oc_account", accountName
);
1360 /// prepare result to return to the Authenticator
1361 // TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done
1362 final Intent intent
= new Intent();
1363 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, MainApp
.getAccountType());
1364 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1366 intent.putExtra(AccountManager.KEY_AUTHTOKEN, MainApp.getAccountType()); */
1367 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1368 if (isOAuth
|| isSaml
) {
1369 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1371 /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
1372 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_OC_VERSION
, mDiscoveredVersion
.getVersion());
1373 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_OC_VERSION_STRING
, mDiscoveredVersion
.getVersionString());
1374 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_OC_BASE_URL
, mHostBaseUrl
);
1377 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
, "TRUE");
1378 } else if (isOAuth
) {
1379 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
, "TRUE");
1382 setAccountAuthenticatorResult(intent
.getExtras());
1383 setResult(RESULT_OK
, intent
);
1393 * Necessary to update the contents of the SSL Dialog
1395 * TODO move to some common place for all possible untrusted SSL failures
1398 protected void onPrepareDialog(int id
, Dialog dialog
, Bundle args
) {
1400 case DIALOG_LOGIN_PROGRESS
:
1401 case DIALOG_CERT_NOT_SAVED
:
1402 case DIALOG_OAUTH2_LOGIN_PROGRESS
:
1405 Log_OC
.e(TAG
, "Incorrect dialog called with id = " + id
);
1414 protected Dialog
onCreateDialog(int id
) {
1415 Dialog dialog
= null
;
1417 case DIALOG_LOGIN_PROGRESS
: {
1418 /// simple progress dialog
1419 ProgressDialog working_dialog
= new ProgressDialog(this);
1420 working_dialog
.setMessage(getResources().getString(R
.string
.auth_trying_to_login
));
1421 working_dialog
.setIndeterminate(true
);
1422 working_dialog
.setCancelable(true
);
1424 .setOnCancelListener(new DialogInterface
.OnCancelListener() {
1426 public void onCancel(DialogInterface dialog
) {
1427 /// TODO study if this is enough
1428 Log_OC
.i(TAG
, "Login canceled");
1429 if (mOperationThread
!= null
) {
1430 mOperationThread
.interrupt();
1435 dialog
= working_dialog
;
1438 case DIALOG_OAUTH2_LOGIN_PROGRESS
: {
1439 ProgressDialog working_dialog
= new ProgressDialog(this);
1440 working_dialog
.setMessage(String
.format("Getting authorization"));
1441 working_dialog
.setIndeterminate(true
);
1442 working_dialog
.setCancelable(true
);
1444 .setOnCancelListener(new DialogInterface
.OnCancelListener() {
1446 public void onCancel(DialogInterface dialog
) {
1447 Log_OC
.i(TAG
, "Login canceled");
1451 dialog
= working_dialog
;
1454 case DIALOG_CERT_NOT_SAVED
: {
1455 AlertDialog
.Builder builder
= new AlertDialog
.Builder(this);
1456 builder
.setMessage(getResources().getString(R
.string
.ssl_validator_not_saved
));
1457 builder
.setCancelable(false
);
1458 builder
.setPositiveButton(R
.string
.common_ok
, new DialogInterface
.OnClickListener() {
1460 public void onClick(DialogInterface dialog
, int which
) {
1464 dialog
= builder
.create();
1468 Log_OC
.e(TAG
, "Incorrect dialog called with id = " + id
);
1475 * Starts and activity to open the 'new account' page in the ownCloud web site
1477 * @param view 'Account register' button
1479 public void onRegisterClick(View view
) {
1480 Intent register
= new Intent(Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.welcome_link_url
)));
1481 setResult(RESULT_CANCELED
);
1482 startActivity(register
);
1487 * Updates the content and visibility state of the icon and text associated
1488 * to the last check on the ownCloud server.
1490 private void showServerStatus() {
1491 TextView tv
= (TextView
) findViewById(R
.id
.server_status_text
);
1493 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1494 tv
.setVisibility(View
.INVISIBLE
);
1497 tv
.setText(mServerStatusText
);
1498 tv
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1499 tv
.setVisibility(View
.VISIBLE
);
1506 * Updates the content and visibility state of the icon and text associated
1507 * to the interactions with the OAuth authorization server.
1509 private void showAuthStatus() {
1510 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1511 mAuthStatusLayout
.setVisibility(View
.INVISIBLE
);
1514 mAuthStatusLayout
.setText(mAuthStatusText
);
1515 mAuthStatusLayout
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1516 mAuthStatusLayout
.setVisibility(View
.VISIBLE
);
1521 private void showRefreshButton() {
1522 mRefreshButton
.setVisibility(View
.VISIBLE
);
1525 private void hideRefreshButton() {
1526 mRefreshButton
.setVisibility(View
.GONE
);
1530 * Called when the refresh button in the input field for ownCloud host is clicked.
1532 * Performs a new check on the URL in the input field.
1534 * @param view Refresh 'button'
1536 public void onRefreshClick(View view
) {
1542 * Called when the eye icon in the password field is clicked.
1544 * Toggles the visibility of the password in the field.
1546 public void onViewPasswordClick() {
1547 int selectionStart
= mPasswordInput
.getSelectionStart();
1548 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1549 if (isPasswordVisible()) {
1554 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1559 * Called when the checkbox for OAuth authorization is clicked.
1561 * Hides or shows the input fields for user & password.
1563 * @param view 'View password' 'button'
1565 public void onCheckClick(View view
) {
1566 CheckBox oAuth2Check
= (CheckBox
)view
;
1567 if (oAuth2Check
.isChecked()) {
1568 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1570 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1572 adaptViewAccordingToAuthenticationMethod();
1577 * Changes the visibility of input elements depending on
1578 * the current authorization method.
1580 private void adaptViewAccordingToAuthenticationMethod () {
1581 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
1582 // OAuth 2 authorization
1583 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
1584 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
1585 mUsernameInput
.setVisibility(View
.GONE
);
1586 mPasswordInput
.setVisibility(View
.GONE
);
1588 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
1589 // SAML-based web Single Sign On
1590 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
1591 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
1592 mUsernameInput
.setVisibility(View
.GONE
);
1593 mPasswordInput
.setVisibility(View
.GONE
);
1595 // basic HTTP authorization
1596 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
1597 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
1598 mUsernameInput
.setVisibility(View
.VISIBLE
);
1599 mPasswordInput
.setVisibility(View
.VISIBLE
);
1604 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1606 * Used to trigger the authentication check when the user presses 'enter' after writing the password,
1607 * or to throw the server test when the only field on screen is the URL input field.
1610 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1611 if (actionId
== EditorInfo
.IME_ACTION_DONE
&& inputField
!= null
&& inputField
.equals(mPasswordInput
)) {
1612 if (mOkButton
.isEnabled()) {
1613 mOkButton
.performClick();
1616 } else if (actionId
== EditorInfo
.IME_ACTION_NEXT
&& inputField
!= null
&& inputField
.equals(mHostUrlInput
)) {
1617 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
1621 return false
; // always return false to grant that the software keyboard is hidden anyway
1625 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1627 private int fuzz
= 75;
1633 public boolean onTouch(View view
, MotionEvent event
) {
1634 Drawable rightDrawable
= null
;
1635 if (view
instanceof TextView
) {
1636 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1637 if (drawables
.length
> 2) {
1638 rightDrawable
= drawables
[2];
1641 if (rightDrawable
!= null
) {
1642 final int x
= (int) event
.getX();
1643 final int y
= (int) event
.getY();
1644 final Rect bounds
= rightDrawable
.getBounds();
1645 if (x
>= (view
.getRight() - bounds
.width() - fuzz
) && x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
)
1646 && y
>= (view
.getPaddingTop() - fuzz
) && y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1648 return onDrawableTouch(event
);
1654 public abstract boolean onDrawableTouch(final MotionEvent event
);
1658 public void onSamlDialogSuccess(String sessionCookie
) {
1659 mAuthToken
= sessionCookie
;
1661 if (sessionCookie
!= null
&& sessionCookie
.length() > 0) {
1662 mAuthToken
= sessionCookie
;
1664 GetRemoteUserNameOperation getUserOperation
= new GetRemoteUserNameOperation();
1665 OwnCloudClient client
= OwnCloudClientFactory
.createOwnCloudClient(Uri
.parse(mHostBaseUrl
), getApplicationContext(), true
);
1666 client
.setSsoSessionCookie(mAuthToken
);
1667 getUserOperation
.execute(client
, this, mHandler
);
1675 public void onSsoFinished(String sessionCookies
) {
1676 //Toast.makeText(this, "got cookies: " + sessionCookie, Toast.LENGTH_LONG).show();
1678 if (sessionCookies
!= null
&& sessionCookies
.length() > 0) {
1679 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1680 onSamlDialogSuccess(sessionCookies
);
1681 Fragment fd
= getSupportFragmentManager().findFragmentByTag(TAG_SAML_DIALOG
);
1682 if (fd
!= null
&& fd
instanceof SherlockDialogFragment
) {
1683 Dialog d
= ((SherlockDialogFragment
)fd
).getDialog();
1684 if (d
!= null
&& d
.isShowing()) {
1691 Log_OC
.d(TAG
, "SSO failed");
1696 /** Show auth_message
1700 private void showAuthMessage(String message
) {
1701 mAuthMessage
.setVisibility(View
.VISIBLE
);
1702 mAuthMessage
.setText(message
);
1705 private void hideAuthMessage() {
1706 mAuthMessage
.setVisibility(View
.GONE
);
1710 public boolean onTouchEvent(MotionEvent event
) {
1711 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
) &&
1712 mHostUrlInput
.hasFocus() && event
.getAction() == MotionEvent
.ACTION_DOWN
) {
1715 return super.onTouchEvent(event
);
1720 * Show untrusted cert dialog
1722 public void showUntrustedCertDialog(X509Certificate x509Certificate
, SslError error
, SslErrorHandler handler
) {
1723 // Show a dialog with the certificate info
1724 SslUntrustedCertDialog dialog
= null
;
1725 if (x509Certificate
== null
) {
1726 dialog
= SslUntrustedCertDialog
.newInstanceForEmptySslError(error
, handler
);
1728 dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(x509Certificate
, error
, handler
);
1730 FragmentManager fm
= getSupportFragmentManager();
1731 FragmentTransaction ft
= fm
.beginTransaction();
1732 ft
.addToBackStack(null
);
1733 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1737 * Show untrusted cert dialog
1739 public void showUntrustedCertDialog(RemoteOperationResult result
) {
1740 // Show a dialog with the certificate info
1741 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1742 FragmentManager fm
= getSupportFragmentManager();
1743 FragmentTransaction ft
= fm
.beginTransaction();
1744 ft
.addToBackStack(null
);
1745 dialog
.show(ft
, DIALOG_UNTRUSTED_CERT
);
1750 * Dismiss untrusted cert dialog
1752 public void dismissUntrustedCertDialog(){
1753 /*Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_UNTRUSTED_CERT);
1755 SslErrorViewAdapter dialog = (SslErrorViewAdapter) frag;
1762 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1764 public void onSavedCertificate() {
1765 Fragment fd
= getSupportFragmentManager().findFragmentByTag(TAG_SAML_DIALOG
);
1767 // if SAML dialog is not shown, the SslDialog was shown due to an SSL error in the server check
1773 * Called from SslValidatorDialog when a new server certificate could not be saved
1774 * when the user requested it.
1777 public void onFailedSavingCertificate() {
1778 showDialog(DIALOG_CERT_NOT_SAVED
);
1783 public void onCancelCertificate() {
1788 public void cancelWebView() {
1789 Fragment fd
= getSupportFragmentManager().findFragmentByTag(TAG_SAML_DIALOG
);
1790 if (fd
!= null
&& fd
instanceof SherlockDialogFragment
) {
1791 Dialog d
= ((SherlockDialogFragment
)fd
).getDialog();
1792 if (d
!= null
&& d
.isShowing()) {