1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2015 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.authentication
;
21 import java
.security
.cert
.X509Certificate
;
24 import android
.accounts
.Account
;
25 import android
.accounts
.AccountManager
;
26 import android
.app
.Dialog
;
27 import android
.content
.ComponentName
;
28 import android
.content
.Context
;
29 import android
.content
.Intent
;
30 import android
.content
.ServiceConnection
;
31 import android
.content
.SharedPreferences
;
32 import android
.graphics
.Rect
;
33 import android
.graphics
.drawable
.Drawable
;
34 import android
.net
.Uri
;
35 import android
.net
.http
.SslError
;
36 import android
.os
.AsyncTask
;
37 import android
.os
.Bundle
;
38 import android
.os
.Handler
;
39 import android
.os
.IBinder
;
40 import android
.preference
.PreferenceManager
;
41 import android
.support
.v4
.app
.Fragment
;
42 import android
.support
.v4
.app
.FragmentManager
;
43 import android
.support
.v4
.app
.FragmentTransaction
;
44 import android
.text
.Editable
;
45 import android
.text
.InputType
;
46 import android
.text
.TextWatcher
;
47 import android
.view
.KeyEvent
;
48 import android
.view
.MotionEvent
;
49 import android
.view
.View
;
50 import android
.view
.View
.OnFocusChangeListener
;
51 import android
.view
.View
.OnTouchListener
;
52 import android
.view
.Window
;
53 import android
.view
.inputmethod
.EditorInfo
;
54 import android
.webkit
.HttpAuthHandler
;
55 import android
.webkit
.SslErrorHandler
;
56 import android
.webkit
.WebView
;
57 import android
.widget
.Button
;
58 import android
.widget
.CheckBox
;
59 import android
.widget
.EditText
;
60 import android
.widget
.TextView
;
61 import android
.widget
.TextView
.OnEditorActionListener
;
62 import android
.widget
.Toast
;
64 import com
.actionbarsherlock
.app
.SherlockDialogFragment
;
65 import com
.owncloud
.android
.MainApp
;
66 import com
.owncloud
.android
.R
;
67 import com
.owncloud
.android
.authentication
.SsoWebViewClient
.SsoWebViewClientListener
;
68 import com
.owncloud
.android
.lib
.common
.accounts
.AccountTypeUtils
;
69 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.Constants
;
70 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
71 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
72 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
73 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
74 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
75 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
76 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
77 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
78 import com
.owncloud
.android
.lib
.resources
.users
.GetRemoteUserNameOperation
;
79 import com
.owncloud
.android
.operations
.DetectAuthenticationMethodOperation
.AuthenticationMethod
;
80 import com
.owncloud
.android
.operations
.GetServerInfoOperation
;
81 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
82 import com
.owncloud
.android
.services
.OperationsService
;
83 import com
.owncloud
.android
.services
.OperationsService
.OperationsServiceBinder
;
84 import com
.owncloud
.android
.ui
.dialog
.CredentialsDialogFragment
;
85 import com
.owncloud
.android
.ui
.dialog
.IndeterminateProgressDialog
;
86 import com
.owncloud
.android
.ui
.dialog
.SamlWebViewDialog
;
87 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
88 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
89 import com
.owncloud
.android
.utils
.DisplayUtils
;
92 * This Activity is used to add an ownCloud account to the App
94 * @author Bartek Przybylski
95 * @author David A. Velasco
98 public class AuthenticatorActivity
extends AccountAuthenticatorActivity
99 implements OnRemoteOperationListener
, OnFocusChangeListener
, OnEditorActionListener
,
100 SsoWebViewClientListener
, OnSslUntrustedCertListener
,
101 AuthenticatorAsyncTask
.OnAuthenticatorTaskListener
{
103 private static final String TAG
= AuthenticatorActivity
.class.getSimpleName();
105 public static final String EXTRA_ACTION
= "ACTION";
106 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
108 private static final String KEY_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
110 private static final String KEY_HOST_URL_TEXT
= "HOST_URL_TEXT";
111 private static final String KEY_OC_VERSION
= "OC_VERSION";
112 private static final String KEY_SERVER_VALID
= "SERVER_VALID";
113 private static final String KEY_SERVER_CHECKED
= "SERVER_CHECKED";
114 private static final String KEY_SERVER_STATUS_TEXT
= "SERVER_STATUS_TEXT";
115 private static final String KEY_SERVER_STATUS_ICON
= "SERVER_STATUS_ICON";
116 private static final String KEY_IS_SSL_CONN
= "IS_SSL_CONN";
117 private static final String KEY_PASSWORD_EXPOSED
= "PASSWORD_VISIBLE";
118 private static final String KEY_AUTH_STATUS_TEXT
= "AUTH_STATUS_TEXT";
119 private static final String KEY_AUTH_STATUS_ICON
= "AUTH_STATUS_ICON";
120 private static final String KEY_SERVER_AUTH_METHOD
= "SERVER_AUTH_METHOD";
121 private static final String KEY_WAITING_FOR_OP_ID
= "WAITING_FOR_OP_ID";
122 private static final String KEY_AUTH_TOKEN
= "AUTH_TOKEN";
124 private static final String AUTH_ON
= "on";
125 private static final String AUTH_OPTIONAL
= "optional";
127 public static final byte ACTION_CREATE
= 0;
128 public static final byte ACTION_UPDATE_TOKEN
= 1; // requested by the user
129 public static final byte ACTION_UPDATE_EXPIRED_TOKEN
= 2; // detected by the app
131 private static final String UNTRUSTED_CERT_DIALOG_TAG
= "UNTRUSTED_CERT_DIALOG";
132 private static final String SAML_DIALOG_TAG
= "SAML_DIALOG";
133 private static final String WAIT_DIALOG_TAG
= "WAIT_DIALOG";
134 private static final String CREDENTIALS_DIALOG_TAG
= "CREDENTIALS_DIALOG";
135 private static final String KEY_AUTH_IS_FIRST_ATTEMPT_TAG
= "KEY_AUTH_IS_FIRST_ATTEMPT";
137 private static final String KEY_USERNAME
= "USERNAME";
138 private static final String KEY_PASSWORD
= "PASSWORD";
139 private static final String KEY_ASYNC_TASK_IN_PROGRESS
= "AUTH_IN_PROGRESS";
141 /// parameters from EXTRAs in starter Intent
142 private byte mAction
;
143 private Account mAccount
;
144 private String mAuthTokenType
;
147 /// activity-level references / state
148 private final Handler mHandler
= new Handler();
149 private ServiceConnection mOperationsServiceConnection
= null
;
150 private OperationsServiceBinder mOperationsServiceBinder
= null
;
151 private AccountManager mAccountMgr
;
152 private Uri mNewCapturedUriFromOAuth2Redirection
;
155 /// Server PRE-Fragment elements
156 private EditText mHostUrlInput
;
157 private View mRefreshButton
;
158 private TextView mServerStatusView
;
160 private TextWatcher mHostUrlInputWatcher
;
161 private int mServerStatusText
= 0, mServerStatusIcon
= 0;
163 private boolean mServerIsChecked
= false
;
164 private boolean mServerIsValid
= false
;
165 private boolean mPendingAutoCheck
= false
;
167 private GetServerInfoOperation
.ServerInfo mServerInfo
=
168 new GetServerInfoOperation
.ServerInfo();
171 /// Authentication PRE-Fragment elements
172 private CheckBox mOAuth2Check
;
173 private TextView mOAuthAuthEndpointText
;
174 private TextView mOAuthTokenEndpointText
;
175 private EditText mUsernameInput
;
176 private EditText mPasswordInput
;
177 private View mOkButton
;
178 private TextView mAuthStatusView
;
180 private int mAuthStatusText
= 0, mAuthStatusIcon
= 0;
182 private String mAuthToken
= "";
183 private AuthenticatorAsyncTask mAsyncTask
;
185 private boolean mIsFirstAuthAttempt
;
187 /// Identifier of operation in progress which result shouldn't be lost
188 private long mWaitingForOpId
= Long
.MAX_VALUE
;
194 * IMPORTANT ENTRY POINT 1: activity is shown to the user
197 protected void onCreate(Bundle savedInstanceState
) {
198 //Log_OC.wtf(TAG, "onCreate init");
199 super.onCreate(savedInstanceState
);
200 getWindow().requestFeature(Window
.FEATURE_NO_TITLE
);
202 mIsFirstAuthAttempt
= true
;
204 // bind to Operations Service
205 mOperationsServiceConnection
= new OperationsServiceConnection();
206 if (!bindService(new Intent(this, OperationsService
.class),
207 mOperationsServiceConnection
,
208 Context
.BIND_AUTO_CREATE
)) {
210 R
.string
.error_cant_bind_to_operations_service
,
216 /// init activity state
217 mAccountMgr
= AccountManager
.get(this);
218 mNewCapturedUriFromOAuth2Redirection
= null
;
221 mAction
= getIntent().getByteExtra(EXTRA_ACTION
, ACTION_CREATE
);
222 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
223 if (savedInstanceState
== null
) {
226 mAuthTokenType
= savedInstanceState
.getString(KEY_AUTH_TOKEN_TYPE
);
227 mWaitingForOpId
= savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
);
228 mIsFirstAuthAttempt
= savedInstanceState
.getBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
);
233 /// load user interface
234 setContentView(R
.layout
.account_setup
);
236 /// initialize general UI elements
237 initOverallUi(savedInstanceState
);
239 mOkButton
= findViewById(R
.id
.buttonOK
);
241 /// initialize block to be moved to single Fragment to check server and get info about it
242 initServerPreFragment(savedInstanceState
);
244 /// initialize block to be moved to single Fragment to retrieve and validate credentials
245 initAuthorizationPreFragment(savedInstanceState
);
247 //Log_OC.wtf(TAG, "onCreate end");
250 private void initAuthTokenType() {
252 getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
253 if (mAuthTokenType
== null
) {
254 if (mAccount
!= null
) {
255 boolean oAuthRequired
=
256 (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
) != null
);
257 boolean samlWebSsoRequired
= (
258 mAccountMgr
.getUserData(
259 mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
262 mAuthTokenType
= chooseAuthTokenType(oAuthRequired
, samlWebSsoRequired
);
265 boolean oAuthSupported
= AUTH_ON
.equals(getString(R
.string
.auth_method_oauth2
));
266 boolean samlWebSsoSupported
=
267 AUTH_ON
.equals(getString(R
.string
.auth_method_saml_web_sso
));
268 mAuthTokenType
= chooseAuthTokenType(oAuthSupported
, samlWebSsoSupported
);
273 private String
chooseAuthTokenType(boolean oauth
, boolean saml
) {
275 return AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
277 return AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
279 return AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
285 * Configures elements in the user interface under direct control of the Activity.
287 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
289 private void initOverallUi(Bundle savedInstanceState
) {
291 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
292 boolean isWelcomeLinkVisible
= getResources().getBoolean(R
.bool
.show_welcome_link
);
294 String instructionsMessageText
= null
;
295 if (mAction
== ACTION_UPDATE_EXPIRED_TOKEN
) {
296 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
297 .equals(mAuthTokenType
)) {
298 instructionsMessageText
= getString(R
.string
.auth_expired_oauth_token_toast
);
300 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType())
301 .equals(mAuthTokenType
)) {
302 instructionsMessageText
= getString(R
.string
.auth_expired_saml_sso_token_toast
);
305 instructionsMessageText
= getString(R
.string
.auth_expired_basic_auth_toast
);
309 /// step 2 - set properties of UI elements (text, visibility, enabled...)
310 Button welcomeLink
= (Button
) findViewById(R
.id
.welcome_link
);
311 welcomeLink
.setVisibility(isWelcomeLinkVisible ? View
.VISIBLE
: View
.GONE
);
313 String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
315 TextView instructionsView
= (TextView
) findViewById(R
.id
.instructions_message
);
316 if (instructionsMessageText
!= null
) {
317 instructionsView
.setVisibility(View
.VISIBLE
);
318 instructionsView
.setText(instructionsMessageText
);
320 instructionsView
.setVisibility(View
.GONE
);
327 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
329 private void initServerPreFragment(Bundle savedInstanceState
) {
331 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
332 boolean isUrlInputAllowed
= getResources().getBoolean(R
.bool
.show_server_url_input
);
333 if (savedInstanceState
== null
) {
334 if (mAccount
!= null
) {
335 mServerInfo
.mBaseUrl
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_BASE_URL
);
336 // TODO do next in a setter for mBaseUrl
337 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
338 String ocVersion
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_VERSION
);
339 if (ocVersion
!= null
) {
340 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
343 mServerInfo
.mBaseUrl
= getString(R
.string
.server_url
).trim();
344 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
347 mServerStatusText
= savedInstanceState
.getInt(KEY_SERVER_STATUS_TEXT
);
348 mServerStatusIcon
= savedInstanceState
.getInt(KEY_SERVER_STATUS_ICON
);
350 mServerIsValid
= savedInstanceState
.getBoolean(KEY_SERVER_VALID
);
351 mServerIsChecked
= savedInstanceState
.getBoolean(KEY_SERVER_CHECKED
);
354 mServerInfo
.mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
355 mServerInfo
.mBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
356 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
357 if (ocVersion
!= null
) {
358 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
360 mServerInfo
.mAuthMethod
= AuthenticationMethod
.valueOf(
361 savedInstanceState
.getString(KEY_SERVER_AUTH_METHOD
));
365 /// step 2 - set properties of UI elements (text, visibility, enabled...)
366 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
367 // Convert IDN to Unicode
368 mHostUrlInput
.setText(DisplayUtils
.convertIdn(mServerInfo
.mBaseUrl
, false
));
369 if (mAction
!= ACTION_CREATE
) {
370 /// lock things that should not change
371 mHostUrlInput
.setEnabled(false
);
372 mHostUrlInput
.setFocusable(false
);
374 if (isUrlInputAllowed
) {
375 mRefreshButton
= findViewById(R
.id
.embeddedRefreshButton
);
377 findViewById(R
.id
.hostUrlFrame
).setVisibility(View
.GONE
);
378 mRefreshButton
= findViewById(R
.id
.centeredRefreshButton
);
380 showRefreshButton(mServerIsChecked
&& !mServerIsValid
&&
381 mWaitingForOpId
> Integer
.MAX_VALUE
);
382 mServerStatusView
= (TextView
) findViewById(R
.id
.server_status_text
);
385 /// step 3 - bind some listeners and options
386 mHostUrlInput
.setImeOptions(EditorInfo
.IME_ACTION_NEXT
);
387 mHostUrlInput
.setOnEditorActionListener(this);
389 /// step 4 - create listeners that will be bound at onResume
390 mHostUrlInputWatcher
= new TextWatcher() {
393 public void afterTextChanged(Editable s
) {
394 if (mOkButton
.isEnabled() &&
395 !mServerInfo
.mBaseUrl
.equals(
396 normalizeUrl(s
.toString(), mServerInfo
.mIsSslConn
))) {
397 mOkButton
.setEnabled(false
);
402 public void beforeTextChanged(CharSequence s
, int start
, int count
, int after
) {
406 public void onTextChanged(CharSequence s
, int start
, int before
, int count
) {
407 if (mAuthStatusIcon
!= 0) {
408 Log_OC
.d(TAG
, "onTextChanged: hiding authentication status");
417 // TODO find out if this is really necessary, or if it can done in a different way
418 findViewById(R
.id
.scroll
).setOnTouchListener(new OnTouchListener() {
420 public boolean onTouch(View view
, MotionEvent event
) {
421 if (event
.getAction() == MotionEvent
.ACTION_DOWN
) {
423 AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(
424 MainApp
.getAccountType()
425 ).equals(mAuthTokenType
) &&
426 mHostUrlInput
.hasFocus()
436 /// step 4 - mark automatic check to be started when OperationsService is ready
437 mPendingAutoCheck
= (savedInstanceState
== null
&&
438 (mAction
!= ACTION_CREATE
|| !isUrlInputAllowed
));
444 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
446 private void initAuthorizationPreFragment(Bundle savedInstanceState
) {
448 /// step 0 - get UI elements in layout
449 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
450 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
451 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
452 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
453 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
454 mAuthStatusView
= (TextView
) findViewById(R
.id
.auth_status_text
);
456 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
457 String presetUserName
= null
;
458 boolean isPasswordExposed
= false
;
459 if (savedInstanceState
== null
) {
460 if (mAccount
!= null
) {
461 presetUserName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
465 isPasswordExposed
= savedInstanceState
.getBoolean(KEY_PASSWORD_EXPOSED
, false
);
466 mAuthStatusText
= savedInstanceState
.getInt(KEY_AUTH_STATUS_TEXT
);
467 mAuthStatusIcon
= savedInstanceState
.getInt(KEY_AUTH_STATUS_ICON
);
468 mAuthToken
= savedInstanceState
.getString(KEY_AUTH_TOKEN
);
471 /// step 2 - set properties of UI elements (text, visibility, enabled...)
472 mOAuth2Check
.setChecked(
473 AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
474 .equals(mAuthTokenType
));
475 if (presetUserName
!= null
) {
476 mUsernameInput
.setText(presetUserName
);
478 if (mAction
!= ACTION_CREATE
) {
479 mUsernameInput
.setEnabled(false
);
480 mUsernameInput
.setFocusable(false
);
482 mPasswordInput
.setText(""); // clean password to avoid social hacking
483 if (isPasswordExposed
) {
486 updateAuthenticationPreFragmentVisibility();
488 mOkButton
.setEnabled(mServerIsValid
);
491 /// step 3 - bind listeners
492 // bindings for password input field
493 mPasswordInput
.setOnFocusChangeListener(this);
494 mPasswordInput
.setImeOptions(EditorInfo
.IME_ACTION_DONE
);
495 mPasswordInput
.setOnEditorActionListener(this);
496 mPasswordInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
498 public boolean onDrawableTouch(final MotionEvent event
) {
499 if (event
.getAction() == MotionEvent
.ACTION_UP
) {
500 AuthenticatorActivity
.this.onViewPasswordClick();
510 * Changes the visibility of input elements depending on
511 * the current authorization method.
513 private void updateAuthenticationPreFragmentVisibility () {
514 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
515 equals(mAuthTokenType
)) {
516 // SAML-based web Single Sign On
517 mOAuth2Check
.setVisibility(View
.GONE
);
518 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
519 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
520 mUsernameInput
.setVisibility(View
.GONE
);
521 mPasswordInput
.setVisibility(View
.GONE
);
524 if (mAction
== ACTION_CREATE
&&
525 AUTH_OPTIONAL
.equals(getString(R
.string
.auth_method_oauth2
))) {
526 mOAuth2Check
.setVisibility(View
.VISIBLE
);
528 mOAuth2Check
.setVisibility(View
.GONE
);
531 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
532 equals(mAuthTokenType
)) {
533 // OAuth 2 authorization
535 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
536 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
537 mUsernameInput
.setVisibility(View
.GONE
);
538 mPasswordInput
.setVisibility(View
.GONE
);
541 // basic HTTP authorization
542 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
543 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
544 mUsernameInput
.setVisibility(View
.VISIBLE
);
545 mPasswordInput
.setVisibility(View
.VISIBLE
);
553 * Saves relevant state before {@link #onPause()}
555 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag,
556 * intended to defer the processing of the redirection caught in
557 * {@link #onNewIntent(Intent)} until {@link #onResume()}
559 * See {@link #onSaveInstanceState(Bundle)}
562 protected void onSaveInstanceState(Bundle outState
) {
563 //Log_OC.wtf(TAG, "onSaveInstanceState init" );
564 super.onSaveInstanceState(outState
);
567 outState
.putString(KEY_AUTH_TOKEN_TYPE
, mAuthTokenType
);
568 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mWaitingForOpId
);
570 /// Server PRE-fragment state
571 outState
.putInt(KEY_SERVER_STATUS_TEXT
, mServerStatusText
);
572 outState
.putInt(KEY_SERVER_STATUS_ICON
, mServerStatusIcon
);
573 outState
.putBoolean(KEY_SERVER_CHECKED
, mServerIsChecked
);
574 outState
.putBoolean(KEY_SERVER_VALID
, mServerIsValid
);
575 outState
.putBoolean(KEY_IS_SSL_CONN
, mServerInfo
.mIsSslConn
);
576 outState
.putString(KEY_HOST_URL_TEXT
, mServerInfo
.mBaseUrl
);
577 if (mServerInfo
.mVersion
!= null
) {
578 outState
.putString(KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion());
580 outState
.putString(KEY_SERVER_AUTH_METHOD
, mServerInfo
.mAuthMethod
.name());
582 /// Authentication PRE-fragment state
583 outState
.putBoolean(KEY_PASSWORD_EXPOSED
, isPasswordVisible());
584 outState
.putInt(KEY_AUTH_STATUS_ICON
, mAuthStatusIcon
);
585 outState
.putInt(KEY_AUTH_STATUS_TEXT
, mAuthStatusText
);
586 outState
.putString(KEY_AUTH_TOKEN
, mAuthToken
);
589 outState
.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
, mIsFirstAuthAttempt
);
591 /// AsyncTask (User and password)
592 outState
.putString(KEY_USERNAME
, mUsernameInput
.getText().toString());
593 outState
.putString(KEY_PASSWORD
, mPasswordInput
.getText().toString());
595 if (mAsyncTask
!= null
) {
596 mAsyncTask
.cancel(true
);
597 outState
.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS
, true
);
599 outState
.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS
, false
);
603 //Log_OC.wtf(TAG, "onSaveInstanceState end" );
607 public void onRestoreInstanceState(Bundle savedInstanceState
) {
608 super.onRestoreInstanceState(savedInstanceState
);
611 boolean inProgress
= savedInstanceState
.getBoolean(KEY_ASYNC_TASK_IN_PROGRESS
);
613 mAsyncTask
= new AuthenticatorAsyncTask(this);
614 String username
= savedInstanceState
.getString(KEY_USERNAME
);
615 String password
= savedInstanceState
.getString(KEY_PASSWORD
);
616 String
[] params
= {mServerInfo
.mBaseUrl
, username
, password
, mAuthToken
, mAuthTokenType
};
617 mAsyncTask
.execute(params
);
622 * The redirection triggered by the OAuth authentication server as response to the
623 * GET AUTHORIZATION request is caught here.
625 * To make this possible, this activity needs to be qualified with android:launchMode =
626 * "singleTask" in the AndroidManifest.xml file.
629 protected void onNewIntent (Intent intent
) {
630 Log_OC
.d(TAG
, "onNewIntent()");
631 Uri data
= intent
.getData();
632 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
633 mNewCapturedUriFromOAuth2Redirection
= data
;
639 * The redirection triggered by the OAuth authentication server as response to the
640 * GET AUTHORIZATION, and deferred in {@link #onNewIntent(Intent)}, is processed here.
643 protected void onResume() {
644 //Log_OC.wtf(TAG, "onResume init" );
647 // bound here to avoid spurious changes triggered by Android on device rotations
648 mHostUrlInput
.setOnFocusChangeListener(this);
649 mHostUrlInput
.addTextChangedListener(mHostUrlInputWatcher
);
651 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
652 getOAuth2AccessTokenFromCapturedRedirection();
655 if (mOperationsServiceBinder
!= null
) {
656 doOnResumeAndBound();
659 //Log_OC.wtf(TAG, "onResume end" );
664 protected void onPause() {
665 //Log_OC.wtf(TAG, "onPause init" );
666 if (mOperationsServiceBinder
!= null
) {
667 //Log_OC.wtf(TAG, "unregistering to listen for operation callbacks" );
668 mOperationsServiceBinder
.removeOperationListener(this);
671 mHostUrlInput
.removeTextChangedListener(mHostUrlInputWatcher
);
672 mHostUrlInput
.setOnFocusChangeListener(null
);
675 //Log_OC.wtf(TAG, "onPause end" );
679 protected void onDestroy() {
681 mHostUrlInputWatcher
= null
;
683 if (mOperationsServiceConnection
!= null
) {
684 unbindService(mOperationsServiceConnection
);
685 mOperationsServiceBinder
= null
;
692 * Parses the redirection with the response to the GET AUTHORIZATION request to the
693 * oAuth server and requests for the access token (GET ACCESS TOKEN)
695 private void getOAuth2AccessTokenFromCapturedRedirection() {
696 /// Parse data from OAuth redirection
697 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
698 mNewCapturedUriFromOAuth2Redirection
= null
;
700 /// Showing the dialog with instructions for the user.
701 IndeterminateProgressDialog dialog
=
702 IndeterminateProgressDialog
.newInstance(R
.string
.auth_getting_authorization
, true
);
703 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
705 /// GET ACCESS TOKEN to the oAuth server
706 Intent getServerInfoIntent
= new Intent();
707 getServerInfoIntent
.setAction(OperationsService
.ACTION_OAUTH2_GET_ACCESS_TOKEN
);
709 getServerInfoIntent
.putExtra(
710 OperationsService
.EXTRA_SERVER_URL
,
711 mOAuthTokenEndpointText
.getText().toString().trim());
713 getServerInfoIntent
.putExtra(
714 OperationsService
.EXTRA_OAUTH2_QUERY_PARAMETERS
,
717 if (mOperationsServiceBinder
!= null
) {
718 //Log_OC.wtf(TAG, "getting access token..." );
719 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
726 * Handles the change of focus on the text inputs for the server URL and the password
728 public void onFocusChange(View view
, boolean hasFocus
) {
729 if (view
.getId() == R
.id
.hostUrlInput
) {
731 onUrlInputFocusLost((TextView
) view
);
734 showRefreshButton(false
);
737 } else if (view
.getId() == R
.id
.account_password
) {
738 onPasswordFocusChanged((TextView
) view
, hasFocus
);
744 * Handles changes in focus on the text input for the server URL.
746 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
747 * other field. The operation to check the existence of the server in the entered URL is
750 * When hasFocus: user 'comes back' to write again the server URL.
752 * @param hostInput TextView with the URL input field receiving the change of focus.
754 private void onUrlInputFocusLost(TextView hostInput
) {
755 if (!mServerInfo
.mBaseUrl
.equals(
756 normalizeUrl(mHostUrlInput
.getText().toString(), mServerInfo
.mIsSslConn
))) {
757 // check server again only if the user changed something in the field
760 mOkButton
.setEnabled(mServerIsValid
);
761 showRefreshButton(!mServerIsValid
);
766 private void checkOcServer() {
767 String uri
= mHostUrlInput
.getText().toString().trim();
768 mServerIsValid
= false
;
769 mServerIsChecked
= false
;
770 mOkButton
.setEnabled(false
);
771 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
772 showRefreshButton(false
);
774 if (uri
.length() != 0) {
775 // Handle internationalized domain names
776 uri
= DisplayUtils
.convertIdn(uri
, true
);
777 mServerStatusText
= R
.string
.auth_testing_connection
;
778 mServerStatusIcon
= R
.drawable
.progress_small
;
781 Intent getServerInfoIntent
= new Intent();
782 getServerInfoIntent
.setAction(OperationsService
.ACTION_GET_SERVER_INFO
);
783 getServerInfoIntent
.putExtra(
784 OperationsService
.EXTRA_SERVER_URL
,
785 normalizeUrlSuffix(uri
)
787 if (mOperationsServiceBinder
!= null
) {
788 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
790 Log_OC
.wtf(TAG
, "Server check tried with OperationService unbound!" );
794 mServerStatusText
= 0;
795 mServerStatusIcon
= 0;
802 * Handles changes in focus on the text input for the password (basic authorization).
804 * When (hasFocus), the button to toggle password visibility is shown.
806 * When (!hasFocus), the button is made invisible and the password is hidden.
808 * @param passwordInput TextView with the password input field receiving the change of focus.
809 * @param hasFocus 'True' if focus is received, 'false' if is lost
811 private void onPasswordFocusChanged(TextView passwordInput
, boolean hasFocus
) {
813 showViewPasswordButton();
816 hidePasswordButton();
821 private void showViewPasswordButton() {
822 int drawable
= R
.drawable
.ic_view
;
823 if (isPasswordVisible()) {
824 drawable
= R
.drawable
.ic_hide
;
826 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable
, 0);
829 private boolean isPasswordVisible() {
830 return ((mPasswordInput
.getInputType() & InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) ==
831 InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
834 private void hidePasswordButton() {
835 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
838 private void showPassword() {
839 mPasswordInput
.setInputType(
840 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
842 showViewPasswordButton();
845 private void hidePassword() {
846 mPasswordInput
.setInputType(
847 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
849 showViewPasswordButton();
853 * Checks the credentials of the user in the root of the ownCloud server
854 * before creating a new local account.
856 * For basic authorization, a check of existence of the root folder is
859 * For OAuth, starts the flow to get an access token; the credentials test
860 * is postponed until it is available.
862 * IMPORTANT ENTRY POINT 4
864 * @param view OK button
866 public void onOkClick(View view
) {
867 // this check should be unnecessary
868 if (mServerInfo
.mVersion
== null
||
869 !mServerInfo
.mVersion
.isVersionValid() ||
870 mServerInfo
.mBaseUrl
== null
||
871 mServerInfo
.mBaseUrl
.length() == 0) {
872 mServerStatusIcon
= R
.drawable
.common_error
;
873 mServerStatusText
= R
.string
.auth_wtf_reenter_URL
;
875 mOkButton
.setEnabled(false
);
876 //Log_OC.wtf(TAG, "The user was allowed to click 'connect' to an unchecked server!!");
880 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
881 equals(mAuthTokenType
)) {
883 startOauthorization();
884 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
885 equals(mAuthTokenType
)) {
887 startSamlBasedFederatedSingleSignOnAuthorization();
889 checkBasicAuthorization();
895 * Tests the credentials entered by the user performing a check of existence on
896 * the root folder of the ownCloud server.
898 private void checkBasicAuthorization() {
899 /// get basic credentials entered by user
900 String username
= mUsernameInput
.getText().toString();
901 String password
= mPasswordInput
.getText().toString();
903 /// be gentle with the user
904 IndeterminateProgressDialog dialog
=
905 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
906 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
908 /// validate credentials accessing the root folder
909 accessRootFolderRemoteOperation(username
, password
);
913 private void accessRootFolderRemoteOperation(String username
, String password
) {
914 // delete the account if the token has changed
915 if (mAction
== ACTION_UPDATE_TOKEN
|| mAction
== ACTION_UPDATE_EXPIRED_TOKEN
) {
916 // Remove the cookies in AccountManager
917 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_COOKIES
, null
);
920 mAsyncTask
= new AuthenticatorAsyncTask(this);
921 String
[] params
= { mServerInfo
.mBaseUrl
, username
, password
, mAuthToken
, mAuthTokenType
};
922 mAsyncTask
.execute(params
);
927 * Starts the OAuth 'grant type' flow to get an access token, with
928 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
930 private void startOauthorization() {
931 // be gentle with the user
932 mAuthStatusIcon
= R
.drawable
.progress_small
;
933 mAuthStatusText
= R
.string
.oauth_login_connection
;
936 // GET AUTHORIZATION request
937 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
938 Uri
.Builder uriBuilder
= uri
.buildUpon();
939 uriBuilder
.appendQueryParameter(
940 OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
)
942 uriBuilder
.appendQueryParameter(
943 OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
)
945 uriBuilder
.appendQueryParameter(
946 OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
)
948 uriBuilder
.appendQueryParameter(
949 OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
)
951 uri
= uriBuilder
.build();
952 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
953 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
959 * Starts the Web Single Sign On flow to get access to the root folder
962 private void startSamlBasedFederatedSingleSignOnAuthorization() {
963 // be gentle with the user
964 mAuthStatusIcon
= R
.drawable
.progress_small
;
965 mAuthStatusText
= R
.string
.auth_connecting_auth_server
;
967 IndeterminateProgressDialog dialog
=
968 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
969 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
971 /// validate credentials accessing the root folder
972 accessRootFolderRemoteOperation("", "");
977 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
979 * Dispatches the operation flow to the right method.
982 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
984 if (operation
instanceof GetServerInfoOperation
) {
985 if (operation
.hashCode() == mWaitingForOpId
) {
986 onGetServerInfoFinish(result
);
987 } // else nothing ; only the last check operation is considered;
988 // multiple can be started if the user amends a URL quickly
990 } else if (operation
instanceof OAuth2GetAccessToken
) {
991 onGetOAuthAccessTokenFinish(result
);
993 } else if (operation
instanceof ExistenceCheckRemoteOperation
) {
994 // TODO : remove this response??
995 //Log_OC.wtf(TAG, "received detection response through callback" );
996 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
997 equals(mAuthTokenType
)) {
998 onSamlBasedFederatedSingleSignOnAuthorizationStart(result
);
1001 onAuthorizationCheckFinish(result
);
1003 } else if (operation
instanceof GetRemoteUserNameOperation
) {
1004 onGetUserNameFinish(result
);
1009 private void onGetUserNameFinish(RemoteOperationResult result
) {
1010 mWaitingForOpId
= Long
.MAX_VALUE
;
1011 if (result
.isSuccess()) {
1012 boolean success
= false
;
1013 String username
= (String
) result
.getData().get(0);
1015 if ( mAction
== ACTION_CREATE
) {
1016 mUsernameInput
.setText(username
);
1017 success
= createAccount();
1020 if (!mUsernameInput
.getText().toString().equals(username
)) {
1021 // fail - not a new account, but an existing one; disallow
1022 result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_THE_SAME
);
1024 OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(
1025 new OwnCloudAccount(
1026 Uri.parse(mServerInfo.mBaseUrl),
1027 OwnCloudCredentialsFactory.newSamlSsoCredentials(mAuthToken))
1031 updateAuthStatusIconAndText(result
);
1033 Log_OC
.d(TAG
, result
.getLogMessage());
1043 updateStatusIconFailUserName();
1045 Log_OC
.e(TAG
, "Access to user name failed: " + result
.getLogMessage());
1050 private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperationResult result
) {
1051 mWaitingForOpId
= Long
.MAX_VALUE
;
1052 dismissDialog(WAIT_DIALOG_TAG
);
1054 if (result
.isIdPRedirection()) {
1055 String targetUrl
= mServerInfo
.mBaseUrl
1056 + AccountUtils
.getWebdavPath(mServerInfo
.mVersion
, mAuthTokenType
);
1059 SamlWebViewDialog dialog
= SamlWebViewDialog
.newInstance(targetUrl
, targetUrl
);
1060 dialog
.show(getSupportFragmentManager(), SAML_DIALOG_TAG
);
1062 mAuthStatusIcon
= 0;
1063 mAuthStatusText
= 0;
1066 mAuthStatusIcon
= R
.drawable
.common_error
;
1067 mAuthStatusText
= R
.string
.auth_unsupported_auth_method
;
1075 * Processes the result of the server check performed when the user finishes the enter of the
1078 * @param result Result of the check.
1080 private void onGetServerInfoFinish(RemoteOperationResult result
) {
1081 /// update activity state
1082 mServerIsChecked
= true
;
1083 mWaitingForOpId
= Long
.MAX_VALUE
;
1085 // update server status, but don't show it yet
1086 updateServerStatusIconAndText(result
);
1088 if (result
.isSuccess()) {
1090 // 1. connection succeeded, and we know if it's SSL or not
1091 // 2. server is installed
1092 // 3. we got the server version
1093 // 4. we got the authentication method required by the server
1094 mServerInfo
= (GetServerInfoOperation
.ServerInfo
) (result
.getData().get(0));
1096 if (!authSupported(mServerInfo
.mAuthMethod
)) {
1098 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1099 mServerIsValid
= false
;
1102 mServerIsValid
= true
;
1106 mServerIsValid
= false
;
1110 showRefreshButton(!mServerIsValid
);
1112 mOkButton
.setEnabled(mServerIsValid
);
1114 /// very special case (TODO: move to a common place for all the remote operations)
1115 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1116 showUntrustedCertDialog(result
);
1121 private boolean authSupported(AuthenticationMethod authMethod
) {
1122 String basic
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1123 String oAuth
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1124 String saml
= AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
1126 return (( mAuthTokenType
.equals(basic
) &&
1127 authMethod
.equals(AuthenticationMethod
.BASIC_HTTP_AUTH
) ) ||
1128 ( mAuthTokenType
.equals(oAuth
) &&
1129 authMethod
.equals(AuthenticationMethod
.BEARER_TOKEN
)) ||
1130 ( mAuthTokenType
.equals(saml
) &&
1131 authMethod
.equals(AuthenticationMethod
.SAML_WEB_SSO
))
1136 // TODO remove, if possible
1137 private String
normalizeUrl(String url
, boolean sslWhenUnprefixed
) {
1138 if (url
!= null
&& url
.length() > 0) {
1140 if (!url
.toLowerCase().startsWith("http://") &&
1141 !url
.toLowerCase().startsWith("https://")) {
1142 if (sslWhenUnprefixed
) {
1143 url
= "https://" + url
;
1145 url
= "http://" + url
;
1149 url
= normalizeUrlSuffix(url
);
1151 return (url
!= null ? url
: "");
1155 private String
normalizeUrlSuffix(String url
) {
1156 if (url
.endsWith("/")) {
1157 url
= url
.substring(0, url
.length() - 1);
1159 url
= trimUrlWebdav(url
);
1164 // TODO remove, if possible
1165 private String
trimUrlWebdav(String url
){
1166 if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_4_0
)){
1167 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_4_0
.length());
1168 } else if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_2_0
)){
1169 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_2_0
.length());
1170 } else if (url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_1_2
)){
1171 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_1_2
.length());
1173 return (url
!= null ? url
: "");
1178 * Chooses the right icon and text to show to the user for the received operation result.
1180 * @param result Result of a remote operation performed in this activity
1182 private void updateServerStatusIconAndText(RemoteOperationResult result
) {
1183 mServerStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1185 switch (result
.getCode()) {
1187 mServerStatusIcon
= android
.R
.drawable
.ic_secure
;
1188 mServerStatusText
= R
.string
.auth_secure_connection
;
1193 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1194 mServerStatusText
= R
.string
.auth_connection_established
;
1195 mServerStatusIcon
= R
.drawable
.ic_ok
;
1197 mServerStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1198 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1202 case NO_NETWORK_CONNECTION
:
1203 mServerStatusIcon
= R
.drawable
.no_network
;
1204 mServerStatusText
= R
.string
.auth_no_net_conn_title
;
1207 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1208 mServerStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1210 case BAD_OC_VERSION
:
1211 mServerStatusText
= R
.string
.auth_bad_oc_version_title
;
1213 case WRONG_CONNECTION
:
1214 mServerStatusText
= R
.string
.auth_wrong_connection_title
;
1217 mServerStatusText
= R
.string
.auth_timeout_title
;
1219 case INCORRECT_ADDRESS
:
1220 mServerStatusText
= R
.string
.auth_incorrect_address_title
;
1223 mServerStatusText
= R
.string
.auth_ssl_general_error_title
;
1226 mServerStatusText
= R
.string
.auth_unauthorized
;
1228 case HOST_NOT_AVAILABLE
:
1229 mServerStatusText
= R
.string
.auth_unknown_host_title
;
1231 case INSTANCE_NOT_CONFIGURED
:
1232 mServerStatusText
= R
.string
.auth_not_configured_title
;
1234 case FILE_NOT_FOUND
:
1235 mServerStatusText
= R
.string
.auth_incorrect_path_title
;
1238 mServerStatusText
= R
.string
.auth_oauth_error
;
1240 case OAUTH2_ERROR_ACCESS_DENIED
:
1241 mServerStatusText
= R
.string
.auth_oauth_error_access_denied
;
1243 case UNHANDLED_HTTP_CODE
:
1245 mServerStatusText
= R
.string
.auth_unknown_error_title
;
1247 case OK_REDIRECT_TO_NON_SECURE_CONNECTION
:
1248 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1249 mServerStatusText
= R
.string
.auth_redirect_non_secure_connection_title
;
1252 mServerStatusText
= 0;
1253 mServerStatusIcon
= 0;
1259 * Chooses the right icon and text to show to the user for the received operation result.
1261 * @param result Result of a remote operation performed in this activity
1263 private void updateAuthStatusIconAndText(RemoteOperationResult result
) {
1264 mAuthStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1266 switch (result
.getCode()) {
1268 mAuthStatusIcon
= android
.R
.drawable
.ic_secure
;
1269 mAuthStatusText
= R
.string
.auth_secure_connection
;
1274 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1275 mAuthStatusText
= R
.string
.auth_connection_established
;
1276 mAuthStatusIcon
= R
.drawable
.ic_ok
;
1278 mAuthStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1279 mAuthStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1283 case NO_NETWORK_CONNECTION
:
1284 mAuthStatusIcon
= R
.drawable
.no_network
;
1285 mAuthStatusText
= R
.string
.auth_no_net_conn_title
;
1288 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1289 mAuthStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1291 case BAD_OC_VERSION
:
1292 mAuthStatusText
= R
.string
.auth_bad_oc_version_title
;
1294 case WRONG_CONNECTION
:
1295 mAuthStatusText
= R
.string
.auth_wrong_connection_title
;
1298 mAuthStatusText
= R
.string
.auth_timeout_title
;
1300 case INCORRECT_ADDRESS
:
1301 mAuthStatusText
= R
.string
.auth_incorrect_address_title
;
1304 mAuthStatusText
= R
.string
.auth_ssl_general_error_title
;
1307 mAuthStatusText
= R
.string
.auth_unauthorized
;
1309 case HOST_NOT_AVAILABLE
:
1310 mAuthStatusText
= R
.string
.auth_unknown_host_title
;
1312 case INSTANCE_NOT_CONFIGURED
:
1313 mAuthStatusText
= R
.string
.auth_not_configured_title
;
1315 case FILE_NOT_FOUND
:
1316 mAuthStatusText
= R
.string
.auth_incorrect_path_title
;
1319 mAuthStatusText
= R
.string
.auth_oauth_error
;
1321 case OAUTH2_ERROR_ACCESS_DENIED
:
1322 mAuthStatusText
= R
.string
.auth_oauth_error_access_denied
;
1324 case ACCOUNT_NOT_NEW
:
1325 mAuthStatusText
= R
.string
.auth_account_not_new
;
1327 case ACCOUNT_NOT_THE_SAME
:
1328 mAuthStatusText
= R
.string
.auth_account_not_the_same
;
1330 case UNHANDLED_HTTP_CODE
:
1332 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
1335 mAuthStatusText
= 0;
1336 mAuthStatusIcon
= 0;
1341 private void updateStatusIconFailUserName(){
1342 mAuthStatusIcon
= R
.drawable
.common_error
;
1343 mAuthStatusText
= R
.string
.auth_fail_get_user_name
;
1346 private void updateServerStatusIconNoRegularAuth(){
1347 mServerStatusIcon
= R
.drawable
.common_error
;
1348 mServerStatusText
= R
.string
.auth_can_not_auth_against_server
;
1352 * Processes the result of the request for and access token send
1353 * to an OAuth authorization server.
1355 * @param result Result of the operation.
1357 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result
) {
1358 mWaitingForOpId
= Long
.MAX_VALUE
;
1359 dismissDialog(WAIT_DIALOG_TAG
);
1361 if (result
.isSuccess()) {
1362 /// be gentle with the user
1363 IndeterminateProgressDialog dialog
=
1364 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
1365 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
1367 /// time to test the retrieved access token on the ownCloud server
1368 @SuppressWarnings("unchecked")
1369 Map
<String
, String
> tokens
= (Map
<String
, String
>)(result
.getData().get(0));
1370 mAuthToken
= tokens
.get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
1371 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mAuthToken
);
1373 accessRootFolderRemoteOperation("", "");
1376 updateAuthStatusIconAndText(result
);
1378 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1384 * Processes the result of the access check performed to try the user credentials.
1386 * Creates a new account through the AccountManager.
1388 * @param result Result of the operation.
1390 private void onAuthorizationCheckFinish(RemoteOperationResult result
) {
1391 mWaitingForOpId
= Long
.MAX_VALUE
;
1392 dismissDialog(WAIT_DIALOG_TAG
);
1394 if (result
.isSuccess()) {
1395 Log_OC
.d(TAG
, "Successful access - time to save the account");
1397 boolean success
= false
;
1398 if (mAction
== ACTION_CREATE
) {
1399 success
= createAccount();
1410 } else if (result
.isServerFail() || result
.isException()) {
1411 /// server errors or exceptions in authorization take to requiring a new check of
1413 mServerIsChecked
= true
;
1414 mServerIsValid
= false
;
1415 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
1417 // update status icon and text
1418 updateServerStatusIconAndText(result
);
1420 mAuthStatusIcon
= 0;
1421 mAuthStatusText
= 0;
1424 // update input controls state
1425 showRefreshButton(true
);
1426 mOkButton
.setEnabled(false
);
1428 // very special case (TODO: move to a common place for all the remote operations)
1429 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1430 showUntrustedCertDialog(result
);
1433 } else { // authorization fail due to client side - probably wrong credentials
1434 updateAuthStatusIconAndText(result
);
1436 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1444 * Sets the proper response to get that the Account Authenticator that started this activity
1445 * saves a new authorization token for mAccount.
1447 private void updateToken() {
1448 Bundle response
= new Bundle();
1449 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1450 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
1452 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
1453 equals(mAuthTokenType
)) {
1454 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1455 // the next line is necessary, notifications are calling directly to the
1456 // AuthenticatorActivity to update, without AccountManager intervention
1457 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1459 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1460 equals(mAuthTokenType
)) {
1462 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1463 // the next line is necessary; by now, notifications are calling directly to the
1464 // AuthenticatorActivity to update, without AccountManager intervention
1465 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1468 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
1469 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
1471 setAccountAuthenticatorResult(response
);
1477 * Creates a new account through the Account Authenticator that started this activity.
1479 * This makes the account permanent.
1481 * TODO Decide how to name the OAuth accounts
1483 private boolean createAccount() {
1484 /// create and save new ownCloud account
1485 boolean isOAuth
= AccountTypeUtils
.
1486 getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
);
1487 boolean isSaml
= AccountTypeUtils
.
1488 getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
);
1490 Uri uri
= Uri
.parse(mServerInfo
.mBaseUrl
);
1491 String username
= mUsernameInput
.getText().toString().trim();
1493 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1495 String accountName
= com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.
1496 buildAccountName(uri
, username
);
1497 Account newAccount
= new Account(accountName
, MainApp
.getAccountType());
1498 if (AccountUtils
.exists(newAccount
, getApplicationContext())) {
1499 // fail - not a new account, but an existing one; disallow
1500 RemoteOperationResult result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_NEW
);
1501 updateAuthStatusIconAndText(result
);
1503 Log_OC
.d(TAG
, result
.getLogMessage());
1507 mAccount
= newAccount
;
1509 if (isOAuth
|| isSaml
) {
1510 // with external authorizations, the password is never input in the app
1511 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
);
1513 mAccountMgr
.addAccountExplicitly(
1514 mAccount
, mPasswordInput
.getText().toString(), null
1518 /// add the new account as default in preferences, if there is none already
1519 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1520 if (defaultAccount
== null
) {
1521 SharedPreferences
.Editor editor
= PreferenceManager
1522 .getDefaultSharedPreferences(this).edit();
1523 editor
.putString("select_oc_account", accountName
);
1527 /// prepare result to return to the Authenticator
1528 // TODO check again what the Authenticator makes with it; probably has the same
1529 // effect as addAccountExplicitly, but it's not well done
1530 final Intent intent
= new Intent();
1531 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, MainApp
.getAccountType());
1532 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1534 intent.putExtra(AccountManager.KEY_AUTHTOKEN, MainApp.getAccountType()); */
1535 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1536 if (isOAuth
|| isSaml
) {
1537 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1539 /// add user data to the new account; TODO probably can be done in the last parameter
1540 // addAccountExplicitly, or in KEY_USERDATA
1541 mAccountMgr
.setUserData(
1542 mAccount
, Constants
.KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion()
1544 mAccountMgr
.setUserData(
1545 mAccount
, Constants
.KEY_OC_BASE_URL
, mServerInfo
.mBaseUrl
1549 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
, "TRUE");
1550 } else if (isOAuth
) {
1551 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
, "TRUE");
1554 setAccountAuthenticatorResult(intent
.getExtras());
1555 setResult(RESULT_OK
, intent
);
1563 * Starts and activity to open the 'new account' page in the ownCloud web site
1565 * @param view 'Account register' button
1567 public void onRegisterClick(View view
) {
1568 Intent register
= new Intent(
1569 Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.welcome_link_url
))
1571 setResult(RESULT_CANCELED
);
1572 startActivity(register
);
1577 * Updates the content and visibility state of the icon and text associated
1578 * to the last check on the ownCloud server.
1580 private void showServerStatus() {
1581 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1582 mServerStatusView
.setVisibility(View
.INVISIBLE
);
1585 mServerStatusView
.setText(mServerStatusText
);
1586 mServerStatusView
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1587 mServerStatusView
.setVisibility(View
.VISIBLE
);
1594 * Updates the content and visibility state of the icon and text associated
1595 * to the interactions with the OAuth authorization server.
1597 private void showAuthStatus() {
1598 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1599 mAuthStatusView
.setVisibility(View
.INVISIBLE
);
1602 mAuthStatusView
.setText(mAuthStatusText
);
1603 mAuthStatusView
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1604 mAuthStatusView
.setVisibility(View
.VISIBLE
);
1609 private void showRefreshButton (boolean show
) {
1611 mRefreshButton
.setVisibility(View
.VISIBLE
);
1613 mRefreshButton
.setVisibility(View
.GONE
);
1618 * Called when the refresh button in the input field for ownCloud host is clicked.
1620 * Performs a new check on the URL in the input field.
1622 * @param view Refresh 'button'
1624 public void onRefreshClick(View view
) {
1630 * Called when the eye icon in the password field is clicked.
1632 * Toggles the visibility of the password in the field.
1634 public void onViewPasswordClick() {
1635 int selectionStart
= mPasswordInput
.getSelectionStart();
1636 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1637 if (isPasswordVisible()) {
1642 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1647 * Called when the checkbox for OAuth authorization is clicked.
1649 * Hides or shows the input fields for user & password.
1651 * @param view 'View password' 'button'
1653 public void onCheckClick(View view
) {
1654 CheckBox oAuth2Check
= (CheckBox
)view
;
1655 if (oAuth2Check
.isChecked()) {
1656 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1658 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1660 updateAuthenticationPreFragmentVisibility();
1665 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1667 * Used to trigger the authentication check when the user presses 'enter' after writing the
1668 * password, or to throw the server test when the only field on screen is the URL input field.
1671 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1672 if (actionId
== EditorInfo
.IME_ACTION_DONE
&& inputField
!= null
&&
1673 inputField
.equals(mPasswordInput
)) {
1674 if (mOkButton
.isEnabled()) {
1675 mOkButton
.performClick();
1678 } else if (actionId
== EditorInfo
.IME_ACTION_NEXT
&& inputField
!= null
&&
1679 inputField
.equals(mHostUrlInput
)) {
1680 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1681 equals(mAuthTokenType
)) {
1685 return false
; // always return false to grant that the software keyboard is hidden anyway
1689 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1691 private int fuzz
= 75;
1697 public boolean onTouch(View view
, MotionEvent event
) {
1698 Drawable rightDrawable
= null
;
1699 if (view
instanceof TextView
) {
1700 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1701 if (drawables
.length
> 2) {
1702 rightDrawable
= drawables
[2];
1705 if (rightDrawable
!= null
) {
1706 final int x
= (int) event
.getX();
1707 final int y
= (int) event
.getY();
1708 final Rect bounds
= rightDrawable
.getBounds();
1709 if ( x
>= (view
.getRight() - bounds
.width() - fuzz
) &&
1710 x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
) &&
1711 y
>= (view
.getPaddingTop() - fuzz
) &&
1712 y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1714 return onDrawableTouch(event
);
1720 public abstract boolean onDrawableTouch(final MotionEvent event
);
1724 private void getRemoteUserNameOperation(String sessionCookie
, boolean followRedirects
) {
1726 Intent getUserNameIntent
= new Intent();
1727 getUserNameIntent
.setAction(OperationsService
.ACTION_GET_USER_NAME
);
1728 getUserNameIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
1729 getUserNameIntent
.putExtra(OperationsService
.EXTRA_COOKIE
, sessionCookie
);
1731 if (mOperationsServiceBinder
!= null
) {
1732 //Log_OC.wtf(TAG, "starting getRemoteUserNameOperation..." );
1733 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getUserNameIntent
);
1739 public void onSsoFinished(String sessionCookie
) {
1740 if (sessionCookie
!= null
&& sessionCookie
.length() > 0) {
1741 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1742 mAuthToken
= sessionCookie
;
1743 getRemoteUserNameOperation(sessionCookie
, true
);
1744 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1745 if (fd
!= null
&& fd
instanceof SherlockDialogFragment
) {
1746 Dialog d
= ((SherlockDialogFragment
)fd
).getDialog();
1747 if (d
!= null
&& d
.isShowing()) {
1754 Log_OC
.d(TAG
, "SSO failed");
1760 public boolean onTouchEvent(MotionEvent event
) {
1761 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1762 equals(mAuthTokenType
) &&
1763 mHostUrlInput
.hasFocus() && event
.getAction() == MotionEvent
.ACTION_DOWN
) {
1766 return super.onTouchEvent(event
);
1771 * Show untrusted cert dialog
1773 public void showUntrustedCertDialog(
1774 X509Certificate x509Certificate
, SslError error
, SslErrorHandler handler
1776 // Show a dialog with the certificate info
1777 SslUntrustedCertDialog dialog
= null
;
1778 if (x509Certificate
== null
) {
1779 dialog
= SslUntrustedCertDialog
.newInstanceForEmptySslError(error
, handler
);
1781 dialog
= SslUntrustedCertDialog
.
1782 newInstanceForFullSslError(x509Certificate
, error
, handler
);
1784 FragmentManager fm
= getSupportFragmentManager();
1785 FragmentTransaction ft
= fm
.beginTransaction();
1786 ft
.addToBackStack(null
);
1787 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1792 * Show untrusted cert dialog
1794 private void showUntrustedCertDialog(RemoteOperationResult result
) {
1795 // Show a dialog with the certificate info
1796 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.
1797 newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1798 FragmentManager fm
= getSupportFragmentManager();
1799 FragmentTransaction ft
= fm
.beginTransaction();
1800 ft
.addToBackStack(null
);
1801 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1806 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1808 public void onSavedCertificate() {
1809 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1811 // if SAML dialog is not shown,
1812 // the SslDialog was shown due to an SSL error in the server check
1818 * Called from SslValidatorDialog when a new server certificate could not be saved
1819 * when the user requested it.
1822 public void onFailedSavingCertificate() {
1823 dismissDialog(SAML_DIALOG_TAG
);
1824 Toast
.makeText(this, R
.string
.ssl_validator_not_saved
, Toast
.LENGTH_LONG
).show();
1828 public void onCancelCertificate() {
1829 dismissDialog(SAML_DIALOG_TAG
);
1833 private void doOnResumeAndBound() {
1834 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1835 mOperationsServiceBinder
.addOperationListener(AuthenticatorActivity
.this, mHandler
);
1836 if (mWaitingForOpId
<= Integer
.MAX_VALUE
) {
1837 mOperationsServiceBinder
.dispatchResultIfFinished((int)mWaitingForOpId
, this);
1840 if (mPendingAutoCheck
) {
1846 private void dismissDialog(String dialogTag
){
1847 Fragment frag
= getSupportFragmentManager().findFragmentByTag(dialogTag
);
1848 if (frag
!= null
&& frag
instanceof SherlockDialogFragment
) {
1849 SherlockDialogFragment dialog
= (SherlockDialogFragment
) frag
;
1856 * Implements callback methods for service binding.
1858 private class OperationsServiceConnection
implements ServiceConnection
{
1861 public void onServiceConnected(ComponentName component
, IBinder service
) {
1862 if (component
.equals(
1863 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1865 //Log_OC.wtf(TAG, "Operations service connected");
1866 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
1868 doOnResumeAndBound();
1877 public void onServiceDisconnected(ComponentName component
) {
1878 if (component
.equals(
1879 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1881 Log_OC
.e(TAG
, "Operations service crashed");
1882 mOperationsServiceBinder
= null
;
1889 * Create and show dialog for request authentication to the user
1893 public void createAuthenticationDialog(WebView webView
, HttpAuthHandler handler
) {
1895 // Show a dialog with the certificate info
1896 CredentialsDialogFragment dialog
=
1897 CredentialsDialogFragment
.newInstanceForCredentials(webView
, handler
);
1898 FragmentManager fm
= getSupportFragmentManager();
1899 FragmentTransaction ft
= fm
.beginTransaction();
1900 ft
.addToBackStack(null
);
1901 dialog
.setCancelable(false
);
1902 dialog
.show(ft
, CREDENTIALS_DIALOG_TAG
);
1904 if (!mIsFirstAuthAttempt
) {
1906 getApplicationContext(),
1907 getText(R
.string
.saml_authentication_wrong_pass
),
1911 mIsFirstAuthAttempt
= false
;
1916 * For retrieving the clicking on authentication cancel button
1918 public void doNegativeAuthenticatioDialogClick(){
1919 mIsFirstAuthAttempt
= true
;
1924 public void onAuthenticatorTaskCallback(RemoteOperationResult result
) {
1925 //Log_OC.wtf(TAG, "received detection response through callback" );
1926 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1927 equals(mAuthTokenType
)) {
1928 onSamlBasedFederatedSingleSignOnAuthorizationStart(result
);
1931 onAuthorizationCheckFinish(result
);