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
.Constants
;
74 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
75 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
76 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
79 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
80 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
81 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
82 import com
.owncloud
.android
.lib
.resources
.users
.GetRemoteUserNameOperation
;
83 import com
.owncloud
.android
.operations
.DetectAuthenticationMethodOperation
.AuthenticationMethod
;
84 import com
.owncloud
.android
.operations
.GetServerInfoOperation
;
85 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
86 import com
.owncloud
.android
.services
.OperationsService
;
87 import com
.owncloud
.android
.services
.OperationsService
.OperationsServiceBinder
;
88 import com
.owncloud
.android
.ui
.dialog
.CredentialsDialogFragment
;
89 import com
.owncloud
.android
.ui
.dialog
.IndeterminateProgressDialog
;
90 import com
.owncloud
.android
.ui
.dialog
.SamlWebViewDialog
;
91 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
92 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
93 import com
.owncloud
.android
.utils
.DisplayUtils
;
96 * This Activity is used to add an ownCloud account to the App
98 * @author Bartek Przybylski
99 * @author David A. Velasco
102 public class AuthenticatorActivity
extends AccountAuthenticatorActivity
103 implements OnRemoteOperationListener
, OnFocusChangeListener
, OnEditorActionListener
,
104 SsoWebViewClientListener
, OnSslUntrustedCertListener
,
105 AuthenticatorAsyncTask
.OnAuthenticatorTaskListener
{
107 private static final String TAG
= AuthenticatorActivity
.class.getSimpleName();
109 public static final String EXTRA_ACTION
= "ACTION";
110 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
112 private static final String KEY_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
114 private static final String KEY_HOST_URL_TEXT
= "HOST_URL_TEXT";
115 private static final String KEY_OC_VERSION
= "OC_VERSION";
116 private static final String KEY_SERVER_VALID
= "SERVER_VALID";
117 private static final String KEY_SERVER_CHECKED
= "SERVER_CHECKED";
118 private static final String KEY_SERVER_STATUS_TEXT
= "SERVER_STATUS_TEXT";
119 private static final String KEY_SERVER_STATUS_ICON
= "SERVER_STATUS_ICON";
120 private static final String KEY_IS_SSL_CONN
= "IS_SSL_CONN";
121 private static final String KEY_PASSWORD_EXPOSED
= "PASSWORD_VISIBLE";
122 private static final String KEY_AUTH_STATUS_TEXT
= "AUTH_STATUS_TEXT";
123 private static final String KEY_AUTH_STATUS_ICON
= "AUTH_STATUS_ICON";
124 private static final String KEY_SERVER_AUTH_METHOD
= "SERVER_AUTH_METHOD";
125 private static final String KEY_WAITING_FOR_OP_ID
= "WAITING_FOR_OP_ID";
126 private static final String KEY_AUTH_TOKEN
= "AUTH_TOKEN";
128 private static final String AUTH_ON
= "on";
129 private static final String AUTH_OPTIONAL
= "optional";
131 public static final byte ACTION_CREATE
= 0;
132 public static final byte ACTION_UPDATE_TOKEN
= 1; // requested by the user
133 public static final byte ACTION_UPDATE_EXPIRED_TOKEN
= 2; // detected by the app
135 private static final String UNTRUSTED_CERT_DIALOG_TAG
= "UNTRUSTED_CERT_DIALOG";
136 private static final String SAML_DIALOG_TAG
= "SAML_DIALOG";
137 private static final String WAIT_DIALOG_TAG
= "WAIT_DIALOG";
138 private static final String CREDENTIALS_DIALOG_TAG
= "CREDENTIALS_DIALOG";
139 private static final String KEY_AUTH_IS_FIRST_ATTEMPT_TAG
= "KEY_AUTH_IS_FIRST_ATTEMPT";
142 /// parameters from EXTRAs in starter Intent
143 private byte mAction
;
144 private Account mAccount
;
145 private String mAuthTokenType
;
148 /// activity-level references / state
149 private final Handler mHandler
= new Handler();
150 private ServiceConnection mOperationsServiceConnection
= null
;
151 private OperationsServiceBinder mOperationsServiceBinder
= null
;
152 private AccountManager mAccountMgr
;
153 private Uri mNewCapturedUriFromOAuth2Redirection
;
156 /// Server PRE-Fragment elements
157 private EditText mHostUrlInput
;
158 private View mRefreshButton
;
159 private TextView mServerStatusView
;
161 private TextWatcher mHostUrlInputWatcher
;
162 private int mServerStatusText
= 0, mServerStatusIcon
= 0;
164 private boolean mServerIsChecked
= false
;
165 private boolean mServerIsValid
= false
;
166 private boolean mPendingAutoCheck
= false
;
168 private GetServerInfoOperation
.ServerInfo mServerInfo
=
169 new GetServerInfoOperation
.ServerInfo();
172 /// Authentication PRE-Fragment elements
173 private CheckBox mOAuth2Check
;
174 private TextView mOAuthAuthEndpointText
;
175 private TextView mOAuthTokenEndpointText
;
176 private EditText mUsernameInput
;
177 private EditText mPasswordInput
;
178 private View mOkButton
;
179 private TextView mAuthStatusView
;
181 private int mAuthStatusText
= 0, mAuthStatusIcon
= 0;
183 private String mAuthToken
= "";
185 private boolean mIsFirstAuthAttempt
;
188 /// Identifier of operation in progress which result shouldn't be lost
189 private long mWaitingForOpId
= Long
.MAX_VALUE
;
195 * IMPORTANT ENTRY POINT 1: activity is shown to the user
198 protected void onCreate(Bundle savedInstanceState
) {
199 //Log_OC.wtf(TAG, "onCreate init");
200 super.onCreate(savedInstanceState
);
201 getWindow().requestFeature(Window
.FEATURE_NO_TITLE
);
203 mIsFirstAuthAttempt
= true
;
205 // bind to Operations Service
206 mOperationsServiceConnection
= new OperationsServiceConnection();
207 if (!bindService(new Intent(this, OperationsService
.class),
208 mOperationsServiceConnection
,
209 Context
.BIND_AUTO_CREATE
)) {
211 R
.string
.error_cant_bind_to_operations_service
,
217 /// init activity state
218 mAccountMgr
= AccountManager
.get(this);
219 mNewCapturedUriFromOAuth2Redirection
= null
;
222 mAction
= getIntent().getByteExtra(EXTRA_ACTION
, ACTION_CREATE
);
223 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
224 if (savedInstanceState
== null
) {
227 mAuthTokenType
= savedInstanceState
.getString(KEY_AUTH_TOKEN_TYPE
);
228 mWaitingForOpId
= savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
);
229 mIsFirstAuthAttempt
= savedInstanceState
.getBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
);
234 /// load user interface
235 setContentView(R
.layout
.account_setup
);
237 /// initialize general UI elements
238 initOverallUi(savedInstanceState
);
240 mOkButton
= findViewById(R
.id
.buttonOK
);
242 /// initialize block to be moved to single Fragment to check server and get info about it
243 initServerPreFragment(savedInstanceState
);
245 /// initialize block to be moved to single Fragment to retrieve and validate credentials
246 initAuthorizationPreFragment(savedInstanceState
);
248 //Log_OC.wtf(TAG, "onCreate end");
251 private void initAuthTokenType() {
253 getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
254 if (mAuthTokenType
== null
) {
255 if (mAccount
!= null
) {
256 boolean oAuthRequired
=
257 (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
) != null
);
258 boolean samlWebSsoRequired
= (
259 mAccountMgr
.getUserData(
260 mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
263 mAuthTokenType
= chooseAuthTokenType(oAuthRequired
, samlWebSsoRequired
);
266 boolean oAuthSupported
= AUTH_ON
.equals(getString(R
.string
.auth_method_oauth2
));
267 boolean samlWebSsoSupported
=
268 AUTH_ON
.equals(getString(R
.string
.auth_method_saml_web_sso
));
269 mAuthTokenType
= chooseAuthTokenType(oAuthSupported
, samlWebSsoSupported
);
274 private String
chooseAuthTokenType(boolean oauth
, boolean saml
) {
276 return AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
278 return AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
280 return AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
286 * Configures elements in the user interface under direct control of the Activity.
288 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
290 private void initOverallUi(Bundle savedInstanceState
) {
292 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
293 boolean isWelcomeLinkVisible
= getResources().getBoolean(R
.bool
.show_welcome_link
);
295 String instructionsMessageText
= null
;
296 if (mAction
== ACTION_UPDATE_EXPIRED_TOKEN
) {
297 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
298 .equals(mAuthTokenType
)) {
299 instructionsMessageText
= getString(R
.string
.auth_expired_oauth_token_toast
);
301 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType())
302 .equals(mAuthTokenType
)) {
303 instructionsMessageText
= getString(R
.string
.auth_expired_saml_sso_token_toast
);
306 instructionsMessageText
= getString(R
.string
.auth_expired_basic_auth_toast
);
310 /// step 2 - set properties of UI elements (text, visibility, enabled...)
311 Button welcomeLink
= (Button
) findViewById(R
.id
.welcome_link
);
312 welcomeLink
.setVisibility(isWelcomeLinkVisible ? View
.VISIBLE
: View
.GONE
);
314 String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
316 TextView instructionsView
= (TextView
) findViewById(R
.id
.instructions_message
);
317 if (instructionsMessageText
!= null
) {
318 instructionsView
.setVisibility(View
.VISIBLE
);
319 instructionsView
.setText(instructionsMessageText
);
321 instructionsView
.setVisibility(View
.GONE
);
328 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
330 private void initServerPreFragment(Bundle savedInstanceState
) {
332 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
333 boolean isUrlInputAllowed
= getResources().getBoolean(R
.bool
.show_server_url_input
);
334 if (savedInstanceState
== null
) {
335 if (mAccount
!= null
) {
336 mServerInfo
.mBaseUrl
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_BASE_URL
);
337 // TODO do next in a setter for mBaseUrl
338 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
339 String ocVersion
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_VERSION
);
340 if (ocVersion
!= null
) {
341 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
344 mServerInfo
.mBaseUrl
= getString(R
.string
.server_url
).trim();
345 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
348 mServerStatusText
= savedInstanceState
.getInt(KEY_SERVER_STATUS_TEXT
);
349 mServerStatusIcon
= savedInstanceState
.getInt(KEY_SERVER_STATUS_ICON
);
351 mServerIsValid
= savedInstanceState
.getBoolean(KEY_SERVER_VALID
);
352 mServerIsChecked
= savedInstanceState
.getBoolean(KEY_SERVER_CHECKED
);
355 mServerInfo
.mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
356 mServerInfo
.mBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
357 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
358 if (ocVersion
!= null
) {
359 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
361 mServerInfo
.mAuthMethod
= AuthenticationMethod
.valueOf(
362 savedInstanceState
.getString(KEY_SERVER_AUTH_METHOD
));
366 /// step 2 - set properties of UI elements (text, visibility, enabled...)
367 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
368 // Convert IDN to Unicode
369 mHostUrlInput
.setText(DisplayUtils
.convertIdn(mServerInfo
.mBaseUrl
, false
));
370 if (mAction
!= ACTION_CREATE
) {
371 /// lock things that should not change
372 mHostUrlInput
.setEnabled(false
);
373 mHostUrlInput
.setFocusable(false
);
375 if (isUrlInputAllowed
) {
376 mRefreshButton
= findViewById(R
.id
.embeddedRefreshButton
);
378 findViewById(R
.id
.hostUrlFrame
).setVisibility(View
.GONE
);
379 mRefreshButton
= findViewById(R
.id
.centeredRefreshButton
);
381 showRefreshButton(mServerIsChecked
&& !mServerIsValid
&&
382 mWaitingForOpId
> Integer
.MAX_VALUE
);
383 mServerStatusView
= (TextView
) findViewById(R
.id
.server_status_text
);
386 /// step 3 - bind some listeners and options
387 mHostUrlInput
.setImeOptions(EditorInfo
.IME_ACTION_NEXT
);
388 mHostUrlInput
.setOnEditorActionListener(this);
390 /// step 4 - create listeners that will be bound at onResume
391 mHostUrlInputWatcher
= new TextWatcher() {
394 public void afterTextChanged(Editable s
) {
395 if (mOkButton
.isEnabled() &&
396 !mServerInfo
.mBaseUrl
.equals(
397 normalizeUrl(s
.toString(), mServerInfo
.mIsSslConn
))) {
398 mOkButton
.setEnabled(false
);
403 public void beforeTextChanged(CharSequence s
, int start
, int count
, int after
) {
407 public void onTextChanged(CharSequence s
, int start
, int before
, int count
) {
408 if (mAuthStatusIcon
!= 0) {
409 Log_OC
.d(TAG
, "onTextChanged: hiding authentication status");
418 // TODO find out if this is really necessary, or if it can done in a different way
419 findViewById(R
.id
.scroll
).setOnTouchListener(new OnTouchListener() {
421 public boolean onTouch(View view
, MotionEvent event
) {
422 if (event
.getAction() == MotionEvent
.ACTION_DOWN
) {
424 AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(
425 MainApp
.getAccountType()
426 ).equals(mAuthTokenType
) &&
427 mHostUrlInput
.hasFocus()
437 /// step 4 - mark automatic check to be started when OperationsService is ready
438 mPendingAutoCheck
= (savedInstanceState
== null
&&
439 (mAction
!= ACTION_CREATE
|| !isUrlInputAllowed
));
445 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
447 private void initAuthorizationPreFragment(Bundle savedInstanceState
) {
449 /// step 0 - get UI elements in layout
450 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
451 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
452 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
453 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
454 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
455 mAuthStatusView
= (TextView
) findViewById(R
.id
.auth_status_text
);
457 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
458 String presetUserName
= null
;
459 boolean isPasswordExposed
= false
;
460 if (savedInstanceState
== null
) {
461 if (mAccount
!= null
) {
462 presetUserName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
466 isPasswordExposed
= savedInstanceState
.getBoolean(KEY_PASSWORD_EXPOSED
, false
);
467 mAuthStatusText
= savedInstanceState
.getInt(KEY_AUTH_STATUS_TEXT
);
468 mAuthStatusIcon
= savedInstanceState
.getInt(KEY_AUTH_STATUS_ICON
);
469 mAuthToken
= savedInstanceState
.getString(KEY_AUTH_TOKEN
);
472 /// step 2 - set properties of UI elements (text, visibility, enabled...)
473 mOAuth2Check
.setChecked(
474 AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
475 .equals(mAuthTokenType
));
476 if (presetUserName
!= null
) {
477 mUsernameInput
.setText(presetUserName
);
479 if (mAction
!= ACTION_CREATE
) {
480 mUsernameInput
.setEnabled(false
);
481 mUsernameInput
.setFocusable(false
);
483 mPasswordInput
.setText(""); // clean password to avoid social hacking
484 if (isPasswordExposed
) {
487 updateAuthenticationPreFragmentVisibility();
489 mOkButton
.setEnabled(mServerIsValid
);
492 /// step 3 - bind listeners
493 // bindings for password input field
494 mPasswordInput
.setOnFocusChangeListener(this);
495 mPasswordInput
.setImeOptions(EditorInfo
.IME_ACTION_DONE
);
496 mPasswordInput
.setOnEditorActionListener(this);
497 mPasswordInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
499 public boolean onDrawableTouch(final MotionEvent event
) {
500 if (event
.getAction() == MotionEvent
.ACTION_UP
) {
501 AuthenticatorActivity
.this.onViewPasswordClick();
511 * Changes the visibility of input elements depending on
512 * the current authorization method.
514 private void updateAuthenticationPreFragmentVisibility () {
515 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
516 equals(mAuthTokenType
)) {
517 // SAML-based web Single Sign On
518 mOAuth2Check
.setVisibility(View
.GONE
);
519 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
520 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
521 mUsernameInput
.setVisibility(View
.GONE
);
522 mPasswordInput
.setVisibility(View
.GONE
);
525 if (mAction
== ACTION_CREATE
&&
526 AUTH_OPTIONAL
.equals(getString(R
.string
.auth_method_oauth2
))) {
527 mOAuth2Check
.setVisibility(View
.VISIBLE
);
529 mOAuth2Check
.setVisibility(View
.GONE
);
532 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
533 equals(mAuthTokenType
)) {
534 // OAuth 2 authorization
536 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
537 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
538 mUsernameInput
.setVisibility(View
.GONE
);
539 mPasswordInput
.setVisibility(View
.GONE
);
542 // basic HTTP authorization
543 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
544 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
545 mUsernameInput
.setVisibility(View
.VISIBLE
);
546 mPasswordInput
.setVisibility(View
.VISIBLE
);
554 * Saves relevant state before {@link #onPause()}
556 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag,
557 * intended to defer the processing of the redirection caught in
558 * {@link #onNewIntent(Intent)} until {@link #onResume()}
560 * See {@link #onSaveInstanceState(Bundle)}
563 protected void onSaveInstanceState(Bundle outState
) {
564 //Log_OC.wtf(TAG, "onSaveInstanceState init" );
565 super.onSaveInstanceState(outState
);
568 outState
.putString(KEY_AUTH_TOKEN_TYPE
, mAuthTokenType
);
569 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mWaitingForOpId
);
571 /// Server PRE-fragment state
572 outState
.putInt(KEY_SERVER_STATUS_TEXT
, mServerStatusText
);
573 outState
.putInt(KEY_SERVER_STATUS_ICON
, mServerStatusIcon
);
574 outState
.putBoolean(KEY_SERVER_CHECKED
, mServerIsChecked
);
575 outState
.putBoolean(KEY_SERVER_VALID
, mServerIsValid
);
576 outState
.putBoolean(KEY_IS_SSL_CONN
, mServerInfo
.mIsSslConn
);
577 outState
.putString(KEY_HOST_URL_TEXT
, mServerInfo
.mBaseUrl
);
578 if (mServerInfo
.mVersion
!= null
) {
579 outState
.putString(KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion());
581 outState
.putString(KEY_SERVER_AUTH_METHOD
, mServerInfo
.mAuthMethod
.name());
583 /// Authentication PRE-fragment state
584 outState
.putBoolean(KEY_PASSWORD_EXPOSED
, isPasswordVisible());
585 outState
.putInt(KEY_AUTH_STATUS_ICON
, mAuthStatusIcon
);
586 outState
.putInt(KEY_AUTH_STATUS_TEXT
, mAuthStatusText
);
587 outState
.putString(KEY_AUTH_TOKEN
, mAuthToken
);
590 outState
.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
, mIsFirstAuthAttempt
);
592 //Log_OC.wtf(TAG, "onSaveInstanceState end" );
597 * The redirection triggered by the OAuth authentication server as response to the
598 * GET AUTHORIZATION request is caught here.
600 * To make this possible, this activity needs to be qualified with android:launchMode =
601 * "singleTask" in the AndroidManifest.xml file.
604 protected void onNewIntent (Intent intent
) {
605 Log_OC
.d(TAG
, "onNewIntent()");
606 Uri data
= intent
.getData();
607 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
608 mNewCapturedUriFromOAuth2Redirection
= data
;
614 * The redirection triggered by the OAuth authentication server as response to the
615 * GET AUTHORIZATION, and deferred in {@link #onNewIntent(Intent)}, is processed here.
618 protected void onResume() {
619 //Log_OC.wtf(TAG, "onResume init" );
622 // bound here to avoid spurious changes triggered by Android on device rotations
623 mHostUrlInput
.setOnFocusChangeListener(this);
624 mHostUrlInput
.addTextChangedListener(mHostUrlInputWatcher
);
626 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
627 getOAuth2AccessTokenFromCapturedRedirection();
630 if (mOperationsServiceBinder
!= null
) {
631 doOnResumeAndBound();
634 //Log_OC.wtf(TAG, "onResume end" );
639 protected void onPause() {
640 //Log_OC.wtf(TAG, "onPause init" );
641 if (mOperationsServiceBinder
!= null
) {
642 //Log_OC.wtf(TAG, "unregistering to listen for operation callbacks" );
643 mOperationsServiceBinder
.removeOperationListener(this);
646 mHostUrlInput
.removeTextChangedListener(mHostUrlInputWatcher
);
647 mHostUrlInput
.setOnFocusChangeListener(null
);
650 //Log_OC.wtf(TAG, "onPause end" );
654 protected void onDestroy() {
656 mHostUrlInputWatcher
= null
;
658 if (mOperationsServiceConnection
!= null
) {
659 unbindService(mOperationsServiceConnection
);
660 mOperationsServiceBinder
= null
;
667 * Parses the redirection with the response to the GET AUTHORIZATION request to the
668 * oAuth server and requests for the access token (GET ACCESS TOKEN)
670 private void getOAuth2AccessTokenFromCapturedRedirection() {
671 /// Parse data from OAuth redirection
672 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
673 mNewCapturedUriFromOAuth2Redirection
= null
;
675 /// Showing the dialog with instructions for the user.
676 IndeterminateProgressDialog dialog
=
677 IndeterminateProgressDialog
.newInstance(R
.string
.auth_getting_authorization
, true
);
678 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
680 /// GET ACCESS TOKEN to the oAuth server
681 Intent getServerInfoIntent
= new Intent();
682 getServerInfoIntent
.setAction(OperationsService
.ACTION_OAUTH2_GET_ACCESS_TOKEN
);
684 getServerInfoIntent
.putExtra(
685 OperationsService
.EXTRA_SERVER_URL
,
686 mOAuthTokenEndpointText
.getText().toString().trim());
688 getServerInfoIntent
.putExtra(
689 OperationsService
.EXTRA_OAUTH2_QUERY_PARAMETERS
,
692 if (mOperationsServiceBinder
!= null
) {
693 //Log_OC.wtf(TAG, "getting access token..." );
694 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
701 * Handles the change of focus on the text inputs for the server URL and the password
703 public void onFocusChange(View view
, boolean hasFocus
) {
704 if (view
.getId() == R
.id
.hostUrlInput
) {
706 onUrlInputFocusLost((TextView
) view
);
709 showRefreshButton(false
);
712 } else if (view
.getId() == R
.id
.account_password
) {
713 onPasswordFocusChanged((TextView
) view
, hasFocus
);
719 * Handles changes in focus on the text input for the server URL.
721 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
722 * other field. The operation to check the existence of the server in the entered URL is
725 * When hasFocus: user 'comes back' to write again the server URL.
727 * @param hostInput TextView with the URL input field receiving the change of focus.
729 private void onUrlInputFocusLost(TextView hostInput
) {
730 if (!mServerInfo
.mBaseUrl
.equals(
731 normalizeUrl(mHostUrlInput
.getText().toString(), mServerInfo
.mIsSslConn
))) {
732 // check server again only if the user changed something in the field
735 mOkButton
.setEnabled(mServerIsValid
);
736 showRefreshButton(!mServerIsValid
);
741 private void checkOcServer() {
742 String uri
= mHostUrlInput
.getText().toString().trim();
743 mServerIsValid
= false
;
744 mServerIsChecked
= false
;
745 mOkButton
.setEnabled(false
);
746 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
747 showRefreshButton(false
);
749 if (uri
.length() != 0) {
750 // Handle internationalized domain names
751 uri
= DisplayUtils
.convertIdn(uri
, true
);
752 mServerStatusText
= R
.string
.auth_testing_connection
;
753 mServerStatusIcon
= R
.drawable
.progress_small
;
756 Intent getServerInfoIntent
= new Intent();
757 getServerInfoIntent
.setAction(OperationsService
.ACTION_GET_SERVER_INFO
);
758 getServerInfoIntent
.putExtra(
759 OperationsService
.EXTRA_SERVER_URL
,
760 normalizeUrlSuffix(uri
)
762 if (mOperationsServiceBinder
!= null
) {
763 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
765 Log_OC
.wtf(TAG
, "Server check tried with OperationService unbound!" );
769 mServerStatusText
= 0;
770 mServerStatusIcon
= 0;
777 * Handles changes in focus on the text input for the password (basic authorization).
779 * When (hasFocus), the button to toggle password visibility is shown.
781 * When (!hasFocus), the button is made invisible and the password is hidden.
783 * @param passwordInput TextView with the password input field receiving the change of focus.
784 * @param hasFocus 'True' if focus is received, 'false' if is lost
786 private void onPasswordFocusChanged(TextView passwordInput
, boolean hasFocus
) {
788 showViewPasswordButton();
791 hidePasswordButton();
796 private void showViewPasswordButton() {
797 int drawable
= R
.drawable
.ic_view
;
798 if (isPasswordVisible()) {
799 drawable
= R
.drawable
.ic_hide
;
801 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable
, 0);
804 private boolean isPasswordVisible() {
805 return ((mPasswordInput
.getInputType() & InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) ==
806 InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
809 private void hidePasswordButton() {
810 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
813 private void showPassword() {
814 mPasswordInput
.setInputType(
815 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
817 showViewPasswordButton();
820 private void hidePassword() {
821 mPasswordInput
.setInputType(
822 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
824 showViewPasswordButton();
828 * Checks the credentials of the user in the root of the ownCloud server
829 * before creating a new local account.
831 * For basic authorization, a check of existence of the root folder is
834 * For OAuth, starts the flow to get an access token; the credentials test
835 * is postponed until it is available.
837 * IMPORTANT ENTRY POINT 4
839 * @param view OK button
841 public void onOkClick(View view
) {
842 // this check should be unnecessary
843 if (mServerInfo
.mVersion
== null
||
844 !mServerInfo
.mVersion
.isVersionValid() ||
845 mServerInfo
.mBaseUrl
== null
||
846 mServerInfo
.mBaseUrl
.length() == 0) {
847 mServerStatusIcon
= R
.drawable
.common_error
;
848 mServerStatusText
= R
.string
.auth_wtf_reenter_URL
;
850 mOkButton
.setEnabled(false
);
851 //Log_OC.wtf(TAG, "The user was allowed to click 'connect' to an unchecked server!!");
855 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
856 equals(mAuthTokenType
)) {
858 startOauthorization();
859 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
860 equals(mAuthTokenType
)) {
862 startSamlBasedFederatedSingleSignOnAuthorization();
864 checkBasicAuthorization();
870 * Tests the credentials entered by the user performing a check of existence on
871 * the root folder of the ownCloud server.
873 private void checkBasicAuthorization() {
874 /// get basic credentials entered by user
875 String username
= mUsernameInput
.getText().toString();
876 String password
= mPasswordInput
.getText().toString();
878 /// be gentle with the user
879 IndeterminateProgressDialog dialog
=
880 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
881 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
883 /// validate credentials accessing the root folder
884 accessRootFolderRemoteOperation(username
, password
);
888 private void accessRootFolderRemoteOperation(String username
, String password
) {
889 // delete the account if the token has changed
890 if (mAction
== ACTION_UPDATE_TOKEN
|| mAction
== ACTION_UPDATE_EXPIRED_TOKEN
) {
891 // Remove the cookies in AccountManager
892 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_COOKIES
, null
);
895 AuthenticatorAsyncTask asyncTask
= new AuthenticatorAsyncTask(this);
896 String
[] params
= { mServerInfo
.mBaseUrl
, username
, password
, mAuthToken
, mAuthTokenType
};
897 asyncTask
.execute(params
);
902 * Starts the OAuth 'grant type' flow to get an access token, with
903 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
905 private void startOauthorization() {
906 // be gentle with the user
907 mAuthStatusIcon
= R
.drawable
.progress_small
;
908 mAuthStatusText
= R
.string
.oauth_login_connection
;
911 // GET AUTHORIZATION request
912 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
913 Uri
.Builder uriBuilder
= uri
.buildUpon();
914 uriBuilder
.appendQueryParameter(
915 OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
)
917 uriBuilder
.appendQueryParameter(
918 OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
)
920 uriBuilder
.appendQueryParameter(
921 OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
)
923 uriBuilder
.appendQueryParameter(
924 OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
)
926 uri
= uriBuilder
.build();
927 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
928 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
934 * Starts the Web Single Sign On flow to get access to the root folder
937 private void startSamlBasedFederatedSingleSignOnAuthorization() {
938 // be gentle with the user
939 mAuthStatusIcon
= R
.drawable
.progress_small
;
940 mAuthStatusText
= R
.string
.auth_connecting_auth_server
;
942 IndeterminateProgressDialog dialog
=
943 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
944 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
946 /// validate credentials accessing the root folder
947 accessRootFolderRemoteOperation("", "");
952 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
954 * Dispatches the operation flow to the right method.
957 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
959 if (operation
instanceof GetServerInfoOperation
) {
960 if (operation
.hashCode() == mWaitingForOpId
) {
961 onGetServerInfoFinish(result
);
962 } // else nothing ; only the last check operation is considered;
963 // multiple can be started if the user amends a URL quickly
965 } else if (operation
instanceof OAuth2GetAccessToken
) {
966 onGetOAuthAccessTokenFinish(result
);
968 } else if (operation
instanceof ExistenceCheckRemoteOperation
) {
969 // TODO : remove this response??
970 //Log_OC.wtf(TAG, "received detection response through callback" );
971 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
972 equals(mAuthTokenType
)) {
973 onSamlBasedFederatedSingleSignOnAuthorizationStart(result
);
976 onAuthorizationCheckFinish(result
);
978 } else if (operation
instanceof GetRemoteUserNameOperation
) {
979 onGetUserNameFinish(result
);
984 private void onGetUserNameFinish(RemoteOperationResult result
) {
985 mWaitingForOpId
= Long
.MAX_VALUE
;
986 if (result
.isSuccess()) {
987 boolean success
= false
;
988 String username
= (String
) result
.getData().get(0);
990 if ( mAction
== ACTION_CREATE
) {
991 mUsernameInput
.setText(username
);
992 success
= createAccount();
995 if (!mUsernameInput
.getText().toString().equals(username
)) {
996 // fail - not a new account, but an existing one; disallow
997 result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_THE_SAME
);
999 updateAuthStatusIconAndText(result
);
1001 Log_OC
.d(TAG
, result
.getLogMessage());
1003 updateAccountAuthentication();
1011 updateStatusIconFailUserName();
1013 Log_OC
.e(TAG
, "Access to user name failed: " + result
.getLogMessage());
1018 private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperationResult result
) {
1019 mWaitingForOpId
= Long
.MAX_VALUE
;
1020 dismissDialog(WAIT_DIALOG_TAG
);
1022 if (result
.isIdPRedirection()) {
1023 String targetUrl
= mServerInfo
.mBaseUrl
1024 + AccountUtils
.getWebdavPath(mServerInfo
.mVersion
, mAuthTokenType
);
1027 SamlWebViewDialog dialog
= SamlWebViewDialog
.newInstance(targetUrl
, targetUrl
);
1028 dialog
.show(getSupportFragmentManager(), SAML_DIALOG_TAG
);
1030 mAuthStatusIcon
= 0;
1031 mAuthStatusText
= 0;
1034 mAuthStatusIcon
= R
.drawable
.common_error
;
1035 mAuthStatusText
= R
.string
.auth_unsupported_auth_method
;
1043 * Processes the result of the server check performed when the user finishes the enter of the
1046 * @param result Result of the check.
1048 private void onGetServerInfoFinish(RemoteOperationResult result
) {
1049 /// update activity state
1050 mServerIsChecked
= true
;
1051 mWaitingForOpId
= Long
.MAX_VALUE
;
1053 // update server status, but don't show it yet
1054 updateServerStatusIconAndText(result
);
1056 if (result
.isSuccess()) {
1058 // 1. connection succeeded, and we know if it's SSL or not
1059 // 2. server is installed
1060 // 3. we got the server version
1061 // 4. we got the authentication method required by the server
1062 mServerInfo
= (GetServerInfoOperation
.ServerInfo
) (result
.getData().get(0));
1064 if (!authSupported(mServerInfo
.mAuthMethod
)) {
1066 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1067 mServerIsValid
= false
;
1070 mServerIsValid
= true
;
1074 mServerIsValid
= false
;
1078 showRefreshButton(!mServerIsValid
);
1080 mOkButton
.setEnabled(mServerIsValid
);
1082 /// very special case (TODO: move to a common place for all the remote operations)
1083 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1084 showUntrustedCertDialog(result
);
1089 private boolean authSupported(AuthenticationMethod authMethod
) {
1090 String basic
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1091 String oAuth
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1092 String saml
= AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
1094 return (( mAuthTokenType
.equals(basic
) &&
1095 authMethod
.equals(AuthenticationMethod
.BASIC_HTTP_AUTH
) ) ||
1096 ( mAuthTokenType
.equals(oAuth
) &&
1097 authMethod
.equals(AuthenticationMethod
.BEARER_TOKEN
)) ||
1098 ( mAuthTokenType
.equals(saml
) &&
1099 authMethod
.equals(AuthenticationMethod
.SAML_WEB_SSO
))
1104 // TODO remove, if possible
1105 private String
normalizeUrl(String url
, boolean sslWhenUnprefixed
) {
1106 if (url
!= null
&& url
.length() > 0) {
1108 if (!url
.toLowerCase().startsWith("http://") &&
1109 !url
.toLowerCase().startsWith("https://")) {
1110 if (sslWhenUnprefixed
) {
1111 url
= "https://" + url
;
1113 url
= "http://" + url
;
1117 url
= normalizeUrlSuffix(url
);
1119 return (url
!= null ? url
: "");
1123 private String
normalizeUrlSuffix(String url
) {
1124 if (url
.endsWith("/")) {
1125 url
= url
.substring(0, url
.length() - 1);
1127 url
= trimUrlWebdav(url
);
1132 // TODO remove, if possible
1133 private String
trimUrlWebdav(String url
){
1134 if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_4_0
)){
1135 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_4_0
.length());
1136 } else if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_2_0
)){
1137 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_2_0
.length());
1138 } else if (url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_1_2
)){
1139 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_1_2
.length());
1141 return (url
!= null ? url
: "");
1146 * Chooses the right icon and text to show to the user for the received operation result.
1148 * @param result Result of a remote operation performed in this activity
1150 private void updateServerStatusIconAndText(RemoteOperationResult result
) {
1151 mServerStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1153 switch (result
.getCode()) {
1155 mServerStatusIcon
= android
.R
.drawable
.ic_secure
;
1156 mServerStatusText
= R
.string
.auth_secure_connection
;
1161 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1162 mServerStatusText
= R
.string
.auth_connection_established
;
1163 mServerStatusIcon
= R
.drawable
.ic_ok
;
1165 mServerStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1166 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1170 case NO_NETWORK_CONNECTION
:
1171 mServerStatusIcon
= R
.drawable
.no_network
;
1172 mServerStatusText
= R
.string
.auth_no_net_conn_title
;
1175 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1176 mServerStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1178 case BAD_OC_VERSION
:
1179 mServerStatusText
= R
.string
.auth_bad_oc_version_title
;
1181 case WRONG_CONNECTION
:
1182 mServerStatusText
= R
.string
.auth_wrong_connection_title
;
1185 mServerStatusText
= R
.string
.auth_timeout_title
;
1187 case INCORRECT_ADDRESS
:
1188 mServerStatusText
= R
.string
.auth_incorrect_address_title
;
1191 mServerStatusText
= R
.string
.auth_ssl_general_error_title
;
1194 mServerStatusText
= R
.string
.auth_unauthorized
;
1196 case HOST_NOT_AVAILABLE
:
1197 mServerStatusText
= R
.string
.auth_unknown_host_title
;
1199 case INSTANCE_NOT_CONFIGURED
:
1200 mServerStatusText
= R
.string
.auth_not_configured_title
;
1202 case FILE_NOT_FOUND
:
1203 mServerStatusText
= R
.string
.auth_incorrect_path_title
;
1206 mServerStatusText
= R
.string
.auth_oauth_error
;
1208 case OAUTH2_ERROR_ACCESS_DENIED
:
1209 mServerStatusText
= R
.string
.auth_oauth_error_access_denied
;
1211 case UNHANDLED_HTTP_CODE
:
1213 mServerStatusText
= R
.string
.auth_unknown_error_title
;
1215 case OK_REDIRECT_TO_NON_SECURE_CONNECTION
:
1216 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1217 mServerStatusText
= R
.string
.auth_redirect_non_secure_connection_title
;
1220 mServerStatusText
= 0;
1221 mServerStatusIcon
= 0;
1227 * Chooses the right icon and text to show to the user for the received operation result.
1229 * @param result Result of a remote operation performed in this activity
1231 private void updateAuthStatusIconAndText(RemoteOperationResult result
) {
1232 mAuthStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1234 switch (result
.getCode()) {
1236 mAuthStatusIcon
= android
.R
.drawable
.ic_secure
;
1237 mAuthStatusText
= R
.string
.auth_secure_connection
;
1242 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1243 mAuthStatusText
= R
.string
.auth_connection_established
;
1244 mAuthStatusIcon
= R
.drawable
.ic_ok
;
1246 mAuthStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1247 mAuthStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1251 case NO_NETWORK_CONNECTION
:
1252 mAuthStatusIcon
= R
.drawable
.no_network
;
1253 mAuthStatusText
= R
.string
.auth_no_net_conn_title
;
1256 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1257 mAuthStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1259 case BAD_OC_VERSION
:
1260 mAuthStatusText
= R
.string
.auth_bad_oc_version_title
;
1262 case WRONG_CONNECTION
:
1263 mAuthStatusText
= R
.string
.auth_wrong_connection_title
;
1266 mAuthStatusText
= R
.string
.auth_timeout_title
;
1268 case INCORRECT_ADDRESS
:
1269 mAuthStatusText
= R
.string
.auth_incorrect_address_title
;
1272 mAuthStatusText
= R
.string
.auth_ssl_general_error_title
;
1275 mAuthStatusText
= R
.string
.auth_unauthorized
;
1277 case HOST_NOT_AVAILABLE
:
1278 mAuthStatusText
= R
.string
.auth_unknown_host_title
;
1280 case INSTANCE_NOT_CONFIGURED
:
1281 mAuthStatusText
= R
.string
.auth_not_configured_title
;
1283 case FILE_NOT_FOUND
:
1284 mAuthStatusText
= R
.string
.auth_incorrect_path_title
;
1287 mAuthStatusText
= R
.string
.auth_oauth_error
;
1289 case OAUTH2_ERROR_ACCESS_DENIED
:
1290 mAuthStatusText
= R
.string
.auth_oauth_error_access_denied
;
1292 case ACCOUNT_NOT_NEW
:
1293 mAuthStatusText
= R
.string
.auth_account_not_new
;
1295 case ACCOUNT_NOT_THE_SAME
:
1296 mAuthStatusText
= R
.string
.auth_account_not_the_same
;
1298 case UNHANDLED_HTTP_CODE
:
1300 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
1303 mAuthStatusText
= 0;
1304 mAuthStatusIcon
= 0;
1309 private void updateStatusIconFailUserName(){
1310 mAuthStatusIcon
= R
.drawable
.common_error
;
1311 mAuthStatusText
= R
.string
.auth_fail_get_user_name
;
1314 private void updateServerStatusIconNoRegularAuth(){
1315 mServerStatusIcon
= R
.drawable
.common_error
;
1316 mServerStatusText
= R
.string
.auth_can_not_auth_against_server
;
1320 * Processes the result of the request for and access token send
1321 * to an OAuth authorization server.
1323 * @param result Result of the operation.
1325 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result
) {
1326 mWaitingForOpId
= Long
.MAX_VALUE
;
1327 dismissDialog(WAIT_DIALOG_TAG
);
1329 if (result
.isSuccess()) {
1330 /// be gentle with the user
1331 IndeterminateProgressDialog dialog
=
1332 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
1333 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
1335 /// time to test the retrieved access token on the ownCloud server
1336 @SuppressWarnings("unchecked")
1337 Map
<String
, String
> tokens
= (Map
<String
, String
>)(result
.getData().get(0));
1338 mAuthToken
= tokens
.get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
1339 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mAuthToken
);
1341 accessRootFolderRemoteOperation("", "");
1344 updateAuthStatusIconAndText(result
);
1346 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1352 * Processes the result of the access check performed to try the user credentials.
1354 * Creates a new account through the AccountManager.
1356 * @param result Result of the operation.
1358 private void onAuthorizationCheckFinish(RemoteOperationResult result
) {
1359 mWaitingForOpId
= Long
.MAX_VALUE
;
1360 dismissDialog(WAIT_DIALOG_TAG
);
1362 if (result
.isSuccess()) {
1363 Log_OC
.d(TAG
, "Successful access - time to save the account");
1365 boolean success
= false
;
1366 if (mAction
== ACTION_CREATE
) {
1367 success
= createAccount();
1370 updateAccountAuthentication();
1378 } else if (result
.isServerFail() || result
.isException()) {
1379 /// server errors or exceptions in authorization take to requiring a new check of
1381 mServerIsChecked
= true
;
1382 mServerIsValid
= false
;
1383 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
1385 // update status icon and text
1386 updateServerStatusIconAndText(result
);
1388 mAuthStatusIcon
= 0;
1389 mAuthStatusText
= 0;
1392 // update input controls state
1393 showRefreshButton(true
);
1394 mOkButton
.setEnabled(false
);
1396 // very special case (TODO: move to a common place for all the remote operations)
1397 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1398 showUntrustedCertDialog(result
);
1401 } else { // authorization fail due to client side - probably wrong credentials
1402 updateAuthStatusIconAndText(result
);
1404 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1412 * Updates the authentication token.
1414 * Sets the proper response so that the AccountAuthenticator that started this activity
1415 * saves a new authorization token for mAccount.
1417 * Kills the session kept by OwnCloudClientManager so that a new one will created with
1418 * the new credentials when needed.
1420 private void updateAccountAuthentication() {
1423 OwnCloudClientManagerFactory
.getDefaultSingleton().removeClientFor(
1424 new OwnCloudAccount(mAccount
, this) // TODO avoid this creation may block the main thread
1426 } catch (Exception e
) {
1427 e
.printStackTrace();
1431 Bundle response
= new Bundle();
1432 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1433 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
1435 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
1436 equals(mAuthTokenType
)) {
1437 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1438 // the next line is necessary, notifications are calling directly to the
1439 // AuthenticatorActivity to update, without AccountManager intervention
1440 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1442 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1443 equals(mAuthTokenType
)) {
1445 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1446 // the next line is necessary; by now, notifications are calling directly to the
1447 // AuthenticatorActivity to update, without AccountManager intervention
1448 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1451 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
1452 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
1454 setAccountAuthenticatorResult(response
);
1460 * Creates a new account through the Account Authenticator that started this activity.
1462 * This makes the account permanent.
1464 * TODO Decide how to name the OAuth accounts
1466 private boolean createAccount() {
1467 /// create and save new ownCloud account
1468 boolean isOAuth
= AccountTypeUtils
.
1469 getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
);
1470 boolean isSaml
= AccountTypeUtils
.
1471 getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
);
1473 Uri uri
= Uri
.parse(mServerInfo
.mBaseUrl
);
1474 String username
= mUsernameInput
.getText().toString().trim();
1476 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1478 String accountName
= com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.
1479 buildAccountName(uri
, username
);
1480 Account newAccount
= new Account(accountName
, MainApp
.getAccountType());
1481 if (AccountUtils
.exists(newAccount
, getApplicationContext())) {
1482 // fail - not a new account, but an existing one; disallow
1483 RemoteOperationResult result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_NEW
);
1484 updateAuthStatusIconAndText(result
);
1486 Log_OC
.d(TAG
, result
.getLogMessage());
1490 mAccount
= newAccount
;
1492 if (isOAuth
|| isSaml
) {
1493 // with external authorizations, the password is never input in the app
1494 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
);
1496 mAccountMgr
.addAccountExplicitly(
1497 mAccount
, mPasswordInput
.getText().toString(), null
1501 /// add the new account as default in preferences, if there is none already
1502 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1503 if (defaultAccount
== null
) {
1504 SharedPreferences
.Editor editor
= PreferenceManager
1505 .getDefaultSharedPreferences(this).edit();
1506 editor
.putString("select_oc_account", accountName
);
1510 /// prepare result to return to the Authenticator
1511 // TODO check again what the Authenticator makes with it; probably has the same
1512 // effect as addAccountExplicitly, but it's not well done
1513 final Intent intent
= new Intent();
1514 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, MainApp
.getAccountType());
1515 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1517 intent.putExtra(AccountManager.KEY_AUTHTOKEN, MainApp.getAccountType()); */
1518 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1519 if (isOAuth
|| isSaml
) {
1520 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1522 /// add user data to the new account; TODO probably can be done in the last parameter
1523 // addAccountExplicitly, or in KEY_USERDATA
1524 mAccountMgr
.setUserData(
1525 mAccount
, Constants
.KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion()
1527 mAccountMgr
.setUserData(
1528 mAccount
, Constants
.KEY_OC_BASE_URL
, mServerInfo
.mBaseUrl
1532 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
, "TRUE");
1533 } else if (isOAuth
) {
1534 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
, "TRUE");
1537 setAccountAuthenticatorResult(intent
.getExtras());
1538 setResult(RESULT_OK
, intent
);
1546 * Starts and activity to open the 'new account' page in the ownCloud web site
1548 * @param view 'Account register' button
1550 public void onRegisterClick(View view
) {
1551 Intent register
= new Intent(
1552 Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.welcome_link_url
))
1554 setResult(RESULT_CANCELED
);
1555 startActivity(register
);
1560 * Updates the content and visibility state of the icon and text associated
1561 * to the last check on the ownCloud server.
1563 private void showServerStatus() {
1564 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1565 mServerStatusView
.setVisibility(View
.INVISIBLE
);
1568 mServerStatusView
.setText(mServerStatusText
);
1569 mServerStatusView
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1570 mServerStatusView
.setVisibility(View
.VISIBLE
);
1577 * Updates the content and visibility state of the icon and text associated
1578 * to the interactions with the OAuth authorization server.
1580 private void showAuthStatus() {
1581 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1582 mAuthStatusView
.setVisibility(View
.INVISIBLE
);
1585 mAuthStatusView
.setText(mAuthStatusText
);
1586 mAuthStatusView
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1587 mAuthStatusView
.setVisibility(View
.VISIBLE
);
1592 private void showRefreshButton (boolean show
) {
1594 mRefreshButton
.setVisibility(View
.VISIBLE
);
1596 mRefreshButton
.setVisibility(View
.GONE
);
1601 * Called when the refresh button in the input field for ownCloud host is clicked.
1603 * Performs a new check on the URL in the input field.
1605 * @param view Refresh 'button'
1607 public void onRefreshClick(View view
) {
1613 * Called when the eye icon in the password field is clicked.
1615 * Toggles the visibility of the password in the field.
1617 public void onViewPasswordClick() {
1618 int selectionStart
= mPasswordInput
.getSelectionStart();
1619 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1620 if (isPasswordVisible()) {
1625 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1630 * Called when the checkbox for OAuth authorization is clicked.
1632 * Hides or shows the input fields for user & password.
1634 * @param view 'View password' 'button'
1636 public void onCheckClick(View view
) {
1637 CheckBox oAuth2Check
= (CheckBox
)view
;
1638 if (oAuth2Check
.isChecked()) {
1639 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1641 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1643 updateAuthenticationPreFragmentVisibility();
1648 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1650 * Used to trigger the authentication check when the user presses 'enter' after writing the
1651 * password, or to throw the server test when the only field on screen is the URL input field.
1654 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1655 if (actionId
== EditorInfo
.IME_ACTION_DONE
&& inputField
!= null
&&
1656 inputField
.equals(mPasswordInput
)) {
1657 if (mOkButton
.isEnabled()) {
1658 mOkButton
.performClick();
1661 } else if (actionId
== EditorInfo
.IME_ACTION_NEXT
&& inputField
!= null
&&
1662 inputField
.equals(mHostUrlInput
)) {
1663 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1664 equals(mAuthTokenType
)) {
1668 return false
; // always return false to grant that the software keyboard is hidden anyway
1672 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1674 private int fuzz
= 75;
1680 public boolean onTouch(View view
, MotionEvent event
) {
1681 Drawable rightDrawable
= null
;
1682 if (view
instanceof TextView
) {
1683 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1684 if (drawables
.length
> 2) {
1685 rightDrawable
= drawables
[2];
1688 if (rightDrawable
!= null
) {
1689 final int x
= (int) event
.getX();
1690 final int y
= (int) event
.getY();
1691 final Rect bounds
= rightDrawable
.getBounds();
1692 if ( x
>= (view
.getRight() - bounds
.width() - fuzz
) &&
1693 x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
) &&
1694 y
>= (view
.getPaddingTop() - fuzz
) &&
1695 y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1697 return onDrawableTouch(event
);
1703 public abstract boolean onDrawableTouch(final MotionEvent event
);
1707 private void getRemoteUserNameOperation(String sessionCookie
, boolean followRedirects
) {
1709 Intent getUserNameIntent
= new Intent();
1710 getUserNameIntent
.setAction(OperationsService
.ACTION_GET_USER_NAME
);
1711 getUserNameIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
1712 getUserNameIntent
.putExtra(OperationsService
.EXTRA_COOKIE
, sessionCookie
);
1714 if (mOperationsServiceBinder
!= null
) {
1715 //Log_OC.wtf(TAG, "starting getRemoteUserNameOperation..." );
1716 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getUserNameIntent
);
1722 public void onSsoFinished(String sessionCookie
) {
1723 if (sessionCookie
!= null
&& sessionCookie
.length() > 0) {
1724 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1725 mAuthToken
= sessionCookie
;
1726 getRemoteUserNameOperation(sessionCookie
, true
);
1727 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1728 if (fd
!= null
&& fd
instanceof SherlockDialogFragment
) {
1729 Dialog d
= ((SherlockDialogFragment
)fd
).getDialog();
1730 if (d
!= null
&& d
.isShowing()) {
1737 Log_OC
.d(TAG
, "SSO failed");
1743 public boolean onTouchEvent(MotionEvent event
) {
1744 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1745 equals(mAuthTokenType
) &&
1746 mHostUrlInput
.hasFocus() && event
.getAction() == MotionEvent
.ACTION_DOWN
) {
1749 return super.onTouchEvent(event
);
1754 * Show untrusted cert dialog
1756 public void showUntrustedCertDialog(
1757 X509Certificate x509Certificate
, SslError error
, SslErrorHandler handler
1759 // Show a dialog with the certificate info
1760 SslUntrustedCertDialog dialog
= null
;
1761 if (x509Certificate
== null
) {
1762 dialog
= SslUntrustedCertDialog
.newInstanceForEmptySslError(error
, handler
);
1764 dialog
= SslUntrustedCertDialog
.
1765 newInstanceForFullSslError(x509Certificate
, error
, handler
);
1767 FragmentManager fm
= getSupportFragmentManager();
1768 FragmentTransaction ft
= fm
.beginTransaction();
1769 ft
.addToBackStack(null
);
1770 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1775 * Show untrusted cert dialog
1777 private void showUntrustedCertDialog(RemoteOperationResult result
) {
1778 // Show a dialog with the certificate info
1779 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.
1780 newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1781 FragmentManager fm
= getSupportFragmentManager();
1782 FragmentTransaction ft
= fm
.beginTransaction();
1783 ft
.addToBackStack(null
);
1784 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1789 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1791 public void onSavedCertificate() {
1792 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1794 // if SAML dialog is not shown,
1795 // the SslDialog was shown due to an SSL error in the server check
1801 * Called from SslValidatorDialog when a new server certificate could not be saved
1802 * when the user requested it.
1805 public void onFailedSavingCertificate() {
1806 dismissDialog(SAML_DIALOG_TAG
);
1807 Toast
.makeText(this, R
.string
.ssl_validator_not_saved
, Toast
.LENGTH_LONG
).show();
1811 public void onCancelCertificate() {
1812 dismissDialog(SAML_DIALOG_TAG
);
1816 private void doOnResumeAndBound() {
1817 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1818 mOperationsServiceBinder
.addOperationListener(AuthenticatorActivity
.this, mHandler
);
1819 if (mWaitingForOpId
<= Integer
.MAX_VALUE
) {
1820 mOperationsServiceBinder
.dispatchResultIfFinished((int)mWaitingForOpId
, this);
1823 if (mPendingAutoCheck
) {
1829 private void dismissDialog(String dialogTag
){
1830 Fragment frag
= getSupportFragmentManager().findFragmentByTag(dialogTag
);
1831 if (frag
!= null
&& frag
instanceof SherlockDialogFragment
) {
1832 SherlockDialogFragment dialog
= (SherlockDialogFragment
) frag
;
1839 * Implements callback methods for service binding.
1841 private class OperationsServiceConnection
implements ServiceConnection
{
1844 public void onServiceConnected(ComponentName component
, IBinder service
) {
1845 if (component
.equals(
1846 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1848 //Log_OC.wtf(TAG, "Operations service connected");
1849 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
1851 doOnResumeAndBound();
1860 public void onServiceDisconnected(ComponentName component
) {
1861 if (component
.equals(
1862 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1864 Log_OC
.e(TAG
, "Operations service crashed");
1865 mOperationsServiceBinder
= null
;
1872 * Create and show dialog for request authentication to the user
1876 public void createAuthenticationDialog(WebView webView
, HttpAuthHandler handler
) {
1878 // Show a dialog with the certificate info
1879 CredentialsDialogFragment dialog
=
1880 CredentialsDialogFragment
.newInstanceForCredentials(webView
, handler
);
1881 FragmentManager fm
= getSupportFragmentManager();
1882 FragmentTransaction ft
= fm
.beginTransaction();
1883 ft
.addToBackStack(null
);
1884 dialog
.setCancelable(false
);
1885 dialog
.show(ft
, CREDENTIALS_DIALOG_TAG
);
1887 if (!mIsFirstAuthAttempt
) {
1889 getApplicationContext(),
1890 getText(R
.string
.saml_authentication_wrong_pass
),
1894 mIsFirstAuthAttempt
= false
;
1899 * For retrieving the clicking on authentication cancel button
1901 public void doNegativeAuthenticatioDialogClick(){
1902 mIsFirstAuthAttempt
= true
;
1907 public void onAuthenticatorTaskCallback(RemoteOperationResult result
) {
1908 //Log_OC.wtf(TAG, "received detection response through callback" );
1909 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1910 equals(mAuthTokenType
)) {
1911 onSamlBasedFederatedSingleSignOnAuthorizationStart(result
);
1914 onAuthorizationCheckFinish(result
);