1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2014 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
.io
.IOException
;
22 import java
.security
.cert
.X509Certificate
;
25 import android
.accounts
.Account
;
26 import android
.accounts
.AccountManager
;
27 import android
.accounts
.AuthenticatorException
;
28 import android
.accounts
.OperationCanceledException
;
29 import android
.app
.Dialog
;
30 import android
.content
.ComponentName
;
31 import android
.content
.Context
;
32 import android
.content
.Intent
;
33 import android
.content
.ServiceConnection
;
34 import android
.content
.SharedPreferences
;
35 import android
.graphics
.Rect
;
36 import android
.graphics
.drawable
.Drawable
;
37 import android
.net
.Uri
;
38 import android
.net
.http
.SslError
;
39 import android
.os
.Bundle
;
40 import android
.os
.Handler
;
41 import android
.os
.IBinder
;
42 import android
.preference
.PreferenceManager
;
43 import android
.support
.v4
.app
.Fragment
;
44 import android
.support
.v4
.app
.FragmentManager
;
45 import android
.support
.v4
.app
.FragmentTransaction
;
46 import android
.text
.Editable
;
47 import android
.text
.InputType
;
48 import android
.text
.TextWatcher
;
49 import android
.view
.KeyEvent
;
50 import android
.view
.MotionEvent
;
51 import android
.view
.View
;
52 import android
.view
.View
.OnFocusChangeListener
;
53 import android
.view
.View
.OnTouchListener
;
54 import android
.view
.Window
;
55 import android
.view
.inputmethod
.EditorInfo
;
56 import android
.webkit
.HttpAuthHandler
;
57 import android
.webkit
.SslErrorHandler
;
58 import android
.webkit
.WebView
;
59 import android
.widget
.Button
;
60 import android
.widget
.CheckBox
;
61 import android
.widget
.EditText
;
62 import android
.widget
.TextView
;
63 import android
.widget
.TextView
.OnEditorActionListener
;
64 import android
.widget
.Toast
;
66 import com
.actionbarsherlock
.app
.SherlockDialogFragment
;
67 import com
.owncloud
.android
.MainApp
;
68 import com
.owncloud
.android
.R
;
69 import com
.owncloud
.android
.authentication
.SsoWebViewClient
.SsoWebViewClientListener
;
70 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
71 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
72 import com
.owncloud
.android
.lib
.common
.accounts
.AccountTypeUtils
;
73 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
74 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.Constants
;
75 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
76 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
79 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
80 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
81 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
82 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
83 import com
.owncloud
.android
.lib
.resources
.users
.GetRemoteUserNameOperation
;
84 import com
.owncloud
.android
.operations
.DetectAuthenticationMethodOperation
.AuthenticationMethod
;
85 import com
.owncloud
.android
.operations
.GetServerInfoOperation
;
86 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
87 import com
.owncloud
.android
.services
.OperationsService
;
88 import com
.owncloud
.android
.services
.OperationsService
.OperationsServiceBinder
;
89 import com
.owncloud
.android
.ui
.dialog
.CredentialsDialogFragment
;
90 import com
.owncloud
.android
.ui
.dialog
.IndeterminateProgressDialog
;
91 import com
.owncloud
.android
.ui
.dialog
.SamlWebViewDialog
;
92 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
93 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
94 import com
.owncloud
.android
.utils
.DisplayUtils
;
97 * This Activity is used to add an ownCloud account to the App
99 * @author Bartek Przybylski
100 * @author David A. Velasco
103 public class AuthenticatorActivity
extends AccountAuthenticatorActivity
104 implements OnRemoteOperationListener
, OnFocusChangeListener
, OnEditorActionListener
,
105 SsoWebViewClientListener
, OnSslUntrustedCertListener
,
106 AuthenticatorAsyncTask
.OnAuthenticatorTaskListener
{
108 private static final String TAG
= AuthenticatorActivity
.class.getSimpleName();
110 public static final String EXTRA_ACTION
= "ACTION";
111 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
113 private static final String KEY_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
115 private static final String KEY_HOST_URL_TEXT
= "HOST_URL_TEXT";
116 private static final String KEY_OC_VERSION
= "OC_VERSION";
117 private static final String KEY_SERVER_VALID
= "SERVER_VALID";
118 private static final String KEY_SERVER_CHECKED
= "SERVER_CHECKED";
119 private static final String KEY_SERVER_STATUS_TEXT
= "SERVER_STATUS_TEXT";
120 private static final String KEY_SERVER_STATUS_ICON
= "SERVER_STATUS_ICON";
121 private static final String KEY_IS_SSL_CONN
= "IS_SSL_CONN";
122 private static final String KEY_PASSWORD_EXPOSED
= "PASSWORD_VISIBLE";
123 private static final String KEY_AUTH_STATUS_TEXT
= "AUTH_STATUS_TEXT";
124 private static final String KEY_AUTH_STATUS_ICON
= "AUTH_STATUS_ICON";
125 private static final String KEY_SERVER_AUTH_METHOD
= "SERVER_AUTH_METHOD";
126 private static final String KEY_WAITING_FOR_OP_ID
= "WAITING_FOR_OP_ID";
127 private static final String KEY_AUTH_TOKEN
= "AUTH_TOKEN";
129 private static final String AUTH_ON
= "on";
130 private static final String AUTH_OPTIONAL
= "optional";
132 public static final byte ACTION_CREATE
= 0;
133 public static final byte ACTION_UPDATE_TOKEN
= 1; // requested by the user
134 public static final byte ACTION_UPDATE_EXPIRED_TOKEN
= 2; // detected by the app
136 private static final String UNTRUSTED_CERT_DIALOG_TAG
= "UNTRUSTED_CERT_DIALOG";
137 private static final String SAML_DIALOG_TAG
= "SAML_DIALOG";
138 private static final String WAIT_DIALOG_TAG
= "WAIT_DIALOG";
139 private static final String CREDENTIALS_DIALOG_TAG
= "CREDENTIALS_DIALOG";
140 private static final String KEY_AUTH_IS_FIRST_ATTEMPT_TAG
= "KEY_AUTH_IS_FIRST_ATTEMPT";
143 /// parameters from EXTRAs in starter Intent
144 private byte mAction
;
145 private Account mAccount
;
146 private String mAuthTokenType
;
149 /// activity-level references / state
150 private final Handler mHandler
= new Handler();
151 private ServiceConnection mOperationsServiceConnection
= null
;
152 private OperationsServiceBinder mOperationsServiceBinder
= null
;
153 private AccountManager mAccountMgr
;
154 private Uri mNewCapturedUriFromOAuth2Redirection
;
157 /// Server PRE-Fragment elements
158 private EditText mHostUrlInput
;
159 private View mRefreshButton
;
160 private TextView mServerStatusView
;
162 private TextWatcher mHostUrlInputWatcher
;
163 private int mServerStatusText
= 0, mServerStatusIcon
= 0;
165 private boolean mServerIsChecked
= false
;
166 private boolean mServerIsValid
= false
;
167 private boolean mPendingAutoCheck
= false
;
169 private GetServerInfoOperation
.ServerInfo mServerInfo
=
170 new GetServerInfoOperation
.ServerInfo();
173 /// Authentication PRE-Fragment elements
174 private CheckBox mOAuth2Check
;
175 private TextView mOAuthAuthEndpointText
;
176 private TextView mOAuthTokenEndpointText
;
177 private EditText mUsernameInput
;
178 private EditText mPasswordInput
;
179 private View mOkButton
;
180 private TextView mAuthStatusView
;
182 private int mAuthStatusText
= 0, mAuthStatusIcon
= 0;
184 private String mAuthToken
= "";
186 private boolean mIsFirstAuthAttempt
;
189 /// Identifier of operation in progress which result shouldn't be lost
190 private long mWaitingForOpId
= Long
.MAX_VALUE
;
196 * IMPORTANT ENTRY POINT 1: activity is shown to the user
199 protected void onCreate(Bundle savedInstanceState
) {
200 //Log_OC.wtf(TAG, "onCreate init");
201 super.onCreate(savedInstanceState
);
202 getWindow().requestFeature(Window
.FEATURE_NO_TITLE
);
204 mIsFirstAuthAttempt
= true
;
206 // bind to Operations Service
207 mOperationsServiceConnection
= new OperationsServiceConnection();
208 if (!bindService(new Intent(this, OperationsService
.class),
209 mOperationsServiceConnection
,
210 Context
.BIND_AUTO_CREATE
)) {
212 R
.string
.error_cant_bind_to_operations_service
,
218 /// init activity state
219 mAccountMgr
= AccountManager
.get(this);
220 mNewCapturedUriFromOAuth2Redirection
= null
;
223 mAction
= getIntent().getByteExtra(EXTRA_ACTION
, ACTION_CREATE
);
224 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
225 if (savedInstanceState
== null
) {
228 mAuthTokenType
= savedInstanceState
.getString(KEY_AUTH_TOKEN_TYPE
);
229 mWaitingForOpId
= savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
);
230 mIsFirstAuthAttempt
= savedInstanceState
.getBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
);
235 /// load user interface
236 setContentView(R
.layout
.account_setup
);
238 /// initialize general UI elements
239 initOverallUi(savedInstanceState
);
241 mOkButton
= findViewById(R
.id
.buttonOK
);
243 /// initialize block to be moved to single Fragment to check server and get info about it
244 initServerPreFragment(savedInstanceState
);
246 /// initialize block to be moved to single Fragment to retrieve and validate credentials
247 initAuthorizationPreFragment(savedInstanceState
);
249 //Log_OC.wtf(TAG, "onCreate end");
252 private void initAuthTokenType() {
254 getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
255 if (mAuthTokenType
== null
) {
256 if (mAccount
!= null
) {
257 boolean oAuthRequired
=
258 (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
) != null
);
259 boolean samlWebSsoRequired
= (
260 mAccountMgr
.getUserData(
261 mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
264 mAuthTokenType
= chooseAuthTokenType(oAuthRequired
, samlWebSsoRequired
);
267 boolean oAuthSupported
= AUTH_ON
.equals(getString(R
.string
.auth_method_oauth2
));
268 boolean samlWebSsoSupported
=
269 AUTH_ON
.equals(getString(R
.string
.auth_method_saml_web_sso
));
270 mAuthTokenType
= chooseAuthTokenType(oAuthSupported
, samlWebSsoSupported
);
275 private String
chooseAuthTokenType(boolean oauth
, boolean saml
) {
277 return AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
279 return AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
281 return AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
287 * Configures elements in the user interface under direct control of the Activity.
289 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
291 private void initOverallUi(Bundle savedInstanceState
) {
293 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
294 boolean isWelcomeLinkVisible
= getResources().getBoolean(R
.bool
.show_welcome_link
);
296 String instructionsMessageText
= null
;
297 if (mAction
== ACTION_UPDATE_EXPIRED_TOKEN
) {
298 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
299 .equals(mAuthTokenType
)) {
300 instructionsMessageText
= getString(R
.string
.auth_expired_oauth_token_toast
);
302 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType())
303 .equals(mAuthTokenType
)) {
304 instructionsMessageText
= getString(R
.string
.auth_expired_saml_sso_token_toast
);
307 instructionsMessageText
= getString(R
.string
.auth_expired_basic_auth_toast
);
311 /// step 2 - set properties of UI elements (text, visibility, enabled...)
312 Button welcomeLink
= (Button
) findViewById(R
.id
.welcome_link
);
313 welcomeLink
.setVisibility(isWelcomeLinkVisible ? View
.VISIBLE
: View
.GONE
);
315 String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
317 TextView instructionsView
= (TextView
) findViewById(R
.id
.instructions_message
);
318 if (instructionsMessageText
!= null
) {
319 instructionsView
.setVisibility(View
.VISIBLE
);
320 instructionsView
.setText(instructionsMessageText
);
322 instructionsView
.setVisibility(View
.GONE
);
329 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
331 private void initServerPreFragment(Bundle savedInstanceState
) {
333 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
334 boolean isUrlInputAllowed
= getResources().getBoolean(R
.bool
.show_server_url_input
);
335 if (savedInstanceState
== null
) {
336 if (mAccount
!= null
) {
337 mServerInfo
.mBaseUrl
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_BASE_URL
);
338 // TODO do next in a setter for mBaseUrl
339 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
340 String ocVersion
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_VERSION
);
341 if (ocVersion
!= null
) {
342 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
345 mServerInfo
.mBaseUrl
= getString(R
.string
.server_url
).trim();
346 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
349 mServerStatusText
= savedInstanceState
.getInt(KEY_SERVER_STATUS_TEXT
);
350 mServerStatusIcon
= savedInstanceState
.getInt(KEY_SERVER_STATUS_ICON
);
352 mServerIsValid
= savedInstanceState
.getBoolean(KEY_SERVER_VALID
);
353 mServerIsChecked
= savedInstanceState
.getBoolean(KEY_SERVER_CHECKED
);
356 mServerInfo
.mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
357 mServerInfo
.mBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
358 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
359 if (ocVersion
!= null
) {
360 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
362 mServerInfo
.mAuthMethod
= AuthenticationMethod
.valueOf(
363 savedInstanceState
.getString(KEY_SERVER_AUTH_METHOD
));
367 /// step 2 - set properties of UI elements (text, visibility, enabled...)
368 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
369 // Convert IDN to Unicode
370 mHostUrlInput
.setText(DisplayUtils
.convertIdn(mServerInfo
.mBaseUrl
, false
));
371 if (mAction
!= ACTION_CREATE
) {
372 /// lock things that should not change
373 mHostUrlInput
.setEnabled(false
);
374 mHostUrlInput
.setFocusable(false
);
376 if (isUrlInputAllowed
) {
377 mRefreshButton
= findViewById(R
.id
.embeddedRefreshButton
);
379 findViewById(R
.id
.hostUrlFrame
).setVisibility(View
.GONE
);
380 mRefreshButton
= findViewById(R
.id
.centeredRefreshButton
);
382 showRefreshButton(mServerIsChecked
&& !mServerIsValid
&&
383 mWaitingForOpId
> Integer
.MAX_VALUE
);
384 mServerStatusView
= (TextView
) findViewById(R
.id
.server_status_text
);
387 /// step 3 - bind some listeners and options
388 mHostUrlInput
.setImeOptions(EditorInfo
.IME_ACTION_NEXT
);
389 mHostUrlInput
.setOnEditorActionListener(this);
391 /// step 4 - create listeners that will be bound at onResume
392 mHostUrlInputWatcher
= new TextWatcher() {
395 public void afterTextChanged(Editable s
) {
396 if (mOkButton
.isEnabled() &&
397 !mServerInfo
.mBaseUrl
.equals(
398 normalizeUrl(s
.toString(), mServerInfo
.mIsSslConn
))) {
399 mOkButton
.setEnabled(false
);
404 public void beforeTextChanged(CharSequence s
, int start
, int count
, int after
) {
408 public void onTextChanged(CharSequence s
, int start
, int before
, int count
) {
409 if (mAuthStatusIcon
!= 0) {
410 Log_OC
.d(TAG
, "onTextChanged: hiding authentication status");
419 // TODO find out if this is really necessary, or if it can done in a different way
420 findViewById(R
.id
.scroll
).setOnTouchListener(new OnTouchListener() {
422 public boolean onTouch(View view
, MotionEvent event
) {
423 if (event
.getAction() == MotionEvent
.ACTION_DOWN
) {
425 AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(
426 MainApp
.getAccountType()
427 ).equals(mAuthTokenType
) &&
428 mHostUrlInput
.hasFocus()
438 /// step 4 - mark automatic check to be started when OperationsService is ready
439 mPendingAutoCheck
= (savedInstanceState
== null
&&
440 (mAction
!= ACTION_CREATE
|| !isUrlInputAllowed
));
446 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
448 private void initAuthorizationPreFragment(Bundle savedInstanceState
) {
450 /// step 0 - get UI elements in layout
451 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
452 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
453 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
454 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
455 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
456 mAuthStatusView
= (TextView
) findViewById(R
.id
.auth_status_text
);
458 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
459 String presetUserName
= null
;
460 boolean isPasswordExposed
= false
;
461 if (savedInstanceState
== null
) {
462 if (mAccount
!= null
) {
463 presetUserName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
467 isPasswordExposed
= savedInstanceState
.getBoolean(KEY_PASSWORD_EXPOSED
, false
);
468 mAuthStatusText
= savedInstanceState
.getInt(KEY_AUTH_STATUS_TEXT
);
469 mAuthStatusIcon
= savedInstanceState
.getInt(KEY_AUTH_STATUS_ICON
);
470 mAuthToken
= savedInstanceState
.getString(KEY_AUTH_TOKEN
);
473 /// step 2 - set properties of UI elements (text, visibility, enabled...)
474 mOAuth2Check
.setChecked(
475 AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
476 .equals(mAuthTokenType
));
477 if (presetUserName
!= null
) {
478 mUsernameInput
.setText(presetUserName
);
480 if (mAction
!= ACTION_CREATE
) {
481 mUsernameInput
.setEnabled(false
);
482 mUsernameInput
.setFocusable(false
);
484 mPasswordInput
.setText(""); // clean password to avoid social hacking
485 if (isPasswordExposed
) {
488 updateAuthenticationPreFragmentVisibility();
490 mOkButton
.setEnabled(mServerIsValid
);
493 /// step 3 - bind listeners
494 // bindings for password input field
495 mPasswordInput
.setOnFocusChangeListener(this);
496 mPasswordInput
.setImeOptions(EditorInfo
.IME_ACTION_DONE
);
497 mPasswordInput
.setOnEditorActionListener(this);
498 mPasswordInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
500 public boolean onDrawableTouch(final MotionEvent event
) {
501 if (event
.getAction() == MotionEvent
.ACTION_UP
) {
502 AuthenticatorActivity
.this.onViewPasswordClick();
512 * Changes the visibility of input elements depending on
513 * the current authorization method.
515 private void updateAuthenticationPreFragmentVisibility () {
516 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
517 equals(mAuthTokenType
)) {
518 // SAML-based web Single Sign On
519 mOAuth2Check
.setVisibility(View
.GONE
);
520 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
521 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
522 mUsernameInput
.setVisibility(View
.GONE
);
523 mPasswordInput
.setVisibility(View
.GONE
);
526 if (mAction
== ACTION_CREATE
&&
527 AUTH_OPTIONAL
.equals(getString(R
.string
.auth_method_oauth2
))) {
528 mOAuth2Check
.setVisibility(View
.VISIBLE
);
530 mOAuth2Check
.setVisibility(View
.GONE
);
533 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
534 equals(mAuthTokenType
)) {
535 // OAuth 2 authorization
537 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
538 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
539 mUsernameInput
.setVisibility(View
.GONE
);
540 mPasswordInput
.setVisibility(View
.GONE
);
543 // basic HTTP authorization
544 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
545 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
546 mUsernameInput
.setVisibility(View
.VISIBLE
);
547 mPasswordInput
.setVisibility(View
.VISIBLE
);
555 * Saves relevant state before {@link #onPause()}
557 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag,
558 * intended to defer the processing of the redirection caught in
559 * {@link #onNewIntent(Intent)} until {@link #onResume()}
561 * See {@link #onSaveInstanceState(Bundle)}
564 protected void onSaveInstanceState(Bundle outState
) {
565 //Log_OC.wtf(TAG, "onSaveInstanceState init" );
566 super.onSaveInstanceState(outState
);
569 outState
.putString(KEY_AUTH_TOKEN_TYPE
, mAuthTokenType
);
570 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mWaitingForOpId
);
572 /// Server PRE-fragment state
573 outState
.putInt(KEY_SERVER_STATUS_TEXT
, mServerStatusText
);
574 outState
.putInt(KEY_SERVER_STATUS_ICON
, mServerStatusIcon
);
575 outState
.putBoolean(KEY_SERVER_CHECKED
, mServerIsChecked
);
576 outState
.putBoolean(KEY_SERVER_VALID
, mServerIsValid
);
577 outState
.putBoolean(KEY_IS_SSL_CONN
, mServerInfo
.mIsSslConn
);
578 outState
.putString(KEY_HOST_URL_TEXT
, mServerInfo
.mBaseUrl
);
579 if (mServerInfo
.mVersion
!= null
) {
580 outState
.putString(KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion());
582 outState
.putString(KEY_SERVER_AUTH_METHOD
, mServerInfo
.mAuthMethod
.name());
584 /// Authentication PRE-fragment state
585 outState
.putBoolean(KEY_PASSWORD_EXPOSED
, isPasswordVisible());
586 outState
.putInt(KEY_AUTH_STATUS_ICON
, mAuthStatusIcon
);
587 outState
.putInt(KEY_AUTH_STATUS_TEXT
, mAuthStatusText
);
588 outState
.putString(KEY_AUTH_TOKEN
, mAuthToken
);
591 outState
.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
, mIsFirstAuthAttempt
);
593 //Log_OC.wtf(TAG, "onSaveInstanceState end" );
598 * The redirection triggered by the OAuth authentication server as response to the
599 * GET AUTHORIZATION request is caught here.
601 * To make this possible, this activity needs to be qualified with android:launchMode =
602 * "singleTask" in the AndroidManifest.xml file.
605 protected void onNewIntent (Intent intent
) {
606 Log_OC
.d(TAG
, "onNewIntent()");
607 Uri data
= intent
.getData();
608 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
609 mNewCapturedUriFromOAuth2Redirection
= data
;
615 * The redirection triggered by the OAuth authentication server as response to the
616 * GET AUTHORIZATION, and deferred in {@link #onNewIntent(Intent)}, is processed here.
619 protected void onResume() {
620 //Log_OC.wtf(TAG, "onResume init" );
623 // bound here to avoid spurious changes triggered by Android on device rotations
624 mHostUrlInput
.setOnFocusChangeListener(this);
625 mHostUrlInput
.addTextChangedListener(mHostUrlInputWatcher
);
627 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
628 getOAuth2AccessTokenFromCapturedRedirection();
631 if (mOperationsServiceBinder
!= null
) {
632 doOnResumeAndBound();
635 //Log_OC.wtf(TAG, "onResume end" );
640 protected void onPause() {
641 //Log_OC.wtf(TAG, "onPause init" );
642 if (mOperationsServiceBinder
!= null
) {
643 //Log_OC.wtf(TAG, "unregistering to listen for operation callbacks" );
644 mOperationsServiceBinder
.removeOperationListener(this);
647 mHostUrlInput
.removeTextChangedListener(mHostUrlInputWatcher
);
648 mHostUrlInput
.setOnFocusChangeListener(null
);
651 //Log_OC.wtf(TAG, "onPause end" );
655 protected void onDestroy() {
657 mHostUrlInputWatcher
= null
;
659 if (mOperationsServiceConnection
!= null
) {
660 unbindService(mOperationsServiceConnection
);
661 mOperationsServiceBinder
= null
;
668 * Parses the redirection with the response to the GET AUTHORIZATION request to the
669 * oAuth server and requests for the access token (GET ACCESS TOKEN)
671 private void getOAuth2AccessTokenFromCapturedRedirection() {
672 /// Parse data from OAuth redirection
673 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
674 mNewCapturedUriFromOAuth2Redirection
= null
;
676 /// Showing the dialog with instructions for the user.
677 IndeterminateProgressDialog dialog
=
678 IndeterminateProgressDialog
.newInstance(R
.string
.auth_getting_authorization
, true
);
679 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
681 /// GET ACCESS TOKEN to the oAuth server
682 Intent getServerInfoIntent
= new Intent();
683 getServerInfoIntent
.setAction(OperationsService
.ACTION_OAUTH2_GET_ACCESS_TOKEN
);
685 getServerInfoIntent
.putExtra(
686 OperationsService
.EXTRA_SERVER_URL
,
687 mOAuthTokenEndpointText
.getText().toString().trim());
689 getServerInfoIntent
.putExtra(
690 OperationsService
.EXTRA_OAUTH2_QUERY_PARAMETERS
,
693 if (mOperationsServiceBinder
!= null
) {
694 //Log_OC.wtf(TAG, "getting access token..." );
695 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
702 * Handles the change of focus on the text inputs for the server URL and the password
704 public void onFocusChange(View view
, boolean hasFocus
) {
705 if (view
.getId() == R
.id
.hostUrlInput
) {
707 onUrlInputFocusLost((TextView
) view
);
710 showRefreshButton(false
);
713 } else if (view
.getId() == R
.id
.account_password
) {
714 onPasswordFocusChanged((TextView
) view
, hasFocus
);
720 * Handles changes in focus on the text input for the server URL.
722 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
723 * other field. The operation to check the existence of the server in the entered URL is
726 * When hasFocus: user 'comes back' to write again the server URL.
728 * @param hostInput TextView with the URL input field receiving the change of focus.
730 private void onUrlInputFocusLost(TextView hostInput
) {
731 if (!mServerInfo
.mBaseUrl
.equals(
732 normalizeUrl(mHostUrlInput
.getText().toString(), mServerInfo
.mIsSslConn
))) {
733 // check server again only if the user changed something in the field
736 mOkButton
.setEnabled(mServerIsValid
);
737 showRefreshButton(!mServerIsValid
);
742 private void checkOcServer() {
743 String uri
= mHostUrlInput
.getText().toString().trim();
744 mServerIsValid
= false
;
745 mServerIsChecked
= false
;
746 mOkButton
.setEnabled(false
);
747 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
748 showRefreshButton(false
);
750 if (uri
.length() != 0) {
751 // Handle internationalized domain names
752 uri
= DisplayUtils
.convertIdn(uri
, true
);
753 mServerStatusText
= R
.string
.auth_testing_connection
;
754 mServerStatusIcon
= R
.drawable
.progress_small
;
757 Intent getServerInfoIntent
= new Intent();
758 getServerInfoIntent
.setAction(OperationsService
.ACTION_GET_SERVER_INFO
);
759 getServerInfoIntent
.putExtra(
760 OperationsService
.EXTRA_SERVER_URL
,
761 normalizeUrlSuffix(uri
)
763 if (mOperationsServiceBinder
!= null
) {
764 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
766 Log_OC
.wtf(TAG
, "Server check tried with OperationService unbound!" );
770 mServerStatusText
= 0;
771 mServerStatusIcon
= 0;
778 * Handles changes in focus on the text input for the password (basic authorization).
780 * When (hasFocus), the button to toggle password visibility is shown.
782 * When (!hasFocus), the button is made invisible and the password is hidden.
784 * @param passwordInput TextView with the password input field receiving the change of focus.
785 * @param hasFocus 'True' if focus is received, 'false' if is lost
787 private void onPasswordFocusChanged(TextView passwordInput
, boolean hasFocus
) {
789 showViewPasswordButton();
792 hidePasswordButton();
797 private void showViewPasswordButton() {
798 int drawable
= R
.drawable
.ic_view
;
799 if (isPasswordVisible()) {
800 drawable
= R
.drawable
.ic_hide
;
802 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable
, 0);
805 private boolean isPasswordVisible() {
806 return ((mPasswordInput
.getInputType() & InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) ==
807 InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
810 private void hidePasswordButton() {
811 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
814 private void showPassword() {
815 mPasswordInput
.setInputType(
816 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
818 showViewPasswordButton();
821 private void hidePassword() {
822 mPasswordInput
.setInputType(
823 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
825 showViewPasswordButton();
829 * Checks the credentials of the user in the root of the ownCloud server
830 * before creating a new local account.
832 * For basic authorization, a check of existence of the root folder is
835 * For OAuth, starts the flow to get an access token; the credentials test
836 * is postponed until it is available.
838 * IMPORTANT ENTRY POINT 4
840 * @param view OK button
842 public void onOkClick(View view
) {
843 // this check should be unnecessary
844 if (mServerInfo
.mVersion
== null
||
845 !mServerInfo
.mVersion
.isVersionValid() ||
846 mServerInfo
.mBaseUrl
== null
||
847 mServerInfo
.mBaseUrl
.length() == 0) {
848 mServerStatusIcon
= R
.drawable
.common_error
;
849 mServerStatusText
= R
.string
.auth_wtf_reenter_URL
;
851 mOkButton
.setEnabled(false
);
852 //Log_OC.wtf(TAG, "The user was allowed to click 'connect' to an unchecked server!!");
856 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
857 equals(mAuthTokenType
)) {
859 startOauthorization();
860 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
861 equals(mAuthTokenType
)) {
863 startSamlBasedFederatedSingleSignOnAuthorization();
865 checkBasicAuthorization();
871 * Tests the credentials entered by the user performing a check of existence on
872 * the root folder of the ownCloud server.
874 private void checkBasicAuthorization() {
875 /// get basic credentials entered by user
876 String username
= mUsernameInput
.getText().toString();
877 String password
= mPasswordInput
.getText().toString();
879 /// be gentle with the user
880 IndeterminateProgressDialog dialog
=
881 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
882 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
884 /// validate credentials accessing the root folder
885 accessRootFolderRemoteOperation(username
, password
);
889 private void accessRootFolderRemoteOperation(String username
, String password
) {
890 // delete the account if the token has changed
891 if (mAction
== ACTION_UPDATE_TOKEN
|| mAction
== ACTION_UPDATE_EXPIRED_TOKEN
) {
892 // Remove the cookies in AccountManager
893 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_COOKIES
, null
);
896 AuthenticatorAsyncTask asyncTask
= new AuthenticatorAsyncTask(this);
897 String
[] params
= { mServerInfo
.mBaseUrl
, username
, password
, mAuthToken
, mAuthTokenType
};
898 asyncTask
.execute(params
);
903 * Starts the OAuth 'grant type' flow to get an access token, with
904 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
906 private void startOauthorization() {
907 // be gentle with the user
908 mAuthStatusIcon
= R
.drawable
.progress_small
;
909 mAuthStatusText
= R
.string
.oauth_login_connection
;
912 // GET AUTHORIZATION request
913 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
914 Uri
.Builder uriBuilder
= uri
.buildUpon();
915 uriBuilder
.appendQueryParameter(
916 OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
)
918 uriBuilder
.appendQueryParameter(
919 OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
)
921 uriBuilder
.appendQueryParameter(
922 OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
)
924 uriBuilder
.appendQueryParameter(
925 OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
)
927 uri
= uriBuilder
.build();
928 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
929 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
935 * Starts the Web Single Sign On flow to get access to the root folder
938 private void startSamlBasedFederatedSingleSignOnAuthorization() {
939 // be gentle with the user
940 mAuthStatusIcon
= R
.drawable
.progress_small
;
941 mAuthStatusText
= R
.string
.auth_connecting_auth_server
;
943 IndeterminateProgressDialog dialog
=
944 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
945 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
947 /// validate credentials accessing the root folder
948 accessRootFolderRemoteOperation("", "");
953 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
955 * Dispatches the operation flow to the right method.
958 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
960 if (operation
instanceof GetServerInfoOperation
) {
961 if (operation
.hashCode() == mWaitingForOpId
) {
962 onGetServerInfoFinish(result
);
963 } // else nothing ; only the last check operation is considered;
964 // multiple can be started if the user amends a URL quickly
966 } else if (operation
instanceof OAuth2GetAccessToken
) {
967 onGetOAuthAccessTokenFinish(result
);
969 } else if (operation
instanceof ExistenceCheckRemoteOperation
) {
970 // TODO : remove this response??
971 //Log_OC.wtf(TAG, "received detection response through callback" );
972 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
973 equals(mAuthTokenType
)) {
974 onSamlBasedFederatedSingleSignOnAuthorizationStart(result
);
977 onAuthorizationCheckFinish(result
);
979 } else if (operation
instanceof GetRemoteUserNameOperation
) {
980 onGetUserNameFinish(result
);
985 private void onGetUserNameFinish(RemoteOperationResult result
) {
986 mWaitingForOpId
= Long
.MAX_VALUE
;
987 if (result
.isSuccess()) {
988 boolean success
= false
;
989 String username
= (String
) result
.getData().get(0);
991 if ( mAction
== ACTION_CREATE
) {
992 mUsernameInput
.setText(username
);
993 success
= createAccount();
996 if (!mUsernameInput
.getText().toString().equals(username
)) {
997 // fail - not a new account, but an existing one; disallow
998 result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_THE_SAME
);
1000 updateAuthStatusIconAndText(result
);
1002 Log_OC
.d(TAG
, result
.getLogMessage());
1005 updateAccountAuthentication();
1008 } catch (AccountNotFoundException e
) {
1009 Log_OC
.e(TAG
, "Account " + mAccount
+ " was removed!", e
);
1010 Toast
.makeText(this, R
.string
.auth_account_does_not_exist
, Toast
.LENGTH_SHORT
).show();
1019 updateStatusIconFailUserName();
1021 Log_OC
.e(TAG
, "Access to user name failed: " + result
.getLogMessage());
1026 private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperationResult result
) {
1027 mWaitingForOpId
= Long
.MAX_VALUE
;
1028 dismissDialog(WAIT_DIALOG_TAG
);
1030 if (result
.isIdPRedirection()) {
1031 String targetUrl
= mServerInfo
.mBaseUrl
1032 + AccountUtils
.getWebdavPath(mServerInfo
.mVersion
, mAuthTokenType
);
1035 SamlWebViewDialog dialog
= SamlWebViewDialog
.newInstance(targetUrl
, targetUrl
);
1036 dialog
.show(getSupportFragmentManager(), SAML_DIALOG_TAG
);
1038 mAuthStatusIcon
= 0;
1039 mAuthStatusText
= 0;
1042 mAuthStatusIcon
= R
.drawable
.common_error
;
1043 mAuthStatusText
= R
.string
.auth_unsupported_auth_method
;
1051 * Processes the result of the server check performed when the user finishes the enter of the
1054 * @param result Result of the check.
1056 private void onGetServerInfoFinish(RemoteOperationResult result
) {
1057 /// update activity state
1058 mServerIsChecked
= true
;
1059 mWaitingForOpId
= Long
.MAX_VALUE
;
1061 // update server status, but don't show it yet
1062 updateServerStatusIconAndText(result
);
1064 if (result
.isSuccess()) {
1066 // 1. connection succeeded, and we know if it's SSL or not
1067 // 2. server is installed
1068 // 3. we got the server version
1069 // 4. we got the authentication method required by the server
1070 mServerInfo
= (GetServerInfoOperation
.ServerInfo
) (result
.getData().get(0));
1072 if (!authSupported(mServerInfo
.mAuthMethod
)) {
1074 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1075 mServerIsValid
= false
;
1078 mServerIsValid
= true
;
1082 mServerIsValid
= false
;
1086 showRefreshButton(!mServerIsValid
);
1088 mOkButton
.setEnabled(mServerIsValid
);
1090 /// very special case (TODO: move to a common place for all the remote operations)
1091 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1092 showUntrustedCertDialog(result
);
1097 private boolean authSupported(AuthenticationMethod authMethod
) {
1098 String basic
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1099 String oAuth
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1100 String saml
= AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
1102 return (( mAuthTokenType
.equals(basic
) &&
1103 authMethod
.equals(AuthenticationMethod
.BASIC_HTTP_AUTH
) ) ||
1104 ( mAuthTokenType
.equals(oAuth
) &&
1105 authMethod
.equals(AuthenticationMethod
.BEARER_TOKEN
)) ||
1106 ( mAuthTokenType
.equals(saml
) &&
1107 authMethod
.equals(AuthenticationMethod
.SAML_WEB_SSO
))
1112 // TODO remove, if possible
1113 private String
normalizeUrl(String url
, boolean sslWhenUnprefixed
) {
1114 if (url
!= null
&& url
.length() > 0) {
1116 if (!url
.toLowerCase().startsWith("http://") &&
1117 !url
.toLowerCase().startsWith("https://")) {
1118 if (sslWhenUnprefixed
) {
1119 url
= "https://" + url
;
1121 url
= "http://" + url
;
1125 url
= normalizeUrlSuffix(url
);
1127 return (url
!= null ? url
: "");
1131 private String
normalizeUrlSuffix(String url
) {
1132 if (url
.endsWith("/")) {
1133 url
= url
.substring(0, url
.length() - 1);
1135 url
= trimUrlWebdav(url
);
1140 // TODO remove, if possible
1141 private String
trimUrlWebdav(String url
){
1142 if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_4_0
)){
1143 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_4_0
.length());
1144 } else if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_2_0
)){
1145 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_2_0
.length());
1146 } else if (url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_1_2
)){
1147 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_1_2
.length());
1149 return (url
!= null ? url
: "");
1154 * Chooses the right icon and text to show to the user for the received operation result.
1156 * @param result Result of a remote operation performed in this activity
1158 private void updateServerStatusIconAndText(RemoteOperationResult result
) {
1159 mServerStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1161 switch (result
.getCode()) {
1163 mServerStatusIcon
= android
.R
.drawable
.ic_secure
;
1164 mServerStatusText
= R
.string
.auth_secure_connection
;
1169 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1170 mServerStatusText
= R
.string
.auth_connection_established
;
1171 mServerStatusIcon
= R
.drawable
.ic_ok
;
1173 mServerStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1174 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1178 case NO_NETWORK_CONNECTION
:
1179 mServerStatusIcon
= R
.drawable
.no_network
;
1180 mServerStatusText
= R
.string
.auth_no_net_conn_title
;
1183 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1184 mServerStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1186 case BAD_OC_VERSION
:
1187 mServerStatusText
= R
.string
.auth_bad_oc_version_title
;
1189 case WRONG_CONNECTION
:
1190 mServerStatusText
= R
.string
.auth_wrong_connection_title
;
1193 mServerStatusText
= R
.string
.auth_timeout_title
;
1195 case INCORRECT_ADDRESS
:
1196 mServerStatusText
= R
.string
.auth_incorrect_address_title
;
1199 mServerStatusText
= R
.string
.auth_ssl_general_error_title
;
1202 mServerStatusText
= R
.string
.auth_unauthorized
;
1204 case HOST_NOT_AVAILABLE
:
1205 mServerStatusText
= R
.string
.auth_unknown_host_title
;
1207 case INSTANCE_NOT_CONFIGURED
:
1208 mServerStatusText
= R
.string
.auth_not_configured_title
;
1210 case FILE_NOT_FOUND
:
1211 mServerStatusText
= R
.string
.auth_incorrect_path_title
;
1214 mServerStatusText
= R
.string
.auth_oauth_error
;
1216 case OAUTH2_ERROR_ACCESS_DENIED
:
1217 mServerStatusText
= R
.string
.auth_oauth_error_access_denied
;
1219 case UNHANDLED_HTTP_CODE
:
1221 mServerStatusText
= R
.string
.auth_unknown_error_title
;
1223 case OK_REDIRECT_TO_NON_SECURE_CONNECTION
:
1224 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1225 mServerStatusText
= R
.string
.auth_redirect_non_secure_connection_title
;
1228 mServerStatusText
= 0;
1229 mServerStatusIcon
= 0;
1235 * Chooses the right icon and text to show to the user for the received operation result.
1237 * @param result Result of a remote operation performed in this activity
1239 private void updateAuthStatusIconAndText(RemoteOperationResult result
) {
1240 mAuthStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1242 switch (result
.getCode()) {
1244 mAuthStatusIcon
= android
.R
.drawable
.ic_secure
;
1245 mAuthStatusText
= R
.string
.auth_secure_connection
;
1250 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1251 mAuthStatusText
= R
.string
.auth_connection_established
;
1252 mAuthStatusIcon
= R
.drawable
.ic_ok
;
1254 mAuthStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1255 mAuthStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1259 case NO_NETWORK_CONNECTION
:
1260 mAuthStatusIcon
= R
.drawable
.no_network
;
1261 mAuthStatusText
= R
.string
.auth_no_net_conn_title
;
1264 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1265 mAuthStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1267 case BAD_OC_VERSION
:
1268 mAuthStatusText
= R
.string
.auth_bad_oc_version_title
;
1270 case WRONG_CONNECTION
:
1271 mAuthStatusText
= R
.string
.auth_wrong_connection_title
;
1274 mAuthStatusText
= R
.string
.auth_timeout_title
;
1276 case INCORRECT_ADDRESS
:
1277 mAuthStatusText
= R
.string
.auth_incorrect_address_title
;
1280 mAuthStatusText
= R
.string
.auth_ssl_general_error_title
;
1283 mAuthStatusText
= R
.string
.auth_unauthorized
;
1285 case HOST_NOT_AVAILABLE
:
1286 mAuthStatusText
= R
.string
.auth_unknown_host_title
;
1288 case INSTANCE_NOT_CONFIGURED
:
1289 mAuthStatusText
= R
.string
.auth_not_configured_title
;
1291 case FILE_NOT_FOUND
:
1292 mAuthStatusText
= R
.string
.auth_incorrect_path_title
;
1295 mAuthStatusText
= R
.string
.auth_oauth_error
;
1297 case OAUTH2_ERROR_ACCESS_DENIED
:
1298 mAuthStatusText
= R
.string
.auth_oauth_error_access_denied
;
1300 case ACCOUNT_NOT_NEW
:
1301 mAuthStatusText
= R
.string
.auth_account_not_new
;
1303 case ACCOUNT_NOT_THE_SAME
:
1304 mAuthStatusText
= R
.string
.auth_account_not_the_same
;
1306 case UNHANDLED_HTTP_CODE
:
1308 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
1311 mAuthStatusText
= 0;
1312 mAuthStatusIcon
= 0;
1317 private void updateStatusIconFailUserName(){
1318 mAuthStatusIcon
= R
.drawable
.common_error
;
1319 mAuthStatusText
= R
.string
.auth_fail_get_user_name
;
1322 private void updateServerStatusIconNoRegularAuth(){
1323 mServerStatusIcon
= R
.drawable
.common_error
;
1324 mServerStatusText
= R
.string
.auth_can_not_auth_against_server
;
1328 * Processes the result of the request for and access token send
1329 * to an OAuth authorization server.
1331 * @param result Result of the operation.
1333 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result
) {
1334 mWaitingForOpId
= Long
.MAX_VALUE
;
1335 dismissDialog(WAIT_DIALOG_TAG
);
1337 if (result
.isSuccess()) {
1338 /// be gentle with the user
1339 IndeterminateProgressDialog dialog
=
1340 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
1341 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
1343 /// time to test the retrieved access token on the ownCloud server
1344 @SuppressWarnings("unchecked")
1345 Map
<String
, String
> tokens
= (Map
<String
, String
>)(result
.getData().get(0));
1346 mAuthToken
= tokens
.get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
1347 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mAuthToken
);
1349 accessRootFolderRemoteOperation("", "");
1352 updateAuthStatusIconAndText(result
);
1354 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1360 * Processes the result of the access check performed to try the user credentials.
1362 * Creates a new account through the AccountManager.
1364 * @param result Result of the operation.
1366 private void onAuthorizationCheckFinish(RemoteOperationResult result
) {
1367 mWaitingForOpId
= Long
.MAX_VALUE
;
1368 dismissDialog(WAIT_DIALOG_TAG
);
1370 if (result
.isSuccess()) {
1371 Log_OC
.d(TAG
, "Successful access - time to save the account");
1373 boolean success
= false
;
1374 if (mAction
== ACTION_CREATE
) {
1375 success
= createAccount();
1379 updateAccountAuthentication();
1382 } catch (AccountNotFoundException e
) {
1383 Log_OC
.e(TAG
, "Account " + mAccount
+ " was removed!", e
);
1384 Toast
.makeText(this, R
.string
.auth_account_does_not_exist
, Toast
.LENGTH_SHORT
).show();
1393 } else if (result
.isServerFail() || result
.isException()) {
1394 /// server errors or exceptions in authorization take to requiring a new check of
1396 mServerIsChecked
= true
;
1397 mServerIsValid
= false
;
1398 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
1400 // update status icon and text
1401 updateServerStatusIconAndText(result
);
1403 mAuthStatusIcon
= 0;
1404 mAuthStatusText
= 0;
1407 // update input controls state
1408 showRefreshButton(true
);
1409 mOkButton
.setEnabled(false
);
1411 // very special case (TODO: move to a common place for all the remote operations)
1412 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1413 showUntrustedCertDialog(result
);
1416 } else { // authorization fail due to client side - probably wrong credentials
1417 updateAuthStatusIconAndText(result
);
1419 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1427 * Updates the authentication token.
1429 * Sets the proper response so that the AccountAuthenticator that started this activity
1430 * saves a new authorization token for mAccount.
1432 * Kills the session kept by OwnCloudClientManager so that a new one will created with
1433 * the new credentials when needed.
1435 private void updateAccountAuthentication() throws AccountNotFoundException
{
1437 OwnCloudClientManagerFactory
.getDefaultSingleton().removeClientFor(
1438 new OwnCloudAccount(mAccount
, this)
1441 Bundle response
= new Bundle();
1442 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1443 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
1445 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
1446 equals(mAuthTokenType
)) {
1447 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1448 // the next line is necessary, notifications are calling directly to the
1449 // AuthenticatorActivity to update, without AccountManager intervention
1450 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1452 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1453 equals(mAuthTokenType
)) {
1455 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1456 // the next line is necessary; by now, notifications are calling directly to the
1457 // AuthenticatorActivity to update, without AccountManager intervention
1458 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1461 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
1462 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
1464 setAccountAuthenticatorResult(response
);
1470 * Creates a new account through the Account Authenticator that started this activity.
1472 * This makes the account permanent.
1474 * TODO Decide how to name the OAuth accounts
1476 private boolean createAccount() {
1477 /// create and save new ownCloud account
1478 boolean isOAuth
= AccountTypeUtils
.
1479 getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
);
1480 boolean isSaml
= AccountTypeUtils
.
1481 getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
);
1483 Uri uri
= Uri
.parse(mServerInfo
.mBaseUrl
);
1484 String username
= mUsernameInput
.getText().toString().trim();
1486 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1488 String accountName
= com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.
1489 buildAccountName(uri
, username
);
1490 Account newAccount
= new Account(accountName
, MainApp
.getAccountType());
1491 if (AccountUtils
.exists(newAccount
, getApplicationContext())) {
1492 // fail - not a new account, but an existing one; disallow
1493 RemoteOperationResult result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_NEW
);
1494 updateAuthStatusIconAndText(result
);
1496 Log_OC
.d(TAG
, result
.getLogMessage());
1500 mAccount
= newAccount
;
1502 if (isOAuth
|| isSaml
) {
1503 // with external authorizations, the password is never input in the app
1504 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
);
1506 mAccountMgr
.addAccountExplicitly(
1507 mAccount
, mPasswordInput
.getText().toString(), null
1511 /// add the new account as default in preferences, if there is none already
1512 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1513 if (defaultAccount
== null
) {
1514 SharedPreferences
.Editor editor
= PreferenceManager
1515 .getDefaultSharedPreferences(this).edit();
1516 editor
.putString("select_oc_account", accountName
);
1520 /// prepare result to return to the Authenticator
1521 // TODO check again what the Authenticator makes with it; probably has the same
1522 // effect as addAccountExplicitly, but it's not well done
1523 final Intent intent
= new Intent();
1524 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, MainApp
.getAccountType());
1525 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1527 intent.putExtra(AccountManager.KEY_AUTHTOKEN, MainApp.getAccountType()); */
1528 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1529 if (isOAuth
|| isSaml
) {
1530 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1532 /// add user data to the new account; TODO probably can be done in the last parameter
1533 // addAccountExplicitly, or in KEY_USERDATA
1534 mAccountMgr
.setUserData(
1535 mAccount
, Constants
.KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion()
1537 mAccountMgr
.setUserData(
1538 mAccount
, Constants
.KEY_OC_BASE_URL
, mServerInfo
.mBaseUrl
1542 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
, "TRUE");
1543 } else if (isOAuth
) {
1544 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
, "TRUE");
1547 setAccountAuthenticatorResult(intent
.getExtras());
1548 setResult(RESULT_OK
, intent
);
1556 * Starts and activity to open the 'new account' page in the ownCloud web site
1558 * @param view 'Account register' button
1560 public void onRegisterClick(View view
) {
1561 Intent register
= new Intent(
1562 Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.welcome_link_url
))
1564 setResult(RESULT_CANCELED
);
1565 startActivity(register
);
1570 * Updates the content and visibility state of the icon and text associated
1571 * to the last check on the ownCloud server.
1573 private void showServerStatus() {
1574 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1575 mServerStatusView
.setVisibility(View
.INVISIBLE
);
1578 mServerStatusView
.setText(mServerStatusText
);
1579 mServerStatusView
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1580 mServerStatusView
.setVisibility(View
.VISIBLE
);
1587 * Updates the content and visibility state of the icon and text associated
1588 * to the interactions with the OAuth authorization server.
1590 private void showAuthStatus() {
1591 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1592 mAuthStatusView
.setVisibility(View
.INVISIBLE
);
1595 mAuthStatusView
.setText(mAuthStatusText
);
1596 mAuthStatusView
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1597 mAuthStatusView
.setVisibility(View
.VISIBLE
);
1602 private void showRefreshButton (boolean show
) {
1604 mRefreshButton
.setVisibility(View
.VISIBLE
);
1606 mRefreshButton
.setVisibility(View
.GONE
);
1611 * Called when the refresh button in the input field for ownCloud host is clicked.
1613 * Performs a new check on the URL in the input field.
1615 * @param view Refresh 'button'
1617 public void onRefreshClick(View view
) {
1623 * Called when the eye icon in the password field is clicked.
1625 * Toggles the visibility of the password in the field.
1627 public void onViewPasswordClick() {
1628 int selectionStart
= mPasswordInput
.getSelectionStart();
1629 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1630 if (isPasswordVisible()) {
1635 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1640 * Called when the checkbox for OAuth authorization is clicked.
1642 * Hides or shows the input fields for user & password.
1644 * @param view 'View password' 'button'
1646 public void onCheckClick(View view
) {
1647 CheckBox oAuth2Check
= (CheckBox
)view
;
1648 if (oAuth2Check
.isChecked()) {
1649 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1651 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1653 updateAuthenticationPreFragmentVisibility();
1658 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1660 * Used to trigger the authentication check when the user presses 'enter' after writing the
1661 * password, or to throw the server test when the only field on screen is the URL input field.
1664 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1665 if (actionId
== EditorInfo
.IME_ACTION_DONE
&& inputField
!= null
&&
1666 inputField
.equals(mPasswordInput
)) {
1667 if (mOkButton
.isEnabled()) {
1668 mOkButton
.performClick();
1671 } else if (actionId
== EditorInfo
.IME_ACTION_NEXT
&& inputField
!= null
&&
1672 inputField
.equals(mHostUrlInput
)) {
1673 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1674 equals(mAuthTokenType
)) {
1678 return false
; // always return false to grant that the software keyboard is hidden anyway
1682 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1684 private int fuzz
= 75;
1690 public boolean onTouch(View view
, MotionEvent event
) {
1691 Drawable rightDrawable
= null
;
1692 if (view
instanceof TextView
) {
1693 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1694 if (drawables
.length
> 2) {
1695 rightDrawable
= drawables
[2];
1698 if (rightDrawable
!= null
) {
1699 final int x
= (int) event
.getX();
1700 final int y
= (int) event
.getY();
1701 final Rect bounds
= rightDrawable
.getBounds();
1702 if ( x
>= (view
.getRight() - bounds
.width() - fuzz
) &&
1703 x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
) &&
1704 y
>= (view
.getPaddingTop() - fuzz
) &&
1705 y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1707 return onDrawableTouch(event
);
1713 public abstract boolean onDrawableTouch(final MotionEvent event
);
1717 private void getRemoteUserNameOperation(String sessionCookie
, boolean followRedirects
) {
1719 Intent getUserNameIntent
= new Intent();
1720 getUserNameIntent
.setAction(OperationsService
.ACTION_GET_USER_NAME
);
1721 getUserNameIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
1722 getUserNameIntent
.putExtra(OperationsService
.EXTRA_COOKIE
, sessionCookie
);
1724 if (mOperationsServiceBinder
!= null
) {
1725 //Log_OC.wtf(TAG, "starting getRemoteUserNameOperation..." );
1726 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getUserNameIntent
);
1732 public void onSsoFinished(String sessionCookie
) {
1733 if (sessionCookie
!= null
&& sessionCookie
.length() > 0) {
1734 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1735 mAuthToken
= sessionCookie
;
1736 getRemoteUserNameOperation(sessionCookie
, true
);
1737 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1738 if (fd
!= null
&& fd
instanceof SherlockDialogFragment
) {
1739 Dialog d
= ((SherlockDialogFragment
)fd
).getDialog();
1740 if (d
!= null
&& d
.isShowing()) {
1747 Log_OC
.d(TAG
, "SSO failed");
1753 public boolean onTouchEvent(MotionEvent event
) {
1754 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1755 equals(mAuthTokenType
) &&
1756 mHostUrlInput
.hasFocus() && event
.getAction() == MotionEvent
.ACTION_DOWN
) {
1759 return super.onTouchEvent(event
);
1764 * Show untrusted cert dialog
1766 public void showUntrustedCertDialog(
1767 X509Certificate x509Certificate
, SslError error
, SslErrorHandler handler
1769 // Show a dialog with the certificate info
1770 SslUntrustedCertDialog dialog
= null
;
1771 if (x509Certificate
== null
) {
1772 dialog
= SslUntrustedCertDialog
.newInstanceForEmptySslError(error
, handler
);
1774 dialog
= SslUntrustedCertDialog
.
1775 newInstanceForFullSslError(x509Certificate
, error
, handler
);
1777 FragmentManager fm
= getSupportFragmentManager();
1778 FragmentTransaction ft
= fm
.beginTransaction();
1779 ft
.addToBackStack(null
);
1780 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1785 * Show untrusted cert dialog
1787 private void showUntrustedCertDialog(RemoteOperationResult result
) {
1788 // Show a dialog with the certificate info
1789 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.
1790 newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1791 FragmentManager fm
= getSupportFragmentManager();
1792 FragmentTransaction ft
= fm
.beginTransaction();
1793 ft
.addToBackStack(null
);
1794 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1799 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1801 public void onSavedCertificate() {
1802 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1804 // if SAML dialog is not shown,
1805 // the SslDialog was shown due to an SSL error in the server check
1811 * Called from SslValidatorDialog when a new server certificate could not be saved
1812 * when the user requested it.
1815 public void onFailedSavingCertificate() {
1816 dismissDialog(SAML_DIALOG_TAG
);
1817 Toast
.makeText(this, R
.string
.ssl_validator_not_saved
, Toast
.LENGTH_LONG
).show();
1821 public void onCancelCertificate() {
1822 dismissDialog(SAML_DIALOG_TAG
);
1826 private void doOnResumeAndBound() {
1827 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1828 mOperationsServiceBinder
.addOperationListener(AuthenticatorActivity
.this, mHandler
);
1829 if (mWaitingForOpId
<= Integer
.MAX_VALUE
) {
1830 mOperationsServiceBinder
.dispatchResultIfFinished((int)mWaitingForOpId
, this);
1833 if (mPendingAutoCheck
) {
1839 private void dismissDialog(String dialogTag
){
1840 Fragment frag
= getSupportFragmentManager().findFragmentByTag(dialogTag
);
1841 if (frag
!= null
&& frag
instanceof SherlockDialogFragment
) {
1842 SherlockDialogFragment dialog
= (SherlockDialogFragment
) frag
;
1849 * Implements callback methods for service binding.
1851 private class OperationsServiceConnection
implements ServiceConnection
{
1854 public void onServiceConnected(ComponentName component
, IBinder service
) {
1855 if (component
.equals(
1856 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1858 //Log_OC.wtf(TAG, "Operations service connected");
1859 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
1861 doOnResumeAndBound();
1870 public void onServiceDisconnected(ComponentName component
) {
1871 if (component
.equals(
1872 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1874 Log_OC
.e(TAG
, "Operations service crashed");
1875 mOperationsServiceBinder
= null
;
1882 * Create and show dialog for request authentication to the user
1886 public void createAuthenticationDialog(WebView webView
, HttpAuthHandler handler
) {
1888 // Show a dialog with the certificate info
1889 CredentialsDialogFragment dialog
=
1890 CredentialsDialogFragment
.newInstanceForCredentials(webView
, handler
);
1891 FragmentManager fm
= getSupportFragmentManager();
1892 FragmentTransaction ft
= fm
.beginTransaction();
1893 ft
.addToBackStack(null
);
1894 dialog
.setCancelable(false
);
1895 dialog
.show(ft
, CREDENTIALS_DIALOG_TAG
);
1897 if (!mIsFirstAuthAttempt
) {
1899 getApplicationContext(),
1900 getText(R
.string
.saml_authentication_wrong_pass
),
1904 mIsFirstAuthAttempt
= false
;
1909 * For retrieving the clicking on authentication cancel button
1911 public void doNegativeAuthenticatioDialogClick(){
1912 mIsFirstAuthAttempt
= true
;
1917 public void onAuthenticatorTaskCallback(RemoteOperationResult result
) {
1918 //Log_OC.wtf(TAG, "received detection response through callback" );
1919 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1920 equals(mAuthTokenType
)) {
1921 onSamlBasedFederatedSingleSignOnAuthorizationStart(result
);
1924 onAuthorizationCheckFinish(result
);