2 * ownCloud Android client application
4 * @author Bartek Przybylski
5 * @author David A. Velasco
7 * Copyright (C) 2012 Bartek Przybylski
8 * Copyright (C) 2015 ownCloud Inc.
10 * This program is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2,
12 * as published by the Free Software Foundation.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 package com
.owncloud
.android
.authentication
;
26 import java
.security
.cert
.X509Certificate
;
29 import android
.accounts
.Account
;
30 import android
.accounts
.AccountManager
;
31 import android
.app
.Dialog
;
32 import android
.content
.ComponentName
;
33 import android
.content
.Context
;
34 import android
.content
.Intent
;
35 import android
.content
.ServiceConnection
;
36 import android
.content
.SharedPreferences
;
37 import android
.graphics
.Rect
;
38 import android
.graphics
.drawable
.Drawable
;
39 import android
.net
.Uri
;
40 import android
.net
.http
.SslError
;
41 import android
.os
.Bundle
;
42 import android
.os
.Handler
;
43 import android
.os
.IBinder
;
44 import android
.preference
.PreferenceManager
;
45 import android
.support
.v4
.app
.Fragment
;
46 import android
.support
.v4
.app
.FragmentManager
;
47 import android
.support
.v4
.app
.FragmentTransaction
;
48 import android
.text
.Editable
;
49 import android
.text
.InputType
;
50 import android
.text
.TextWatcher
;
51 import android
.view
.KeyEvent
;
52 import android
.view
.MotionEvent
;
53 import android
.view
.View
;
54 import android
.view
.View
.OnFocusChangeListener
;
55 import android
.view
.View
.OnTouchListener
;
56 import android
.view
.Window
;
57 import android
.view
.inputmethod
.EditorInfo
;
58 import android
.webkit
.HttpAuthHandler
;
59 import android
.webkit
.SslErrorHandler
;
60 import android
.webkit
.WebView
;
61 import android
.widget
.Button
;
62 import android
.widget
.CheckBox
;
63 import android
.widget
.EditText
;
64 import android
.widget
.TextView
;
65 import android
.widget
.TextView
.OnEditorActionListener
;
66 import android
.widget
.Toast
;
68 import com
.actionbarsherlock
.app
.SherlockDialogFragment
;
69 import com
.owncloud
.android
.MainApp
;
70 import com
.owncloud
.android
.R
;
71 import com
.owncloud
.android
.authentication
.SsoWebViewClient
.SsoWebViewClientListener
;
72 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
73 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentialsFactory
;
74 import com
.owncloud
.android
.lib
.common
.accounts
.AccountTypeUtils
;
75 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
76 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.Constants
;
77 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
78 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
79 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
80 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
81 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
82 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
83 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
84 import com
.owncloud
.android
.lib
.resources
.users
.GetRemoteUserNameOperation
;
85 import com
.owncloud
.android
.operations
.DetectAuthenticationMethodOperation
.AuthenticationMethod
;
86 import com
.owncloud
.android
.operations
.GetServerInfoOperation
;
87 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
88 import com
.owncloud
.android
.services
.OperationsService
;
89 import com
.owncloud
.android
.services
.OperationsService
.OperationsServiceBinder
;
90 import com
.owncloud
.android
.ui
.dialog
.CredentialsDialogFragment
;
91 import com
.owncloud
.android
.ui
.dialog
.IndeterminateProgressDialog
;
92 import com
.owncloud
.android
.ui
.dialog
.SamlWebViewDialog
;
93 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
94 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
95 import com
.owncloud
.android
.utils
.DisplayUtils
;
98 * This Activity is used to add an ownCloud account to the App
100 public class AuthenticatorActivity
extends AccountAuthenticatorActivity
101 implements OnRemoteOperationListener
, OnFocusChangeListener
, OnEditorActionListener
,
102 SsoWebViewClientListener
, OnSslUntrustedCertListener
,
103 AuthenticatorAsyncTask
.OnAuthenticatorTaskListener
{
105 private static final String TAG
= AuthenticatorActivity
.class.getSimpleName();
107 public static final String EXTRA_ACTION
= "ACTION";
108 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
110 private static final String KEY_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
112 private static final String KEY_HOST_URL_TEXT
= "HOST_URL_TEXT";
113 private static final String KEY_OC_VERSION
= "OC_VERSION";
114 private static final String KEY_SERVER_VALID
= "SERVER_VALID";
115 private static final String KEY_SERVER_CHECKED
= "SERVER_CHECKED";
116 private static final String KEY_SERVER_STATUS_TEXT
= "SERVER_STATUS_TEXT";
117 private static final String KEY_SERVER_STATUS_ICON
= "SERVER_STATUS_ICON";
118 private static final String KEY_IS_SSL_CONN
= "IS_SSL_CONN";
119 private static final String KEY_PASSWORD_EXPOSED
= "PASSWORD_VISIBLE";
120 private static final String KEY_AUTH_STATUS_TEXT
= "AUTH_STATUS_TEXT";
121 private static final String KEY_AUTH_STATUS_ICON
= "AUTH_STATUS_ICON";
122 private static final String KEY_SERVER_AUTH_METHOD
= "SERVER_AUTH_METHOD";
123 private static final String KEY_WAITING_FOR_OP_ID
= "WAITING_FOR_OP_ID";
124 private static final String KEY_AUTH_TOKEN
= "AUTH_TOKEN";
126 private static final String AUTH_ON
= "on";
127 private static final String AUTH_OPTIONAL
= "optional";
129 public static final byte ACTION_CREATE
= 0;
130 public static final byte ACTION_UPDATE_TOKEN
= 1; // requested by the user
131 public static final byte ACTION_UPDATE_EXPIRED_TOKEN
= 2; // detected by the app
133 private static final String UNTRUSTED_CERT_DIALOG_TAG
= "UNTRUSTED_CERT_DIALOG";
134 private static final String SAML_DIALOG_TAG
= "SAML_DIALOG";
135 private static final String WAIT_DIALOG_TAG
= "WAIT_DIALOG";
136 private static final String CREDENTIALS_DIALOG_TAG
= "CREDENTIALS_DIALOG";
137 private static final String KEY_AUTH_IS_FIRST_ATTEMPT_TAG
= "KEY_AUTH_IS_FIRST_ATTEMPT";
139 private static final String KEY_USERNAME
= "USERNAME";
140 private static final String KEY_PASSWORD
= "PASSWORD";
141 private static final String KEY_ASYNC_TASK_IN_PROGRESS
= "AUTH_IN_PROGRESS";
143 /// parameters from EXTRAs in starter Intent
144 private byte mAction
;
145 private Account mAccount
;
146 private String mAuthTokenType
;
149 /// activity-level references / state
150 private final Handler mHandler
= new Handler();
151 private ServiceConnection mOperationsServiceConnection
= null
;
152 private OperationsServiceBinder mOperationsServiceBinder
= null
;
153 private AccountManager mAccountMgr
;
154 private Uri mNewCapturedUriFromOAuth2Redirection
;
157 /// Server PRE-Fragment elements
158 private EditText mHostUrlInput
;
159 private View mRefreshButton
;
160 private TextView mServerStatusView
;
162 private TextWatcher mHostUrlInputWatcher
;
163 private int mServerStatusText
= 0, mServerStatusIcon
= 0;
165 private boolean mServerIsChecked
= false
;
166 private boolean mServerIsValid
= false
;
167 private boolean mPendingAutoCheck
= false
;
169 private GetServerInfoOperation
.ServerInfo mServerInfo
=
170 new GetServerInfoOperation
.ServerInfo();
173 /// Authentication PRE-Fragment elements
174 private CheckBox mOAuth2Check
;
175 private TextView mOAuthAuthEndpointText
;
176 private TextView mOAuthTokenEndpointText
;
177 private EditText mUsernameInput
;
178 private EditText mPasswordInput
;
179 private View mOkButton
;
180 private TextView mAuthStatusView
;
182 private int mAuthStatusText
= 0, mAuthStatusIcon
= 0;
184 private String mAuthToken
= "";
185 private AuthenticatorAsyncTask mAsyncTask
;
187 private boolean mIsFirstAuthAttempt
;
189 /// Identifier of operation in progress which result shouldn't be lost
190 private long mWaitingForOpId
= Long
.MAX_VALUE
;
192 private final String BASIC_TOKEN_TYPE
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
193 private final String OAUTH_TOKEN_TYPE
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
194 private final String SAML_TOKEN_TYPE
=
195 AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
201 * IMPORTANT ENTRY POINT 1: activity is shown to the user
204 protected void onCreate(Bundle savedInstanceState
) {
205 //Log_OC.wtf(TAG, "onCreate init");
206 super.onCreate(savedInstanceState
);
207 getWindow().requestFeature(Window
.FEATURE_NO_TITLE
);
209 mIsFirstAuthAttempt
= true
;
211 // bind to Operations Service
212 mOperationsServiceConnection
= new OperationsServiceConnection();
213 if (!bindService(new Intent(this, OperationsService
.class),
214 mOperationsServiceConnection
,
215 Context
.BIND_AUTO_CREATE
)) {
217 R
.string
.error_cant_bind_to_operations_service
,
223 /// init activity state
224 mAccountMgr
= AccountManager
.get(this);
225 mNewCapturedUriFromOAuth2Redirection
= null
;
228 mAction
= getIntent().getByteExtra(EXTRA_ACTION
, ACTION_CREATE
);
229 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
230 if (savedInstanceState
== null
) {
233 mAuthTokenType
= savedInstanceState
.getString(KEY_AUTH_TOKEN_TYPE
);
234 mWaitingForOpId
= savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
);
235 mIsFirstAuthAttempt
= savedInstanceState
.getBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
);
238 /// load user interface
239 setContentView(R
.layout
.account_setup
);
241 /// initialize general UI elements
244 mOkButton
= findViewById(R
.id
.buttonOK
);
246 /// initialize block to be moved to single Fragment to check server and get info about it
247 initServerPreFragment(savedInstanceState
);
249 /// initialize block to be moved to single Fragment to retrieve and validate credentials
250 initAuthorizationPreFragment(savedInstanceState
);
252 //Log_OC.wtf(TAG, "onCreate end");
255 private void initAuthTokenType() {
257 getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
258 if (mAuthTokenType
== null
) {
259 if (mAccount
!= null
) {
260 boolean oAuthRequired
=
261 (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
) != null
);
262 boolean samlWebSsoRequired
= (
263 mAccountMgr
.getUserData(
264 mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
267 mAuthTokenType
= chooseAuthTokenType(oAuthRequired
, samlWebSsoRequired
);
270 boolean oAuthSupported
= AUTH_ON
.equals(getString(R
.string
.auth_method_oauth2
));
271 boolean samlWebSsoSupported
=
272 AUTH_ON
.equals(getString(R
.string
.auth_method_saml_web_sso
));
273 mAuthTokenType
= chooseAuthTokenType(oAuthSupported
, samlWebSsoSupported
);
278 private String
chooseAuthTokenType(boolean oauth
, boolean saml
) {
280 return SAML_TOKEN_TYPE
;
282 return OAUTH_TOKEN_TYPE
;
284 return BASIC_TOKEN_TYPE
;
290 * Configures elements in the user interface under direct control of the Activity.
292 private void initOverallUi() {
294 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
295 boolean isWelcomeLinkVisible
= getResources().getBoolean(R
.bool
.show_welcome_link
);
297 String instructionsMessageText
= null
;
298 if (mAction
== ACTION_UPDATE_EXPIRED_TOKEN
) {
299 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
300 .equals(mAuthTokenType
)) {
301 instructionsMessageText
= getString(R
.string
.auth_expired_oauth_token_toast
);
303 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType())
304 .equals(mAuthTokenType
)) {
305 instructionsMessageText
= getString(R
.string
.auth_expired_saml_sso_token_toast
);
308 instructionsMessageText
= getString(R
.string
.auth_expired_basic_auth_toast
);
312 /// step 2 - set properties of UI elements (text, visibility, enabled...)
313 Button welcomeLink
= (Button
) findViewById(R
.id
.welcome_link
);
314 welcomeLink
.setVisibility(isWelcomeLinkVisible ? View
.VISIBLE
: View
.GONE
);
316 String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
318 TextView instructionsView
= (TextView
) findViewById(R
.id
.instructions_message
);
319 if (instructionsMessageText
!= null
) {
320 instructionsView
.setVisibility(View
.VISIBLE
);
321 instructionsView
.setText(instructionsMessageText
);
323 instructionsView
.setVisibility(View
.GONE
);
330 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
332 private void initServerPreFragment(Bundle savedInstanceState
) {
334 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
335 boolean isUrlInputAllowed
= getResources().getBoolean(R
.bool
.show_server_url_input
);
336 if (savedInstanceState
== null
) {
337 if (mAccount
!= null
) {
338 mServerInfo
.mBaseUrl
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_BASE_URL
);
339 // TODO do next in a setter for mBaseUrl
340 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
341 String ocVersion
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_VERSION
);
342 if (ocVersion
!= null
) {
343 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
346 mServerInfo
.mBaseUrl
= getString(R
.string
.server_url
).trim();
347 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
350 mServerStatusText
= savedInstanceState
.getInt(KEY_SERVER_STATUS_TEXT
);
351 mServerStatusIcon
= savedInstanceState
.getInt(KEY_SERVER_STATUS_ICON
);
353 mServerIsValid
= savedInstanceState
.getBoolean(KEY_SERVER_VALID
);
354 mServerIsChecked
= savedInstanceState
.getBoolean(KEY_SERVER_CHECKED
);
357 mServerInfo
.mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
358 mServerInfo
.mBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
359 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
360 if (ocVersion
!= null
) {
361 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
363 mServerInfo
.mAuthMethod
= AuthenticationMethod
.valueOf(
364 savedInstanceState
.getString(KEY_SERVER_AUTH_METHOD
));
368 /// step 2 - set properties of UI elements (text, visibility, enabled...)
369 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
370 // Convert IDN to Unicode
371 mHostUrlInput
.setText(DisplayUtils
.convertIdn(mServerInfo
.mBaseUrl
, false
));
372 if (mAction
!= ACTION_CREATE
) {
373 /// lock things that should not change
374 mHostUrlInput
.setEnabled(false
);
375 mHostUrlInput
.setFocusable(false
);
377 if (isUrlInputAllowed
) {
378 mRefreshButton
= findViewById(R
.id
.embeddedRefreshButton
);
380 findViewById(R
.id
.hostUrlFrame
).setVisibility(View
.GONE
);
381 mRefreshButton
= findViewById(R
.id
.centeredRefreshButton
);
383 showRefreshButton(mServerIsChecked
&& !mServerIsValid
&&
384 mWaitingForOpId
> Integer
.MAX_VALUE
);
385 mServerStatusView
= (TextView
) findViewById(R
.id
.server_status_text
);
388 /// step 3 - bind some listeners and options
389 mHostUrlInput
.setImeOptions(EditorInfo
.IME_ACTION_NEXT
);
390 mHostUrlInput
.setOnEditorActionListener(this);
392 /// step 4 - create listeners that will be bound at onResume
393 mHostUrlInputWatcher
= new TextWatcher() {
396 public void afterTextChanged(Editable s
) {
397 if (mOkButton
.isEnabled() &&
398 !mServerInfo
.mBaseUrl
.equals(
399 normalizeUrl(s
.toString(), mServerInfo
.mIsSslConn
))) {
400 mOkButton
.setEnabled(false
);
405 public void beforeTextChanged(CharSequence s
, int start
, int count
, int after
) {
409 public void onTextChanged(CharSequence s
, int start
, int before
, int count
) {
410 if (mAuthStatusIcon
!= 0) {
411 Log_OC
.d(TAG
, "onTextChanged: hiding authentication status");
420 // TODO find out if this is really necessary, or if it can done in a different way
421 findViewById(R
.id
.scroll
).setOnTouchListener(new OnTouchListener() {
423 public boolean onTouch(View view
, MotionEvent event
) {
424 if (event
.getAction() == MotionEvent
.ACTION_DOWN
) {
426 AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(
427 MainApp
.getAccountType()
428 ).equals(mAuthTokenType
) &&
429 mHostUrlInput
.hasFocus()
439 /// step 4 - mark automatic check to be started when OperationsService is ready
440 mPendingAutoCheck
= (savedInstanceState
== null
&&
441 (mAction
!= ACTION_CREATE
|| !isUrlInputAllowed
));
447 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
449 private void initAuthorizationPreFragment(Bundle savedInstanceState
) {
451 /// step 0 - get UI elements in layout
452 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
453 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
454 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
455 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
456 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
457 mAuthStatusView
= (TextView
) findViewById(R
.id
.auth_status_text
);
459 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
460 String presetUserName
= null
;
461 boolean isPasswordExposed
= false
;
462 if (savedInstanceState
== null
) {
463 if (mAccount
!= null
) {
464 presetUserName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
468 isPasswordExposed
= savedInstanceState
.getBoolean(KEY_PASSWORD_EXPOSED
, false
);
469 mAuthStatusText
= savedInstanceState
.getInt(KEY_AUTH_STATUS_TEXT
);
470 mAuthStatusIcon
= savedInstanceState
.getInt(KEY_AUTH_STATUS_ICON
);
471 mAuthToken
= savedInstanceState
.getString(KEY_AUTH_TOKEN
);
474 /// step 2 - set properties of UI elements (text, visibility, enabled...)
475 mOAuth2Check
.setChecked(
476 AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
477 .equals(mAuthTokenType
));
478 if (presetUserName
!= null
) {
479 mUsernameInput
.setText(presetUserName
);
481 if (mAction
!= ACTION_CREATE
) {
482 mUsernameInput
.setEnabled(false
);
483 mUsernameInput
.setFocusable(false
);
485 mPasswordInput
.setText(""); // clean password to avoid social hacking
486 if (isPasswordExposed
) {
489 updateAuthenticationPreFragmentVisibility();
491 mOkButton
.setEnabled(mServerIsValid
);
494 /// step 3 - bind listeners
495 // bindings for password input field
496 mPasswordInput
.setOnFocusChangeListener(this);
497 mPasswordInput
.setImeOptions(EditorInfo
.IME_ACTION_DONE
);
498 mPasswordInput
.setOnEditorActionListener(this);
499 mPasswordInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
501 public boolean onDrawableTouch(final MotionEvent event
) {
502 if (event
.getAction() == MotionEvent
.ACTION_UP
) {
503 AuthenticatorActivity
.this.onViewPasswordClick();
513 * Changes the visibility of input elements depending on
514 * the current authorization method.
516 private void updateAuthenticationPreFragmentVisibility () {
517 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
518 equals(mAuthTokenType
)) {
519 // SAML-based web Single Sign On
520 mOAuth2Check
.setVisibility(View
.GONE
);
521 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
522 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
523 mUsernameInput
.setVisibility(View
.GONE
);
524 mPasswordInput
.setVisibility(View
.GONE
);
527 if (mAction
== ACTION_CREATE
&&
528 AUTH_OPTIONAL
.equals(getString(R
.string
.auth_method_oauth2
))) {
529 mOAuth2Check
.setVisibility(View
.VISIBLE
);
531 mOAuth2Check
.setVisibility(View
.GONE
);
534 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
535 equals(mAuthTokenType
)) {
536 // OAuth 2 authorization
538 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
539 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
540 mUsernameInput
.setVisibility(View
.GONE
);
541 mPasswordInput
.setVisibility(View
.GONE
);
544 // basic HTTP authorization
545 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
546 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
547 mUsernameInput
.setVisibility(View
.VISIBLE
);
548 mPasswordInput
.setVisibility(View
.VISIBLE
);
556 * Saves relevant state before {@link #onPause()}
558 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag,
559 * intended to defer the processing of the redirection caught in
560 * {@link #onNewIntent(Intent)} until {@link #onResume()}
562 * See {@link #onSaveInstanceState(Bundle)}
565 protected void onSaveInstanceState(Bundle outState
) {
566 //Log_OC.wtf(TAG, "onSaveInstanceState init" );
567 super.onSaveInstanceState(outState
);
570 outState
.putString(KEY_AUTH_TOKEN_TYPE
, mAuthTokenType
);
571 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mWaitingForOpId
);
573 /// Server PRE-fragment state
574 outState
.putInt(KEY_SERVER_STATUS_TEXT
, mServerStatusText
);
575 outState
.putInt(KEY_SERVER_STATUS_ICON
, mServerStatusIcon
);
576 outState
.putBoolean(KEY_SERVER_CHECKED
, mServerIsChecked
);
577 outState
.putBoolean(KEY_SERVER_VALID
, mServerIsValid
);
578 outState
.putBoolean(KEY_IS_SSL_CONN
, mServerInfo
.mIsSslConn
);
579 outState
.putString(KEY_HOST_URL_TEXT
, mServerInfo
.mBaseUrl
);
580 if (mServerInfo
.mVersion
!= null
) {
581 outState
.putString(KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion());
583 outState
.putString(KEY_SERVER_AUTH_METHOD
, mServerInfo
.mAuthMethod
.name());
585 /// Authentication PRE-fragment state
586 outState
.putBoolean(KEY_PASSWORD_EXPOSED
, isPasswordVisible());
587 outState
.putInt(KEY_AUTH_STATUS_ICON
, mAuthStatusIcon
);
588 outState
.putInt(KEY_AUTH_STATUS_TEXT
, mAuthStatusText
);
589 outState
.putString(KEY_AUTH_TOKEN
, mAuthToken
);
592 outState
.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
, mIsFirstAuthAttempt
);
594 /// AsyncTask (User and password)
595 outState
.putString(KEY_USERNAME
, mUsernameInput
.getText().toString());
596 outState
.putString(KEY_PASSWORD
, mPasswordInput
.getText().toString());
598 if (mAsyncTask
!= null
) {
599 mAsyncTask
.cancel(true
);
600 outState
.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS
, true
);
602 outState
.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS
, false
);
606 //Log_OC.wtf(TAG, "onSaveInstanceState end" );
610 public void onRestoreInstanceState(Bundle savedInstanceState
) {
611 super.onRestoreInstanceState(savedInstanceState
);
614 boolean inProgress
= savedInstanceState
.getBoolean(KEY_ASYNC_TASK_IN_PROGRESS
);
616 String username
= savedInstanceState
.getString(KEY_USERNAME
);
617 String password
= savedInstanceState
.getString(KEY_PASSWORD
);
619 OwnCloudCredentials credentials
= null
;
620 if (BASIC_TOKEN_TYPE
.equals(mAuthTokenType
)) {
621 credentials
= OwnCloudCredentialsFactory
.newBasicCredentials(username
, password
);
623 } else if (OAUTH_TOKEN_TYPE
.equals(mAuthTokenType
)) {
624 credentials
= OwnCloudCredentialsFactory
.newBearerCredentials(mAuthToken
);
627 accessRootFolder(credentials
);
632 * The redirection triggered by the OAuth authentication server as response to the
633 * GET AUTHORIZATION request is caught here.
635 * To make this possible, this activity needs to be qualified with android:launchMode =
636 * "singleTask" in the AndroidManifest.xml file.
639 protected void onNewIntent (Intent intent
) {
640 Log_OC
.d(TAG
, "onNewIntent()");
641 Uri data
= intent
.getData();
642 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
643 mNewCapturedUriFromOAuth2Redirection
= data
;
649 * The redirection triggered by the OAuth authentication server as response to the
650 * GET AUTHORIZATION, and deferred in {@link #onNewIntent(Intent)}, is processed here.
653 protected void onResume() {
656 // bound here to avoid spurious changes triggered by Android on device rotations
657 mHostUrlInput
.setOnFocusChangeListener(this);
658 mHostUrlInput
.addTextChangedListener(mHostUrlInputWatcher
);
660 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
661 getOAuth2AccessTokenFromCapturedRedirection();
664 if (mOperationsServiceBinder
!= null
) {
665 doOnResumeAndBound();
672 protected void onPause() {
673 if (mOperationsServiceBinder
!= null
) {
674 mOperationsServiceBinder
.removeOperationListener(this);
677 mHostUrlInput
.removeTextChangedListener(mHostUrlInputWatcher
);
678 mHostUrlInput
.setOnFocusChangeListener(null
);
684 protected void onDestroy() {
686 mHostUrlInputWatcher
= null
;
688 if (mOperationsServiceConnection
!= null
) {
689 unbindService(mOperationsServiceConnection
);
690 mOperationsServiceBinder
= null
;
697 * Parses the redirection with the response to the GET AUTHORIZATION request to the
698 * oAuth server and requests for the access token (GET ACCESS TOKEN)
700 private void getOAuth2AccessTokenFromCapturedRedirection() {
701 /// Parse data from OAuth redirection
702 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
703 mNewCapturedUriFromOAuth2Redirection
= null
;
705 /// Showing the dialog with instructions for the user.
706 IndeterminateProgressDialog dialog
=
707 IndeterminateProgressDialog
.newInstance(R
.string
.auth_getting_authorization
, true
);
708 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
710 /// GET ACCESS TOKEN to the oAuth server
711 Intent getServerInfoIntent
= new Intent();
712 getServerInfoIntent
.setAction(OperationsService
.ACTION_OAUTH2_GET_ACCESS_TOKEN
);
714 getServerInfoIntent
.putExtra(
715 OperationsService
.EXTRA_SERVER_URL
,
716 mOAuthTokenEndpointText
.getText().toString().trim());
718 getServerInfoIntent
.putExtra(
719 OperationsService
.EXTRA_OAUTH2_QUERY_PARAMETERS
,
722 if (mOperationsServiceBinder
!= null
) {
723 //Log_OC.wtf(TAG, "getting access token..." );
724 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
731 * Handles the change of focus on the text inputs for the server URL and the password
733 public void onFocusChange(View view
, boolean hasFocus
) {
734 if (view
.getId() == R
.id
.hostUrlInput
) {
736 onUrlInputFocusLost();
739 showRefreshButton(false
);
742 } else if (view
.getId() == R
.id
.account_password
) {
743 onPasswordFocusChanged(hasFocus
);
749 * Handles changes in focus on the text input for the server URL.
751 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
752 * other field. The operation to check the existence of the server in the entered URL is
755 * When hasFocus: user 'comes back' to write again the server URL.
757 private void onUrlInputFocusLost() {
758 if (!mServerInfo
.mBaseUrl
.equals(
759 normalizeUrl(mHostUrlInput
.getText().toString(), mServerInfo
.mIsSslConn
))) {
760 // check server again only if the user changed something in the field
763 mOkButton
.setEnabled(mServerIsValid
);
764 showRefreshButton(!mServerIsValid
);
769 private void checkOcServer() {
770 String uri
= mHostUrlInput
.getText().toString().trim();
771 mServerIsValid
= false
;
772 mServerIsChecked
= false
;
773 mOkButton
.setEnabled(false
);
774 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
775 showRefreshButton(false
);
777 if (uri
.length() != 0) {
778 // Handle internationalized domain names
779 if (!uri
.startsWith(".")) {
780 uri
= DisplayUtils
.convertIdn(uri
, true
);
782 mServerStatusText
= R
.string
.auth_testing_connection
;
783 mServerStatusIcon
= R
.drawable
.progress_small
;
786 Intent getServerInfoIntent
= new Intent();
787 getServerInfoIntent
.setAction(OperationsService
.ACTION_GET_SERVER_INFO
);
788 getServerInfoIntent
.putExtra(
789 OperationsService
.EXTRA_SERVER_URL
,
790 normalizeUrlSuffix(uri
)
792 if (mOperationsServiceBinder
!= null
) {
793 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
795 Log_OC
.wtf(TAG
, "Server check tried with OperationService unbound!" );
799 mServerStatusText
= 0;
800 mServerStatusIcon
= 0;
807 * Handles changes in focus on the text input for the password (basic authorization).
809 * When (hasFocus), the button to toggle password visibility is shown.
811 * When (!hasFocus), the button is made invisible and the password is hidden.
813 * @param hasFocus 'True' if focus is received, 'false' if is lost
815 private void onPasswordFocusChanged(boolean hasFocus
) {
817 showViewPasswordButton();
820 hidePasswordButton();
825 private void showViewPasswordButton() {
826 int drawable
= R
.drawable
.ic_view
;
827 if (isPasswordVisible()) {
828 drawable
= R
.drawable
.ic_hide
;
830 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable
, 0);
833 private boolean isPasswordVisible() {
834 return ((mPasswordInput
.getInputType() & InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) ==
835 InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
838 private void hidePasswordButton() {
839 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
842 private void showPassword() {
843 mPasswordInput
.setInputType(
844 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
846 showViewPasswordButton();
849 private void hidePassword() {
850 mPasswordInput
.setInputType(
851 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
853 showViewPasswordButton();
857 * Checks the credentials of the user in the root of the ownCloud server
858 * before creating a new local account.
860 * For basic authorization, a check of existence of the root folder is
863 * For OAuth, starts the flow to get an access token; the credentials test
864 * is postponed until it is available.
866 * IMPORTANT ENTRY POINT 4
868 * @param view OK button
870 public void onOkClick(View view
) {
871 // this check should be unnecessary
872 if (mServerInfo
.mVersion
== null
||
873 !mServerInfo
.mVersion
.isVersionValid() ||
874 mServerInfo
.mBaseUrl
== null
||
875 mServerInfo
.mBaseUrl
.length() == 0) {
876 mServerStatusIcon
= R
.drawable
.common_error
;
877 mServerStatusText
= R
.string
.auth_wtf_reenter_URL
;
879 mOkButton
.setEnabled(false
);
883 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
884 equals(mAuthTokenType
)) {
886 startOauthorization();
887 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
888 equals(mAuthTokenType
)) {
890 startSamlBasedFederatedSingleSignOnAuthorization();
892 checkBasicAuthorization();
898 * Tests the credentials entered by the user performing a check of existence on
899 * the root folder of the ownCloud server.
901 private void checkBasicAuthorization() {
902 /// get basic credentials entered by user
903 String username
= mUsernameInput
.getText().toString();
904 String password
= mPasswordInput
.getText().toString();
906 /// be gentle with the user
907 IndeterminateProgressDialog dialog
=
908 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
909 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
911 /// validate credentials accessing the root folder
912 OwnCloudCredentials credentials
= OwnCloudCredentialsFactory
.newBasicCredentials(username
, password
);
913 accessRootFolder(credentials
);
916 private void accessRootFolder(OwnCloudCredentials credentials
) {
917 mAsyncTask
= new AuthenticatorAsyncTask(this);
918 Object
[] params
= { mServerInfo
.mBaseUrl
, credentials
};
919 mAsyncTask
.execute(params
);
924 * Starts the OAuth 'grant type' flow to get an access token, with
925 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
927 private void startOauthorization() {
928 // be gentle with the user
929 mAuthStatusIcon
= R
.drawable
.progress_small
;
930 mAuthStatusText
= R
.string
.oauth_login_connection
;
933 // GET AUTHORIZATION request
934 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
935 Uri
.Builder uriBuilder
= uri
.buildUpon();
936 uriBuilder
.appendQueryParameter(
937 OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
)
939 uriBuilder
.appendQueryParameter(
940 OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
)
942 uriBuilder
.appendQueryParameter(
943 OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
)
945 uriBuilder
.appendQueryParameter(
946 OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
)
948 uri
= uriBuilder
.build();
949 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
950 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
956 * Starts the Web Single Sign On flow to get access to the root folder
959 private void startSamlBasedFederatedSingleSignOnAuthorization() {
960 /// be gentle with the user
961 mAuthStatusIcon
= R
.drawable
.progress_small
;
962 mAuthStatusText
= R
.string
.auth_connecting_auth_server
;
965 /// Show SAML-based SSO web dialog
966 String targetUrl
= mServerInfo
.mBaseUrl
967 + AccountUtils
.getWebdavPath(mServerInfo
.mVersion
, mAuthTokenType
);
968 SamlWebViewDialog dialog
= SamlWebViewDialog
.newInstance(targetUrl
, targetUrl
);
969 dialog
.show(getSupportFragmentManager(), SAML_DIALOG_TAG
);
973 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
975 * Dispatches the operation flow to the right method.
978 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
980 if (operation
instanceof GetServerInfoOperation
) {
981 if (operation
.hashCode() == mWaitingForOpId
) {
982 onGetServerInfoFinish(result
);
983 } // else nothing ; only the last check operation is considered;
984 // multiple can be started if the user amends a URL quickly
986 } else if (operation
instanceof OAuth2GetAccessToken
) {
987 onGetOAuthAccessTokenFinish(result
);
989 } else if (operation
instanceof GetRemoteUserNameOperation
) {
990 onGetUserNameFinish(result
);
995 private void onGetUserNameFinish(RemoteOperationResult result
) {
996 mWaitingForOpId
= Long
.MAX_VALUE
;
997 if (result
.isSuccess()) {
998 boolean success
= false
;
999 String username
= (String
) result
.getData().get(0);
1001 if ( mAction
== ACTION_CREATE
) {
1002 mUsernameInput
.setText(username
);
1003 success
= createAccount();
1006 if (!mUsernameInput
.getText().toString().equals(username
)) {
1007 // fail - not a new account, but an existing one; disallow
1008 result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_THE_SAME
);
1010 updateAuthStatusIconAndText(result
);
1012 Log_OC
.d(TAG
, result
.getLogMessage());
1015 updateAccountAuthentication();
1018 } catch (AccountNotFoundException e
) {
1019 Log_OC
.e(TAG
, "Account " + mAccount
+ " was removed!", e
);
1020 Toast
.makeText(this, R
.string
.auth_account_does_not_exist
, Toast
.LENGTH_SHORT
).show();
1029 updateStatusIconFailUserName();
1031 Log_OC
.e(TAG
, "Access to user name failed: " + result
.getLogMessage());
1037 * Processes the result of the server check performed when the user finishes the enter of the
1040 * @param result Result of the check.
1042 private void onGetServerInfoFinish(RemoteOperationResult result
) {
1043 /// update activity state
1044 mServerIsChecked
= true
;
1045 mWaitingForOpId
= Long
.MAX_VALUE
;
1047 // update server status, but don't show it yet
1048 updateServerStatusIconAndText(result
);
1050 if (result
.isSuccess()) {
1052 // 1. connection succeeded, and we know if it's SSL or not
1053 // 2. server is installed
1054 // 3. we got the server version
1055 // 4. we got the authentication method required by the server
1056 mServerInfo
= (GetServerInfoOperation
.ServerInfo
) (result
.getData().get(0));
1058 if (!authSupported(mServerInfo
.mAuthMethod
)) {
1060 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1061 mServerIsValid
= false
;
1064 mServerIsValid
= true
;
1068 mServerIsValid
= false
;
1072 showRefreshButton(!mServerIsValid
);
1074 mOkButton
.setEnabled(mServerIsValid
);
1076 /// very special case (TODO: move to a common place for all the remote operations)
1077 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1078 showUntrustedCertDialog(result
);
1083 private boolean authSupported(AuthenticationMethod authMethod
) {
1084 return (( BASIC_TOKEN_TYPE
.equals(mAuthTokenType
) &&
1085 AuthenticationMethod
.BASIC_HTTP_AUTH
.equals(authMethod
) ) ||
1086 ( OAUTH_TOKEN_TYPE
.equals(mAuthTokenType
) &&
1087 AuthenticationMethod
.BEARER_TOKEN
.equals(authMethod
)) ||
1088 ( SAML_TOKEN_TYPE
.equals(mAuthTokenType
) &&
1089 AuthenticationMethod
.SAML_WEB_SSO
.equals(authMethod
))
1094 // TODO remove, if possible
1095 private String
normalizeUrl(String url
, boolean sslWhenUnprefixed
) {
1096 if (url
!= null
&& url
.length() > 0) {
1098 if (!url
.toLowerCase().startsWith("http://") &&
1099 !url
.toLowerCase().startsWith("https://")) {
1100 if (sslWhenUnprefixed
) {
1101 url
= "https://" + url
;
1103 url
= "http://" + url
;
1107 url
= normalizeUrlSuffix(url
);
1109 return (url
!= null ? url
: "");
1113 private String
normalizeUrlSuffix(String url
) {
1114 if (url
.endsWith("/")) {
1115 url
= url
.substring(0, url
.length() - 1);
1117 url
= trimUrlWebdav(url
);
1122 // TODO remove, if possible
1123 private String
trimUrlWebdav(String url
){
1124 if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_4_0
)){
1125 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_4_0
.length());
1126 } else if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_2_0
)){
1127 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_2_0
.length());
1128 } else if (url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_1_2
)){
1129 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_1_2
.length());
1131 return (url
!= null ? url
: "");
1136 * Chooses the right icon and text to show to the user for the received operation result.
1138 * @param result Result of a remote operation performed in this activity
1140 private void updateServerStatusIconAndText(RemoteOperationResult result
) {
1141 mServerStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1143 switch (result
.getCode()) {
1145 mServerStatusIcon
= android
.R
.drawable
.ic_secure
;
1146 mServerStatusText
= R
.string
.auth_secure_connection
;
1151 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1152 mServerStatusText
= R
.string
.auth_connection_established
;
1153 mServerStatusIcon
= R
.drawable
.ic_ok
;
1155 mServerStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1156 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1160 case NO_NETWORK_CONNECTION
:
1161 mServerStatusIcon
= R
.drawable
.no_network
;
1162 mServerStatusText
= R
.string
.auth_no_net_conn_title
;
1165 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1166 mServerStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1168 case BAD_OC_VERSION
:
1169 mServerStatusText
= R
.string
.auth_bad_oc_version_title
;
1171 case WRONG_CONNECTION
:
1172 mServerStatusText
= R
.string
.auth_wrong_connection_title
;
1175 mServerStatusText
= R
.string
.auth_timeout_title
;
1177 case INCORRECT_ADDRESS
:
1178 mServerStatusText
= R
.string
.auth_incorrect_address_title
;
1181 mServerStatusText
= R
.string
.auth_ssl_general_error_title
;
1184 mServerStatusText
= R
.string
.auth_unauthorized
;
1186 case HOST_NOT_AVAILABLE
:
1187 mServerStatusText
= R
.string
.auth_unknown_host_title
;
1189 case INSTANCE_NOT_CONFIGURED
:
1190 mServerStatusText
= R
.string
.auth_not_configured_title
;
1192 case FILE_NOT_FOUND
:
1193 mServerStatusText
= R
.string
.auth_incorrect_path_title
;
1196 mServerStatusText
= R
.string
.auth_oauth_error
;
1198 case OAUTH2_ERROR_ACCESS_DENIED
:
1199 mServerStatusText
= R
.string
.auth_oauth_error_access_denied
;
1201 case UNHANDLED_HTTP_CODE
:
1203 mServerStatusText
= R
.string
.auth_unknown_error_title
;
1205 case OK_REDIRECT_TO_NON_SECURE_CONNECTION
:
1206 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1207 mServerStatusText
= R
.string
.auth_redirect_non_secure_connection_title
;
1210 mServerStatusText
= 0;
1211 mServerStatusIcon
= 0;
1217 * Chooses the right icon and text to show to the user for the received operation result.
1219 * @param result Result of a remote operation performed in this activity
1221 private void updateAuthStatusIconAndText(RemoteOperationResult result
) {
1222 mAuthStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1224 switch (result
.getCode()) {
1226 mAuthStatusIcon
= android
.R
.drawable
.ic_secure
;
1227 mAuthStatusText
= R
.string
.auth_secure_connection
;
1232 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1233 mAuthStatusText
= R
.string
.auth_connection_established
;
1234 mAuthStatusIcon
= R
.drawable
.ic_ok
;
1236 mAuthStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1237 mAuthStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1241 case NO_NETWORK_CONNECTION
:
1242 mAuthStatusIcon
= R
.drawable
.no_network
;
1243 mAuthStatusText
= R
.string
.auth_no_net_conn_title
;
1246 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1247 mAuthStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1249 case BAD_OC_VERSION
:
1250 mAuthStatusText
= R
.string
.auth_bad_oc_version_title
;
1252 case WRONG_CONNECTION
:
1253 mAuthStatusText
= R
.string
.auth_wrong_connection_title
;
1256 mAuthStatusText
= R
.string
.auth_timeout_title
;
1258 case INCORRECT_ADDRESS
:
1259 mAuthStatusText
= R
.string
.auth_incorrect_address_title
;
1262 mAuthStatusText
= R
.string
.auth_ssl_general_error_title
;
1265 mAuthStatusText
= R
.string
.auth_unauthorized
;
1267 case HOST_NOT_AVAILABLE
:
1268 mAuthStatusText
= R
.string
.auth_unknown_host_title
;
1270 case INSTANCE_NOT_CONFIGURED
:
1271 mAuthStatusText
= R
.string
.auth_not_configured_title
;
1273 case FILE_NOT_FOUND
:
1274 mAuthStatusText
= R
.string
.auth_incorrect_path_title
;
1277 mAuthStatusText
= R
.string
.auth_oauth_error
;
1279 case OAUTH2_ERROR_ACCESS_DENIED
:
1280 mAuthStatusText
= R
.string
.auth_oauth_error_access_denied
;
1282 case ACCOUNT_NOT_NEW
:
1283 mAuthStatusText
= R
.string
.auth_account_not_new
;
1285 case ACCOUNT_NOT_THE_SAME
:
1286 mAuthStatusText
= R
.string
.auth_account_not_the_same
;
1288 case UNHANDLED_HTTP_CODE
:
1290 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
1293 mAuthStatusText
= 0;
1294 mAuthStatusIcon
= 0;
1299 private void updateStatusIconFailUserName(){
1300 mAuthStatusIcon
= R
.drawable
.common_error
;
1301 mAuthStatusText
= R
.string
.auth_fail_get_user_name
;
1304 private void updateServerStatusIconNoRegularAuth(){
1305 mServerStatusIcon
= R
.drawable
.common_error
;
1306 mServerStatusText
= R
.string
.auth_can_not_auth_against_server
;
1310 * Processes the result of the request for and access token send
1311 * to an OAuth authorization server.
1313 * @param result Result of the operation.
1315 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result
) {
1316 mWaitingForOpId
= Long
.MAX_VALUE
;
1317 dismissDialog(WAIT_DIALOG_TAG
);
1319 if (result
.isSuccess()) {
1320 /// be gentle with the user
1321 IndeterminateProgressDialog dialog
=
1322 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
1323 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
1325 /// time to test the retrieved access token on the ownCloud server
1326 @SuppressWarnings("unchecked")
1327 Map
<String
, String
> tokens
= (Map
<String
, String
>)(result
.getData().get(0));
1328 mAuthToken
= tokens
.get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
1329 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mAuthToken
);
1331 /// validate token accessing to root folder / getting session
1332 OwnCloudCredentials credentials
= OwnCloudCredentialsFactory
.newBearerCredentials(mAuthToken
);
1333 accessRootFolder(credentials
);
1336 updateAuthStatusIconAndText(result
);
1338 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1344 * Processes the result of the access check performed to try the user credentials.
1346 * Creates a new account through the AccountManager.
1348 * @param result Result of the operation.
1351 public void onAuthenticatorTaskCallback(RemoteOperationResult result
) {
1352 mWaitingForOpId
= Long
.MAX_VALUE
;
1353 dismissDialog(WAIT_DIALOG_TAG
);
1355 if (result
.isSuccess()) {
1356 Log_OC
.d(TAG
, "Successful access - time to save the account");
1358 boolean success
= false
;
1359 if (mAction
== ACTION_CREATE
) {
1360 success
= createAccount();
1364 updateAccountAuthentication();
1367 } catch (AccountNotFoundException e
) {
1368 Log_OC
.e(TAG
, "Account " + mAccount
+ " was removed!", e
);
1369 Toast
.makeText(this, R
.string
.auth_account_does_not_exist
, Toast
.LENGTH_SHORT
).show();
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() throws AccountNotFoundException
{
1422 Bundle response
= new Bundle();
1423 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1424 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
1426 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
1427 equals(mAuthTokenType
)) {
1428 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1429 // the next line is necessary, notifications are calling directly to the
1430 // AuthenticatorActivity to update, without AccountManager intervention
1431 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1433 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1434 equals(mAuthTokenType
)) {
1436 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1437 // the next line is necessary; by now, notifications are calling directly to the
1438 // AuthenticatorActivity to update, without AccountManager intervention
1439 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1442 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
1443 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
1445 setAccountAuthenticatorResult(response
);
1451 * Creates a new account through the Account Authenticator that started this activity.
1453 * This makes the account permanent.
1455 * TODO Decide how to name the OAuth accounts
1457 private boolean createAccount() {
1458 /// create and save new ownCloud account
1459 boolean isOAuth
= AccountTypeUtils
.
1460 getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
);
1461 boolean isSaml
= AccountTypeUtils
.
1462 getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
);
1464 Uri uri
= Uri
.parse(mServerInfo
.mBaseUrl
);
1465 String username
= mUsernameInput
.getText().toString().trim();
1467 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1469 String accountName
= com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.
1470 buildAccountName(uri
, username
);
1471 Account newAccount
= new Account(accountName
, MainApp
.getAccountType());
1472 if (AccountUtils
.exists(newAccount
, getApplicationContext())) {
1473 // fail - not a new account, but an existing one; disallow
1474 RemoteOperationResult result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_NEW
);
1475 updateAuthStatusIconAndText(result
);
1477 Log_OC
.d(TAG
, result
.getLogMessage());
1481 mAccount
= newAccount
;
1483 if (isOAuth
|| isSaml
) {
1484 // with external authorizations, the password is never input in the app
1485 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
);
1487 mAccountMgr
.addAccountExplicitly(
1488 mAccount
, mPasswordInput
.getText().toString(), null
1492 /// add the new account as default in preferences, if there is none already
1493 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1494 if (defaultAccount
== null
) {
1495 SharedPreferences
.Editor editor
= PreferenceManager
1496 .getDefaultSharedPreferences(this).edit();
1497 editor
.putString("select_oc_account", accountName
);
1501 /// prepare result to return to the Authenticator
1502 // TODO check again what the Authenticator makes with it; probably has the same
1503 // effect as addAccountExplicitly, but it's not well done
1504 final Intent intent
= new Intent();
1505 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, MainApp
.getAccountType());
1506 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1507 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1508 if (isOAuth
|| isSaml
) {
1509 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1511 /// add user data to the new account; TODO probably can be done in the last parameter
1512 // addAccountExplicitly, or in KEY_USERDATA
1513 mAccountMgr
.setUserData(
1514 mAccount
, Constants
.KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion()
1516 mAccountMgr
.setUserData(
1517 mAccount
, Constants
.KEY_OC_BASE_URL
, mServerInfo
.mBaseUrl
1521 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
, "TRUE");
1522 } else if (isOAuth
) {
1523 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
, "TRUE");
1526 setAccountAuthenticatorResult(intent
.getExtras());
1527 setResult(RESULT_OK
, intent
);
1535 * Starts and activity to open the 'new account' page in the ownCloud web site
1537 * @param view 'Account register' button
1539 public void onRegisterClick(View view
) {
1540 Intent register
= new Intent(
1541 Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.welcome_link_url
))
1543 setResult(RESULT_CANCELED
);
1544 startActivity(register
);
1549 * Updates the content and visibility state of the icon and text associated
1550 * to the last check on the ownCloud server.
1553 private void showServerStatus() {
1554 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1555 mServerStatusView
.setVisibility(View
.INVISIBLE
);
1558 mServerStatusView
.setText(mServerStatusText
);
1559 mServerStatusView
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1560 mServerStatusView
.setVisibility(View
.VISIBLE
);
1567 * Updates the content and visibility state of the icon and text associated
1568 * to the interactions with the OAuth authorization server.
1570 private void showAuthStatus() {
1571 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1572 mAuthStatusView
.setVisibility(View
.INVISIBLE
);
1575 mAuthStatusView
.setText(mAuthStatusText
);
1576 mAuthStatusView
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1577 mAuthStatusView
.setVisibility(View
.VISIBLE
);
1582 private void showRefreshButton (boolean show
) {
1584 mRefreshButton
.setVisibility(View
.VISIBLE
);
1586 mRefreshButton
.setVisibility(View
.GONE
);
1591 * Called when the refresh button in the input field for ownCloud host is clicked.
1593 * Performs a new check on the URL in the input field.
1595 * @param view Refresh 'button'
1597 public void onRefreshClick(View view
) {
1603 * Called when the eye icon in the password field is clicked.
1605 * Toggles the visibility of the password in the field.
1607 public void onViewPasswordClick() {
1608 int selectionStart
= mPasswordInput
.getSelectionStart();
1609 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1610 if (isPasswordVisible()) {
1615 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1620 * Called when the checkbox for OAuth authorization is clicked.
1622 * Hides or shows the input fields for user & password.
1624 * @param view 'View password' 'button'
1626 public void onCheckClick(View view
) {
1627 CheckBox oAuth2Check
= (CheckBox
)view
;
1628 if (oAuth2Check
.isChecked()) {
1629 mAuthTokenType
= OAUTH_TOKEN_TYPE
;
1631 mAuthTokenType
= BASIC_TOKEN_TYPE
;
1633 updateAuthenticationPreFragmentVisibility();
1638 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1640 * Used to trigger the authentication check when the user presses 'enter' after writing the
1641 * password, or to throw the server test when the only field on screen is the URL input field.
1644 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1645 if (actionId
== EditorInfo
.IME_ACTION_DONE
&& inputField
!= null
&&
1646 inputField
.equals(mPasswordInput
)) {
1647 if (mOkButton
.isEnabled()) {
1648 mOkButton
.performClick();
1651 } else if (actionId
== EditorInfo
.IME_ACTION_NEXT
&& inputField
!= null
&&
1652 inputField
.equals(mHostUrlInput
)) {
1653 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1654 equals(mAuthTokenType
)) {
1658 return false
; // always return false to grant that the software keyboard is hidden anyway
1662 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1664 private int fuzz
= 75;
1670 public boolean onTouch(View view
, MotionEvent event
) {
1671 Drawable rightDrawable
= null
;
1672 if (view
instanceof TextView
) {
1673 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1674 if (drawables
.length
> 2) {
1675 rightDrawable
= drawables
[2];
1678 if (rightDrawable
!= null
) {
1679 final int x
= (int) event
.getX();
1680 final int y
= (int) event
.getY();
1681 final Rect bounds
= rightDrawable
.getBounds();
1682 if ( x
>= (view
.getRight() - bounds
.width() - fuzz
) &&
1683 x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
) &&
1684 y
>= (view
.getPaddingTop() - fuzz
) &&
1685 y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1687 return onDrawableTouch(event
);
1693 public abstract boolean onDrawableTouch(final MotionEvent event
);
1697 private void getRemoteUserNameOperation(String sessionCookie
, boolean followRedirects
) {
1699 Intent getUserNameIntent
= new Intent();
1700 getUserNameIntent
.setAction(OperationsService
.ACTION_GET_USER_NAME
);
1701 getUserNameIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
1702 getUserNameIntent
.putExtra(OperationsService
.EXTRA_COOKIE
, sessionCookie
);
1704 if (mOperationsServiceBinder
!= null
) {
1705 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getUserNameIntent
);
1711 public void onSsoFinished(String sessionCookie
) {
1712 if (sessionCookie
!= null
&& sessionCookie
.length() > 0) {
1713 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1714 mAuthToken
= sessionCookie
;
1715 getRemoteUserNameOperation(sessionCookie
, true
);
1716 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1717 if (fd
!= null
&& fd
instanceof SherlockDialogFragment
) {
1718 Dialog d
= ((SherlockDialogFragment
)fd
).getDialog();
1719 if (d
!= null
&& d
.isShowing()) {
1726 Log_OC
.d(TAG
, "SSO failed");
1732 public boolean onTouchEvent(MotionEvent event
) {
1733 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1734 equals(mAuthTokenType
) &&
1735 mHostUrlInput
.hasFocus() && event
.getAction() == MotionEvent
.ACTION_DOWN
) {
1738 return super.onTouchEvent(event
);
1743 * Show untrusted cert dialog
1745 public void showUntrustedCertDialog(
1746 X509Certificate x509Certificate
, SslError error
, SslErrorHandler handler
1748 // Show a dialog with the certificate info
1749 SslUntrustedCertDialog dialog
= null
;
1750 if (x509Certificate
== null
) {
1751 dialog
= SslUntrustedCertDialog
.newInstanceForEmptySslError(error
, handler
);
1753 dialog
= SslUntrustedCertDialog
.
1754 newInstanceForFullSslError(x509Certificate
, error
, handler
);
1756 FragmentManager fm
= getSupportFragmentManager();
1757 FragmentTransaction ft
= fm
.beginTransaction();
1758 ft
.addToBackStack(null
);
1759 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1764 * Show untrusted cert dialog
1766 private void showUntrustedCertDialog(RemoteOperationResult result
) {
1767 // Show a dialog with the certificate info
1768 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.
1769 newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1770 FragmentManager fm
= getSupportFragmentManager();
1771 FragmentTransaction ft
= fm
.beginTransaction();
1772 ft
.addToBackStack(null
);
1773 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1778 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1780 public void onSavedCertificate() {
1781 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1783 // if SAML dialog is not shown,
1784 // the SslDialog was shown due to an SSL error in the server check
1790 * Called from SslValidatorDialog when a new server certificate could not be saved
1791 * when the user requested it.
1794 public void onFailedSavingCertificate() {
1795 dismissDialog(SAML_DIALOG_TAG
);
1796 Toast
.makeText(this, R
.string
.ssl_validator_not_saved
, Toast
.LENGTH_LONG
).show();
1800 public void onCancelCertificate() {
1801 dismissDialog(SAML_DIALOG_TAG
);
1805 private void doOnResumeAndBound() {
1806 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1807 mOperationsServiceBinder
.addOperationListener(AuthenticatorActivity
.this, mHandler
);
1808 if (mWaitingForOpId
<= Integer
.MAX_VALUE
) {
1809 mOperationsServiceBinder
.dispatchResultIfFinished((int)mWaitingForOpId
, this);
1812 if (mPendingAutoCheck
) {
1818 private void dismissDialog(String dialogTag
){
1819 Fragment frag
= getSupportFragmentManager().findFragmentByTag(dialogTag
);
1820 if (frag
!= null
&& frag
instanceof SherlockDialogFragment
) {
1821 SherlockDialogFragment dialog
= (SherlockDialogFragment
) frag
;
1828 * Implements callback methods for service binding.
1830 private class OperationsServiceConnection
implements ServiceConnection
{
1833 public void onServiceConnected(ComponentName component
, IBinder service
) {
1834 if (component
.equals(
1835 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1837 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
1839 doOnResumeAndBound();
1848 public void onServiceDisconnected(ComponentName component
) {
1849 if (component
.equals(
1850 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1852 Log_OC
.e(TAG
, "Operations service crashed");
1853 mOperationsServiceBinder
= null
;
1860 * Create and show dialog for request authentication to the user
1864 public void createAuthenticationDialog(WebView webView
, HttpAuthHandler handler
) {
1866 // Show a dialog with the certificate info
1867 CredentialsDialogFragment dialog
=
1868 CredentialsDialogFragment
.newInstanceForCredentials(webView
, handler
);
1869 FragmentManager fm
= getSupportFragmentManager();
1870 FragmentTransaction ft
= fm
.beginTransaction();
1871 ft
.addToBackStack(null
);
1872 dialog
.setCancelable(false
);
1873 dialog
.show(ft
, CREDENTIALS_DIALOG_TAG
);
1875 if (!mIsFirstAuthAttempt
) {
1877 getApplicationContext(),
1878 getText(R
.string
.saml_authentication_wrong_pass
),
1882 mIsFirstAuthAttempt
= false
;
1887 * For retrieving the clicking on authentication cancel button
1889 public void doNegativeAuthenticatioDialogClick(){
1890 mIsFirstAuthAttempt
= true
;