1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.authentication
;
21 import java
.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
.Bundle
;
37 import android
.os
.Handler
;
38 import android
.os
.IBinder
;
39 import android
.preference
.PreferenceManager
;
40 import android
.support
.v4
.app
.Fragment
;
41 import android
.support
.v4
.app
.FragmentManager
;
42 import android
.support
.v4
.app
.FragmentTransaction
;
43 import android
.text
.Editable
;
44 import android
.text
.InputType
;
45 import android
.text
.TextWatcher
;
46 import android
.view
.KeyEvent
;
47 import android
.view
.MotionEvent
;
48 import android
.view
.View
;
49 import android
.view
.View
.OnFocusChangeListener
;
50 import android
.view
.View
.OnTouchListener
;
51 import android
.view
.Window
;
52 import android
.view
.inputmethod
.EditorInfo
;
53 import android
.webkit
.HttpAuthHandler
;
54 import android
.webkit
.SslErrorHandler
;
55 import android
.webkit
.WebView
;
56 import android
.widget
.Button
;
57 import android
.widget
.CheckBox
;
58 import android
.widget
.EditText
;
59 import android
.widget
.TextView
;
60 import android
.widget
.TextView
.OnEditorActionListener
;
61 import android
.widget
.Toast
;
63 import com
.actionbarsherlock
.app
.SherlockDialogFragment
;
64 import com
.owncloud
.android
.MainApp
;
65 import com
.owncloud
.android
.R
;
66 import com
.owncloud
.android
.authentication
.SsoWebViewClient
.SsoWebViewClientListener
;
67 import com
.owncloud
.android
.lib
.common
.accounts
.AccountTypeUtils
;
68 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.Constants
;
69 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
70 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
71 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
72 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
73 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
74 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
75 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
76 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
77 import com
.owncloud
.android
.lib
.resources
.users
.GetRemoteUserNameOperation
;
78 import com
.owncloud
.android
.operations
.DetectAuthenticationMethodOperation
.AuthenticationMethod
;
79 import com
.owncloud
.android
.operations
.GetServerInfoOperation
;
80 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
81 import com
.owncloud
.android
.services
.OperationsService
;
82 import com
.owncloud
.android
.services
.OperationsService
.OperationsServiceBinder
;
83 import com
.owncloud
.android
.ui
.dialog
.CredentialsDialogFragment
;
84 import com
.owncloud
.android
.ui
.dialog
.IndeterminateProgressDialog
;
85 import com
.owncloud
.android
.ui
.dialog
.SamlWebViewDialog
;
86 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
87 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
90 * This Activity is used to add an ownCloud account to the App
92 * @author Bartek Przybylski
93 * @author David A. Velasco
96 public class AuthenticatorActivity
extends AccountAuthenticatorActivity
97 implements OnRemoteOperationListener
, OnFocusChangeListener
, OnEditorActionListener
,
98 SsoWebViewClientListener
, OnSslUntrustedCertListener
{
100 private static final String TAG
= AuthenticatorActivity
.class.getSimpleName();
102 public static final String EXTRA_ACTION
= "ACTION";
103 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
105 private static final String KEY_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
107 private static final String KEY_HOST_URL_TEXT
= "HOST_URL_TEXT";
108 private static final String KEY_OC_VERSION
= "OC_VERSION";
109 private static final String KEY_SERVER_VALID
= "SERVER_VALID";
110 private static final String KEY_SERVER_CHECKED
= "SERVER_CHECKED";
111 private static final String KEY_SERVER_STATUS_TEXT
= "SERVER_STATUS_TEXT";
112 private static final String KEY_SERVER_STATUS_ICON
= "SERVER_STATUS_ICON";
113 private static final String KEY_IS_SSL_CONN
= "IS_SSL_CONN";
114 private static final String KEY_PASSWORD_EXPOSED
= "PASSWORD_VISIBLE";
115 private static final String KEY_AUTH_STATUS_TEXT
= "AUTH_STATUS_TEXT";
116 private static final String KEY_AUTH_STATUS_ICON
= "AUTH_STATUS_ICON";
117 private static final String KEY_SERVER_AUTH_METHOD
= "SERVER_AUTH_METHOD";
118 private static final String KEY_WAITING_FOR_OP_ID
= "WAITING_FOR_OP_ID";
119 private static final String KEY_AUTH_TOKEN
= "AUTH_TOKEN";
121 private static final String AUTH_ON
= "on";
122 private static final String AUTH_OPTIONAL
= "optional";
124 public static final byte ACTION_CREATE
= 0;
125 public static final byte ACTION_UPDATE_TOKEN
= 1; // requested by the user
126 public static final byte ACTION_UPDATE_EXPIRED_TOKEN
= 2; // detected by the app
128 private static final String UNTRUSTED_CERT_DIALOG_TAG
= "UNTRUSTED_CERT_DIALOG";
129 private static final String SAML_DIALOG_TAG
= "SAML_DIALOG";
130 private static final String WAIT_DIALOG_TAG
= "WAIT_DIALOG";
131 private static final String CREDENTIALS_DIALOG_TAG
= "CREDENTIALS_DIALOG";
132 private static final String KEY_AUTH_IS_FIRST_ATTEMPT_TAG
= "KEY_AUTH_IS_FIRST_ATTEMPT";
135 /// parameters from EXTRAs in starter Intent
136 private byte mAction
;
137 private Account mAccount
;
138 private String mAuthTokenType
;
141 /// activity-level references / state
142 private final Handler mHandler
= new Handler();
143 private ServiceConnection mOperationsServiceConnection
= null
;
144 private OperationsServiceBinder mOperationsServiceBinder
= null
;
145 private AccountManager mAccountMgr
;
146 private Uri mNewCapturedUriFromOAuth2Redirection
;
149 /// Server PRE-Fragment elements
150 private EditText mHostUrlInput
;
151 private View mRefreshButton
;
152 private TextView mServerStatusView
;
154 private TextWatcher mHostUrlInputWatcher
;
155 private int mServerStatusText
= 0, mServerStatusIcon
= 0;
157 private boolean mServerIsChecked
= false
;
158 private boolean mServerIsValid
= false
;
159 private boolean mPendingAutoCheck
= false
;
161 private GetServerInfoOperation
.ServerInfo mServerInfo
=
162 new GetServerInfoOperation
.ServerInfo();
165 /// Authentication PRE-Fragment elements
166 private CheckBox mOAuth2Check
;
167 private TextView mOAuthAuthEndpointText
;
168 private TextView mOAuthTokenEndpointText
;
169 private EditText mUsernameInput
;
170 private EditText mPasswordInput
;
171 private View mOkButton
;
172 private TextView mAuthStatusView
;
174 private int mAuthStatusText
= 0, mAuthStatusIcon
= 0;
176 private String mAuthToken
= "";
178 private boolean mIsFirstAuthAttempt
;
181 /// Identifier of operation in progress which result shouldn't be lost
182 private long mWaitingForOpId
= Long
.MAX_VALUE
;
188 * IMPORTANT ENTRY POINT 1: activity is shown to the user
191 protected void onCreate(Bundle savedInstanceState
) {
192 //Log_OC.wtf(TAG, "onCreate init");
193 super.onCreate(savedInstanceState
);
194 getWindow().requestFeature(Window
.FEATURE_NO_TITLE
);
196 mIsFirstAuthAttempt
= true
;
198 // bind to Operations Service
199 mOperationsServiceConnection
= new OperationsServiceConnection();
200 if (!bindService(new Intent(this, OperationsService
.class),
201 mOperationsServiceConnection
,
202 Context
.BIND_AUTO_CREATE
)) {
204 R
.string
.error_cant_bind_to_operations_service
,
210 /// init activity state
211 mAccountMgr
= AccountManager
.get(this);
212 mNewCapturedUriFromOAuth2Redirection
= null
;
215 mAction
= getIntent().getByteExtra(EXTRA_ACTION
, ACTION_CREATE
);
216 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
217 if (savedInstanceState
== null
) {
220 mAuthTokenType
= savedInstanceState
.getString(KEY_AUTH_TOKEN_TYPE
);
221 mWaitingForOpId
= savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
);
222 mIsFirstAuthAttempt
= savedInstanceState
.getBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
);
225 /// load user interface
226 setContentView(R
.layout
.account_setup
);
228 /// initialize general UI elements
229 initOverallUi(savedInstanceState
);
231 mOkButton
= findViewById(R
.id
.buttonOK
);
233 /// initialize block to be moved to single Fragment to check server and get info about it
234 initServerPreFragment(savedInstanceState
);
236 /// initialize block to be moved to single Fragment to retrieve and validate credentials
237 initAuthorizationPreFragment(savedInstanceState
);
239 //Log_OC.wtf(TAG, "onCreate end");
242 private void initAuthTokenType() {
244 getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
245 if (mAuthTokenType
== null
) {
246 if (mAccount
!= null
) {
247 boolean oAuthRequired
=
248 (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
) != null
);
249 boolean samlWebSsoRequired
= (
250 mAccountMgr
.getUserData(
251 mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
254 mAuthTokenType
= chooseAuthTokenType(oAuthRequired
, samlWebSsoRequired
);
257 boolean oAuthSupported
= AUTH_ON
.equals(getString(R
.string
.auth_method_oauth2
));
258 boolean samlWebSsoSupported
=
259 AUTH_ON
.equals(getString(R
.string
.auth_method_saml_web_sso
));
260 mAuthTokenType
= chooseAuthTokenType(oAuthSupported
, samlWebSsoSupported
);
265 private String
chooseAuthTokenType(boolean oauth
, boolean saml
) {
267 return AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
269 return AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
271 return AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
277 * Configures elements in the user interface under direct control of the Activity.
279 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
281 private void initOverallUi(Bundle savedInstanceState
) {
283 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
284 boolean isWelcomeLinkVisible
= getResources().getBoolean(R
.bool
.show_welcome_link
);
286 String instructionsMessageText
= null
;
287 if (mAction
== ACTION_UPDATE_EXPIRED_TOKEN
) {
288 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
289 .equals(mAuthTokenType
)) {
290 instructionsMessageText
= getString(R
.string
.auth_expired_oauth_token_toast
);
292 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType())
293 .equals(mAuthTokenType
)) {
294 instructionsMessageText
= getString(R
.string
.auth_expired_saml_sso_token_toast
);
297 instructionsMessageText
= getString(R
.string
.auth_expired_basic_auth_toast
);
301 /// step 2 - set properties of UI elements (text, visibility, enabled...)
302 Button welcomeLink
= (Button
) findViewById(R
.id
.welcome_link
);
303 welcomeLink
.setVisibility(isWelcomeLinkVisible ? View
.VISIBLE
: View
.GONE
);
305 String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
307 TextView instructionsView
= (TextView
) findViewById(R
.id
.instructions_message
);
308 if (instructionsMessageText
!= null
) {
309 instructionsView
.setVisibility(View
.VISIBLE
);
310 instructionsView
.setText(instructionsMessageText
);
312 instructionsView
.setVisibility(View
.GONE
);
319 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
321 private void initServerPreFragment(Bundle savedInstanceState
) {
323 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
324 boolean isUrlInputAllowed
= getResources().getBoolean(R
.bool
.show_server_url_input
);
325 if (savedInstanceState
== null
) {
326 if (mAccount
!= null
) {
327 mServerInfo
.mBaseUrl
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_BASE_URL
);
328 // TODO do next in a setter for mBaseUrl
329 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
330 String ocVersion
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_VERSION
);
331 if (ocVersion
!= null
) {
332 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
335 mServerInfo
.mBaseUrl
= getString(R
.string
.server_url
).trim();
336 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
339 mServerStatusText
= savedInstanceState
.getInt(KEY_SERVER_STATUS_TEXT
);
340 mServerStatusIcon
= savedInstanceState
.getInt(KEY_SERVER_STATUS_ICON
);
342 mServerIsValid
= savedInstanceState
.getBoolean(KEY_SERVER_VALID
);
343 mServerIsChecked
= savedInstanceState
.getBoolean(KEY_SERVER_CHECKED
);
346 mServerInfo
.mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
347 mServerInfo
.mBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
348 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
349 if (ocVersion
!= null
) {
350 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
352 mServerInfo
.mAuthMethod
= AuthenticationMethod
.valueOf(
353 savedInstanceState
.getString(KEY_SERVER_AUTH_METHOD
));
357 /// step 2 - set properties of UI elements (text, visibility, enabled...)
358 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
359 mHostUrlInput
.setText(mServerInfo
.mBaseUrl
);
360 if (mAction
!= ACTION_CREATE
) {
361 /// lock things that should not change
362 mHostUrlInput
.setEnabled(false
);
363 mHostUrlInput
.setFocusable(false
);
365 if (isUrlInputAllowed
) {
366 mRefreshButton
= findViewById(R
.id
.embeddedRefreshButton
);
368 findViewById(R
.id
.hostUrlFrame
).setVisibility(View
.GONE
);
369 mRefreshButton
= findViewById(R
.id
.centeredRefreshButton
);
371 showRefreshButton(mServerIsChecked
&& !mServerIsValid
&&
372 mWaitingForOpId
> Integer
.MAX_VALUE
);
373 mServerStatusView
= (TextView
) findViewById(R
.id
.server_status_text
);
376 /// step 3 - bind some listeners and options
377 mHostUrlInput
.setImeOptions(EditorInfo
.IME_ACTION_NEXT
);
378 mHostUrlInput
.setOnEditorActionListener(this);
380 /// step 4 - create listeners that will be bound at onResume
381 mHostUrlInputWatcher
= new TextWatcher() {
384 public void afterTextChanged(Editable s
) {
385 if (mOkButton
.isEnabled() &&
386 !mServerInfo
.mBaseUrl
.equals(
387 normalizeUrl(s
.toString(), mServerInfo
.mIsSslConn
))) {
388 mOkButton
.setEnabled(false
);
393 public void beforeTextChanged(CharSequence s
, int start
, int count
, int after
) {
397 public void onTextChanged(CharSequence s
, int start
, int before
, int count
) {
398 if (mAuthStatusIcon
!= 0) {
399 Log_OC
.d(TAG
, "onTextChanged: hiding authentication status");
408 // TODO find out if this is really necessary, or if it can done in a different way
409 findViewById(R
.id
.scroll
).setOnTouchListener(new OnTouchListener() {
411 public boolean onTouch(View view
, MotionEvent event
) {
412 if (event
.getAction() == MotionEvent
.ACTION_DOWN
) {
414 AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(
415 MainApp
.getAccountType()
416 ).equals(mAuthTokenType
) &&
417 mHostUrlInput
.hasFocus()
427 /// step 4 - mark automatic check to be started when OperationsService is ready
428 mPendingAutoCheck
= (savedInstanceState
== null
&&
429 (mAction
!= ACTION_CREATE
|| !isUrlInputAllowed
));
435 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
437 private void initAuthorizationPreFragment(Bundle savedInstanceState
) {
439 /// step 0 - get UI elements in layout
440 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
441 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
442 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
443 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
444 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
445 mAuthStatusView
= (TextView
) findViewById(R
.id
.auth_status_text
);
447 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
448 String presetUserName
= null
;
449 boolean isPasswordExposed
= false
;
450 if (savedInstanceState
== null
) {
451 if (mAccount
!= null
) {
452 presetUserName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
456 isPasswordExposed
= savedInstanceState
.getBoolean(KEY_PASSWORD_EXPOSED
, false
);
457 mAuthStatusText
= savedInstanceState
.getInt(KEY_AUTH_STATUS_TEXT
);
458 mAuthStatusIcon
= savedInstanceState
.getInt(KEY_AUTH_STATUS_ICON
);
459 mAuthToken
= savedInstanceState
.getString(KEY_AUTH_TOKEN
);
462 /// step 2 - set properties of UI elements (text, visibility, enabled...)
463 mOAuth2Check
.setChecked(
464 AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
465 .equals(mAuthTokenType
));
466 if (presetUserName
!= null
) {
467 mUsernameInput
.setText(presetUserName
);
469 if (mAction
!= ACTION_CREATE
) {
470 mUsernameInput
.setEnabled(false
);
471 mUsernameInput
.setFocusable(false
);
473 mPasswordInput
.setText(""); // clean password to avoid social hacking
474 if (isPasswordExposed
) {
477 updateAuthenticationPreFragmentVisibility();
479 mOkButton
.setEnabled(mServerIsValid
);
482 /// step 3 - bind listeners
483 // bindings for password input field
484 mPasswordInput
.setOnFocusChangeListener(this);
485 mPasswordInput
.setImeOptions(EditorInfo
.IME_ACTION_DONE
);
486 mPasswordInput
.setOnEditorActionListener(this);
487 mPasswordInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
489 public boolean onDrawableTouch(final MotionEvent event
) {
490 if (event
.getAction() == MotionEvent
.ACTION_UP
) {
491 AuthenticatorActivity
.this.onViewPasswordClick();
501 * Changes the visibility of input elements depending on
502 * the current authorization method.
504 private void updateAuthenticationPreFragmentVisibility () {
505 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
506 equals(mAuthTokenType
)) {
507 // SAML-based web Single Sign On
508 mOAuth2Check
.setVisibility(View
.GONE
);
509 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
510 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
511 mUsernameInput
.setVisibility(View
.GONE
);
512 mPasswordInput
.setVisibility(View
.GONE
);
515 if (mAction
== ACTION_CREATE
&&
516 AUTH_OPTIONAL
.equals(getString(R
.string
.auth_method_oauth2
))) {
517 mOAuth2Check
.setVisibility(View
.VISIBLE
);
519 mOAuth2Check
.setVisibility(View
.GONE
);
522 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
523 equals(mAuthTokenType
)) {
524 // OAuth 2 authorization
526 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
527 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
528 mUsernameInput
.setVisibility(View
.GONE
);
529 mPasswordInput
.setVisibility(View
.GONE
);
532 // basic HTTP authorization
533 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
534 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
535 mUsernameInput
.setVisibility(View
.VISIBLE
);
536 mPasswordInput
.setVisibility(View
.VISIBLE
);
544 * Saves relevant state before {@link #onPause()}
546 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag,
547 * intended to defer the processing of the redirection caught in
548 * {@link #onNewIntent(Intent)} until {@link #onResume()}
550 * See {@link #loadSavedInstanceState(Bundle)}
553 protected void onSaveInstanceState(Bundle outState
) {
554 //Log_OC.wtf(TAG, "onSaveInstanceState init" );
555 super.onSaveInstanceState(outState
);
558 outState
.putString(KEY_AUTH_TOKEN_TYPE
, mAuthTokenType
);
559 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mWaitingForOpId
);
561 /// Server PRE-fragment state
562 outState
.putInt(KEY_SERVER_STATUS_TEXT
, mServerStatusText
);
563 outState
.putInt(KEY_SERVER_STATUS_ICON
, mServerStatusIcon
);
564 outState
.putBoolean(KEY_SERVER_CHECKED
, mServerIsChecked
);
565 outState
.putBoolean(KEY_SERVER_VALID
, mServerIsValid
);
566 outState
.putBoolean(KEY_IS_SSL_CONN
, mServerInfo
.mIsSslConn
);
567 outState
.putString(KEY_HOST_URL_TEXT
, mServerInfo
.mBaseUrl
);
568 if (mServerInfo
.mVersion
!= null
) {
569 outState
.putString(KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion());
571 outState
.putString(KEY_SERVER_AUTH_METHOD
, mServerInfo
.mAuthMethod
.name());
573 /// Authentication PRE-fragment state
574 outState
.putBoolean(KEY_PASSWORD_EXPOSED
, isPasswordVisible());
575 outState
.putInt(KEY_AUTH_STATUS_ICON
, mAuthStatusIcon
);
576 outState
.putInt(KEY_AUTH_STATUS_TEXT
, mAuthStatusText
);
577 outState
.putString(KEY_AUTH_TOKEN
, mAuthToken
);
580 outState
.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
, mIsFirstAuthAttempt
);
582 //Log_OC.wtf(TAG, "onSaveInstanceState end" );
587 * The redirection triggered by the OAuth authentication server as response to the
588 * GET AUTHORIZATION request is caught here.
590 * To make this possible, this activity needs to be qualified with android:launchMode =
591 * "singleTask" in the AndroidManifest.xml file.
594 protected void onNewIntent (Intent intent
) {
595 Log_OC
.d(TAG
, "onNewIntent()");
596 Uri data
= intent
.getData();
597 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
598 mNewCapturedUriFromOAuth2Redirection
= data
;
604 * The redirection triggered by the OAuth authentication server as response to the
605 * GET AUTHORIZATION, and deferred in {@link #onNewIntent(Intent)}, is processed here.
608 protected void onResume() {
609 //Log_OC.wtf(TAG, "onResume init" );
612 // bound here to avoid spurious changes triggered by Android on device rotations
613 mHostUrlInput
.setOnFocusChangeListener(this);
614 mHostUrlInput
.addTextChangedListener(mHostUrlInputWatcher
);
616 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
617 getOAuth2AccessTokenFromCapturedRedirection();
620 if (mOperationsServiceBinder
!= null
) {
621 doOnResumeAndBound();
624 //Log_OC.wtf(TAG, "onResume end" );
629 protected void onPause() {
630 //Log_OC.wtf(TAG, "onPause init" );
631 if (mOperationsServiceBinder
!= null
) {
632 //Log_OC.wtf(TAG, "unregistering to listen for operation callbacks" );
633 mOperationsServiceBinder
.removeOperationListener(this);
636 mHostUrlInput
.removeTextChangedListener(mHostUrlInputWatcher
);
637 mHostUrlInput
.setOnFocusChangeListener(null
);
640 //Log_OC.wtf(TAG, "onPause end" );
644 protected void onDestroy() {
646 mHostUrlInputWatcher
= null
;
648 if (mOperationsServiceConnection
!= null
) {
649 unbindService(mOperationsServiceConnection
);
650 mOperationsServiceBinder
= null
;
657 * Parses the redirection with the response to the GET AUTHORIZATION request to the
658 * oAuth server and requests for the access token (GET ACCESS TOKEN)
660 private void getOAuth2AccessTokenFromCapturedRedirection() {
661 /// Parse data from OAuth redirection
662 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
663 mNewCapturedUriFromOAuth2Redirection
= null
;
665 /// Showing the dialog with instructions for the user.
666 IndeterminateProgressDialog dialog
=
667 IndeterminateProgressDialog
.newInstance(R
.string
.auth_getting_authorization
, true
);
668 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
670 /// GET ACCESS TOKEN to the oAuth server
671 Intent getServerInfoIntent
= new Intent();
672 getServerInfoIntent
.setAction(OperationsService
.ACTION_OAUTH2_GET_ACCESS_TOKEN
);
674 getServerInfoIntent
.putExtra(
675 OperationsService
.EXTRA_SERVER_URL
,
676 mOAuthTokenEndpointText
.getText().toString().trim());
678 getServerInfoIntent
.putExtra(
679 OperationsService
.EXTRA_OAUTH2_QUERY_PARAMETERS
,
682 if (mOperationsServiceBinder
!= null
) {
683 //Log_OC.wtf(TAG, "getting access token..." );
684 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(getServerInfoIntent
);
691 * Handles the change of focus on the text inputs for the server URL and the password
693 public void onFocusChange(View view
, boolean hasFocus
) {
694 if (view
.getId() == R
.id
.hostUrlInput
) {
696 onUrlInputFocusLost((TextView
) view
);
699 showRefreshButton(false
);
702 } else if (view
.getId() == R
.id
.account_password
) {
703 onPasswordFocusChanged((TextView
) view
, hasFocus
);
709 * Handles changes in focus on the text input for the server URL.
711 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
712 * other field. The operation to check the existence of the server in the entered URL is
715 * When hasFocus: user 'comes back' to write again the server URL.
717 * @param hostInput TextView with the URL input field receiving the change of focus.
719 private void onUrlInputFocusLost(TextView hostInput
) {
720 if (!mServerInfo
.mBaseUrl
.equals(
721 normalizeUrl(mHostUrlInput
.getText().toString(), mServerInfo
.mIsSslConn
))) {
722 // check server again only if the user changed something in the field
725 mOkButton
.setEnabled(mServerIsValid
);
726 showRefreshButton(!mServerIsValid
);
731 private void checkOcServer() {
732 String uri
= mHostUrlInput
.getText().toString().trim();
733 mServerIsValid
= false
;
734 mServerIsChecked
= false
;
735 mOkButton
.setEnabled(false
);
736 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
737 showRefreshButton(false
);
739 if (uri
.length() != 0) {
740 mServerStatusText
= R
.string
.auth_testing_connection
;
741 mServerStatusIcon
= R
.drawable
.progress_small
;
744 Intent getServerInfoIntent
= new Intent();
745 getServerInfoIntent
.setAction(OperationsService
.ACTION_GET_SERVER_INFO
);
746 getServerInfoIntent
.putExtra(
747 OperationsService
.EXTRA_SERVER_URL
,
748 normalizeUrlSuffix(uri
)
750 if (mOperationsServiceBinder
!= null
) {
751 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(getServerInfoIntent
);
753 Log_OC
.wtf(TAG
, "Server check tried with OperationService unbound!" );
757 mServerStatusText
= 0;
758 mServerStatusIcon
= 0;
765 * Handles changes in focus on the text input for the password (basic authorization).
767 * When (hasFocus), the button to toggle password visibility is shown.
769 * When (!hasFocus), the button is made invisible and the password is hidden.
771 * @param passwordInput TextView with the password input field receiving the change of focus.
772 * @param hasFocus 'True' if focus is received, 'false' if is lost
774 private void onPasswordFocusChanged(TextView passwordInput
, boolean hasFocus
) {
776 showViewPasswordButton();
779 hidePasswordButton();
784 private void showViewPasswordButton() {
785 int drawable
= R
.drawable
.ic_view
;
786 if (isPasswordVisible()) {
787 drawable
= R
.drawable
.ic_hide
;
789 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable
, 0);
792 private boolean isPasswordVisible() {
793 return ((mPasswordInput
.getInputType() & InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) ==
794 InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
797 private void hidePasswordButton() {
798 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
801 private void showPassword() {
802 mPasswordInput
.setInputType(
803 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
805 showViewPasswordButton();
808 private void hidePassword() {
809 mPasswordInput
.setInputType(
810 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
812 showViewPasswordButton();
816 * Checks the credentials of the user in the root of the ownCloud server
817 * before creating a new local account.
819 * For basic authorization, a check of existence of the root folder is
822 * For OAuth, starts the flow to get an access token; the credentials test
823 * is postponed until it is available.
825 * IMPORTANT ENTRY POINT 4
827 * @param view OK button
829 public void onOkClick(View view
) {
830 // this check should be unnecessary
831 if (mServerInfo
.mVersion
== null
||
832 !mServerInfo
.mVersion
.isVersionValid() ||
833 mServerInfo
.mBaseUrl
== null
||
834 mServerInfo
.mBaseUrl
.length() == 0) {
835 mServerStatusIcon
= R
.drawable
.common_error
;
836 mServerStatusText
= R
.string
.auth_wtf_reenter_URL
;
838 mOkButton
.setEnabled(false
);
839 //Log_OC.wtf(TAG, "The user was allowed to click 'connect' to an unchecked server!!");
843 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
844 equals(mAuthTokenType
)) {
846 startOauthorization();
847 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
848 equals(mAuthTokenType
)) {
850 startSamlBasedFederatedSingleSignOnAuthorization();
852 checkBasicAuthorization();
858 * Tests the credentials entered by the user performing a check of existence on
859 * the root folder of the ownCloud server.
861 private void checkBasicAuthorization() {
862 /// get basic credentials entered by user
863 String username
= mUsernameInput
.getText().toString();
864 String password
= mPasswordInput
.getText().toString();
866 /// be gentle with the user
867 IndeterminateProgressDialog dialog
=
868 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
869 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
871 /// validate credentials accessing the root folder
872 accessRootFolderRemoteOperation(username
, password
);
876 private void accessRootFolderRemoteOperation(String username
, String password
) {
877 Intent existenceCheckIntent
= new Intent();
878 existenceCheckIntent
.setAction(OperationsService
.ACTION_EXISTENCE_CHECK
);
879 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
880 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_REMOTE_PATH
, "/");
881 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_USERNAME
, username
);
882 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_PASSWORD
, password
);
883 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_AUTH_TOKEN
, mAuthToken
);
885 if (mOperationsServiceBinder
!= null
) {
886 //Log_OC.wtf(TAG, "starting existenceCheckRemoteOperation..." );
887 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(existenceCheckIntent
);
892 * Starts the OAuth 'grant type' flow to get an access token, with
893 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
895 private void startOauthorization() {
896 // be gentle with the user
897 mAuthStatusIcon
= R
.drawable
.progress_small
;
898 mAuthStatusText
= R
.string
.oauth_login_connection
;
901 // GET AUTHORIZATION request
902 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
903 Uri
.Builder uriBuilder
= uri
.buildUpon();
904 uriBuilder
.appendQueryParameter(
905 OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
)
907 uriBuilder
.appendQueryParameter(
908 OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
)
910 uriBuilder
.appendQueryParameter(
911 OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
)
913 uriBuilder
.appendQueryParameter(
914 OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
)
916 uri
= uriBuilder
.build();
917 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
918 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
924 * Starts the Web Single Sign On flow to get access to the root folder
927 private void startSamlBasedFederatedSingleSignOnAuthorization() {
928 // be gentle with the user
929 mAuthStatusIcon
= R
.drawable
.progress_small
;
930 mAuthStatusText
= R
.string
.auth_connecting_auth_server
;
932 IndeterminateProgressDialog dialog
=
933 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
934 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
936 /// validate credentials accessing the root folder
937 accessRootFolderRemoteOperation("", "");
942 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
944 * Dispatches the operation flow to the right method.
947 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
949 if (operation
instanceof GetServerInfoOperation
) {
950 if (operation
.hashCode() == mWaitingForOpId
) {
951 onGetServerInfoFinish(result
);
952 } // else nothing ; only the last check operation is considered;
953 // multiple can be started if the user amends a URL quickly
955 } else if (operation
instanceof OAuth2GetAccessToken
) {
956 onGetOAuthAccessTokenFinish(result
);
958 } else if (operation
instanceof ExistenceCheckRemoteOperation
) {
959 //Log_OC.wtf(TAG, "received detection response through callback" );
960 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
961 equals(mAuthTokenType
)) {
962 onSamlBasedFederatedSingleSignOnAuthorizationStart(result
);
965 onAuthorizationCheckFinish(result
);
967 } else if (operation
instanceof GetRemoteUserNameOperation
) {
968 onGetUserNameFinish(result
);
973 private void onGetUserNameFinish(RemoteOperationResult result
) {
974 mWaitingForOpId
= Long
.MAX_VALUE
;
975 if (result
.isSuccess()) {
976 boolean success
= false
;
977 String username
= (String
) result
.getData().get(0);
979 if ( mAction
== ACTION_CREATE
) {
980 mUsernameInput
.setText(username
);
981 success
= createAccount();
984 if (!mUsernameInput
.getText().toString().equals(username
)) {
985 // fail - not a new account, but an existing one; disallow
986 result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_THE_SAME
);
988 OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(
990 Uri.parse(mServerInfo.mBaseUrl),
991 OwnCloudCredentialsFactory.newSamlSsoCredentials(mAuthToken))
995 updateAuthStatusIconAndText(result
);
997 Log_OC
.d(TAG
, result
.getLogMessage());
1007 updateStatusIconFailUserName();
1009 Log_OC
.e(TAG
, "Access to user name failed: " + result
.getLogMessage());
1014 private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperationResult result
) {
1015 mWaitingForOpId
= Long
.MAX_VALUE
;
1016 dismissDialog(WAIT_DIALOG_TAG
);
1018 if (result
.isIdPRedirection()) {
1019 String url
= result
.getRedirectedLocation();
1020 String targetUrl
= mServerInfo
.mBaseUrl
1021 + AccountUtils
.getWebdavPath(mServerInfo
.mVersion
, mAuthTokenType
);
1024 SamlWebViewDialog dialog
= SamlWebViewDialog
.newInstance(url
, targetUrl
);
1025 dialog
.show(getSupportFragmentManager(), SAML_DIALOG_TAG
);
1027 mAuthStatusIcon
= 0;
1028 mAuthStatusText
= 0;
1031 mAuthStatusIcon
= R
.drawable
.common_error
;
1032 mAuthStatusText
= R
.string
.auth_unsupported_auth_method
;
1040 * Processes the result of the server check performed when the user finishes the enter of the
1043 * @param operation Server check performed.
1044 * @param result Result of the check.
1046 private void onGetServerInfoFinish(RemoteOperationResult result
) {
1047 /// update activity state
1048 mServerIsChecked
= true
;
1049 mWaitingForOpId
= Long
.MAX_VALUE
;
1051 // update server status, but don't show it yet
1052 updateServerStatusIconAndText(result
);
1054 if (result
.isSuccess()) {
1056 // 1. connection succeeded, and we know if it's SSL or not
1057 // 2. server is installed
1058 // 3. we got the server version
1059 // 4. we got the authentication method required by the server
1060 mServerInfo
= (GetServerInfoOperation
.ServerInfo
) (result
.getData().get(0));
1062 if (!authSupported(mServerInfo
.mAuthMethod
)) {
1064 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1065 mServerIsValid
= false
;
1068 mServerIsValid
= true
;
1072 mServerIsValid
= false
;
1076 showRefreshButton(!mServerIsValid
);
1078 mOkButton
.setEnabled(mServerIsValid
);
1080 /// very special case (TODO: move to a common place for all the remote operations)
1081 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1082 showUntrustedCertDialog(result
);
1087 private boolean authSupported(AuthenticationMethod authMethod
) {
1088 String basic
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1089 String oAuth
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1090 String saml
= AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
1092 return (( mAuthTokenType
.equals(basic
) &&
1093 authMethod
.equals(AuthenticationMethod
.BASIC_HTTP_AUTH
) ) ||
1094 ( mAuthTokenType
.equals(oAuth
) &&
1095 authMethod
.equals(AuthenticationMethod
.BEARER_TOKEN
)) ||
1096 ( mAuthTokenType
.equals(saml
) &&
1097 authMethod
.equals(AuthenticationMethod
.SAML_WEB_SSO
))
1102 // TODO remove, if possible
1103 private String
normalizeUrl(String url
, boolean sslWhenUnprefixed
) {
1104 if (url
!= null
&& url
.length() > 0) {
1106 if (!url
.toLowerCase().startsWith("http://") &&
1107 !url
.toLowerCase().startsWith("https://")) {
1108 if (sslWhenUnprefixed
) {
1109 url
= "https://" + url
;
1111 url
= "http://" + url
;
1115 url
= normalizeUrlSuffix(url
);
1117 return (url
!= null ? url
: "");
1121 private String
normalizeUrlSuffix(String url
) {
1122 if (url
.endsWith("/")) {
1123 url
= url
.substring(0, url
.length() - 1);
1125 url
= trimUrlWebdav(url
);
1130 // TODO remove, if possible
1131 private String
trimUrlWebdav(String url
){
1132 if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_4_0
)){
1133 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_4_0
.length());
1134 } else if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_2_0
)){
1135 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_2_0
.length());
1136 } else if (url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_1_2
)){
1137 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_1_2
.length());
1139 return (url
!= null ? url
: "");
1144 * Chooses the right icon and text to show to the user for the received operation result.
1146 * @param result Result of a remote operation performed in this activity
1148 private void updateServerStatusIconAndText(RemoteOperationResult result
) {
1149 mServerStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1151 switch (result
.getCode()) {
1153 mServerStatusIcon
= android
.R
.drawable
.ic_secure
;
1154 mServerStatusText
= R
.string
.auth_secure_connection
;
1159 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1160 mServerStatusText
= R
.string
.auth_connection_established
;
1161 mServerStatusIcon
= R
.drawable
.ic_ok
;
1163 mServerStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1164 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1168 case NO_NETWORK_CONNECTION
:
1169 mServerStatusIcon
= R
.drawable
.no_network
;
1170 mServerStatusText
= R
.string
.auth_no_net_conn_title
;
1173 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1174 mServerStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1176 case BAD_OC_VERSION
:
1177 mServerStatusText
= R
.string
.auth_bad_oc_version_title
;
1179 case WRONG_CONNECTION
:
1180 mServerStatusText
= R
.string
.auth_wrong_connection_title
;
1183 mServerStatusText
= R
.string
.auth_timeout_title
;
1185 case INCORRECT_ADDRESS
:
1186 mServerStatusText
= R
.string
.auth_incorrect_address_title
;
1189 mServerStatusText
= R
.string
.auth_ssl_general_error_title
;
1192 mServerStatusText
= R
.string
.auth_unauthorized
;
1194 case HOST_NOT_AVAILABLE
:
1195 mServerStatusText
= R
.string
.auth_unknown_host_title
;
1197 case INSTANCE_NOT_CONFIGURED
:
1198 mServerStatusText
= R
.string
.auth_not_configured_title
;
1200 case FILE_NOT_FOUND
:
1201 mServerStatusText
= R
.string
.auth_incorrect_path_title
;
1204 mServerStatusText
= R
.string
.auth_oauth_error
;
1206 case OAUTH2_ERROR_ACCESS_DENIED
:
1207 mServerStatusText
= R
.string
.auth_oauth_error_access_denied
;
1209 case UNHANDLED_HTTP_CODE
:
1211 mServerStatusText
= R
.string
.auth_unknown_error_title
;
1213 case OK_REDIRECT_TO_NON_SECURE_CONNECTION
:
1214 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1215 mServerStatusText
= R
.string
.auth_redirect_non_secure_connection_title
;
1218 mServerStatusText
= 0;
1219 mServerStatusIcon
= 0;
1225 * Chooses the right icon and text to show to the user for the received operation result.
1227 * @param result Result of a remote operation performed in this activity
1229 private void updateAuthStatusIconAndText(RemoteOperationResult result
) {
1230 mAuthStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1232 switch (result
.getCode()) {
1234 mAuthStatusIcon
= android
.R
.drawable
.ic_secure
;
1235 mAuthStatusText
= R
.string
.auth_secure_connection
;
1240 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1241 mAuthStatusText
= R
.string
.auth_connection_established
;
1242 mAuthStatusIcon
= R
.drawable
.ic_ok
;
1244 mAuthStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1245 mAuthStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1249 case NO_NETWORK_CONNECTION
:
1250 mAuthStatusIcon
= R
.drawable
.no_network
;
1251 mAuthStatusText
= R
.string
.auth_no_net_conn_title
;
1254 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1255 mAuthStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1257 case BAD_OC_VERSION
:
1258 mAuthStatusText
= R
.string
.auth_bad_oc_version_title
;
1260 case WRONG_CONNECTION
:
1261 mAuthStatusText
= R
.string
.auth_wrong_connection_title
;
1264 mAuthStatusText
= R
.string
.auth_timeout_title
;
1266 case INCORRECT_ADDRESS
:
1267 mAuthStatusText
= R
.string
.auth_incorrect_address_title
;
1270 mAuthStatusText
= R
.string
.auth_ssl_general_error_title
;
1273 mAuthStatusText
= R
.string
.auth_unauthorized
;
1275 case HOST_NOT_AVAILABLE
:
1276 mAuthStatusText
= R
.string
.auth_unknown_host_title
;
1278 case INSTANCE_NOT_CONFIGURED
:
1279 mAuthStatusText
= R
.string
.auth_not_configured_title
;
1281 case FILE_NOT_FOUND
:
1282 mAuthStatusText
= R
.string
.auth_incorrect_path_title
;
1285 mAuthStatusText
= R
.string
.auth_oauth_error
;
1287 case OAUTH2_ERROR_ACCESS_DENIED
:
1288 mAuthStatusText
= R
.string
.auth_oauth_error_access_denied
;
1290 case ACCOUNT_NOT_NEW
:
1291 mAuthStatusText
= R
.string
.auth_account_not_new
;
1293 case ACCOUNT_NOT_THE_SAME
:
1294 mAuthStatusText
= R
.string
.auth_account_not_the_same
;
1296 case UNHANDLED_HTTP_CODE
:
1298 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
1301 mAuthStatusText
= 0;
1302 mAuthStatusIcon
= 0;
1307 private void updateStatusIconFailUserName(){
1308 mAuthStatusIcon
= R
.drawable
.common_error
;
1309 mAuthStatusText
= R
.string
.auth_fail_get_user_name
;
1312 private void updateServerStatusIconNoRegularAuth(){
1313 mServerStatusIcon
= R
.drawable
.common_error
;
1314 mServerStatusText
= R
.string
.auth_can_not_auth_against_server
;
1318 * Processes the result of the request for and access token send
1319 * to an OAuth authorization server.
1321 * @param result Result of the operation.
1323 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result
) {
1324 mWaitingForOpId
= Long
.MAX_VALUE
;
1325 dismissDialog(WAIT_DIALOG_TAG
);
1327 if (result
.isSuccess()) {
1328 /// be gentle with the user
1329 IndeterminateProgressDialog dialog
=
1330 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
1331 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
1333 /// time to test the retrieved access token on the ownCloud server
1334 @SuppressWarnings("unchecked")
1335 Map
<String
, String
> tokens
= (Map
<String
, String
>)(result
.getData().get(0));
1336 mAuthToken
= tokens
.get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
1337 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mAuthToken
);
1339 accessRootFolderRemoteOperation("", "");
1342 updateAuthStatusIconAndText(result
);
1344 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1350 * Processes the result of the access check performed to try the user credentials.
1352 * Creates a new account through the AccountManager.
1354 * @param operation Access check performed.
1355 * @param result Result of the operation.
1357 private void onAuthorizationCheckFinish(RemoteOperationResult result
) {
1358 mWaitingForOpId
= Long
.MAX_VALUE
;
1359 dismissDialog(WAIT_DIALOG_TAG
);
1361 if (result
.isSuccess()) {
1362 Log_OC
.d(TAG
, "Successful access - time to save the account");
1364 boolean success
= false
;
1365 if (mAction
== ACTION_CREATE
) {
1366 success
= createAccount();
1377 } else if (result
.isServerFail() || result
.isException()) {
1378 /// server errors or exceptions in authorization take to requiring a new check of
1380 mServerIsChecked
= true
;
1381 mServerIsValid
= false
;
1382 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
1384 // update status icon and text
1385 updateServerStatusIconAndText(result
);
1387 mAuthStatusIcon
= 0;
1388 mAuthStatusText
= 0;
1391 // update input controls state
1392 showRefreshButton(true
);
1393 mOkButton
.setEnabled(false
);
1395 // very special case (TODO: move to a common place for all the remote operations)
1396 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1397 showUntrustedCertDialog(result
);
1400 } else { // authorization fail due to client side - probably wrong credentials
1401 updateAuthStatusIconAndText(result
);
1403 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1411 * Sets the proper response to get that the Account Authenticator that started this activity
1412 * saves a new authorization token for mAccount.
1414 private void updateToken() {
1415 Bundle response
= new Bundle();
1416 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1417 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
1419 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
1420 equals(mAuthTokenType
)) {
1421 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1422 // the next line is necessary, notifications are calling directly to the
1423 // AuthenticatorActivity to update, without AccountManager intervention
1424 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1426 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1427 equals(mAuthTokenType
)) {
1429 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1430 // the next line is necessary; by now, notifications are calling directly to the
1431 // AuthenticatorActivity to update, without AccountManager intervention
1432 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1435 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
1436 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
1438 setAccountAuthenticatorResult(response
);
1444 * Creates a new account through the Account Authenticator that started this activity.
1446 * This makes the account permanent.
1448 * TODO Decide how to name the OAuth accounts
1450 private boolean createAccount() {
1451 /// create and save new ownCloud account
1452 boolean isOAuth
= AccountTypeUtils
.
1453 getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
);
1454 boolean isSaml
= AccountTypeUtils
.
1455 getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
);
1457 Uri uri
= Uri
.parse(mServerInfo
.mBaseUrl
);
1458 String username
= mUsernameInput
.getText().toString().trim();
1460 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1462 String accountName
= com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.
1463 buildAccountName(uri
, username
);
1464 Account newAccount
= new Account(accountName
, MainApp
.getAccountType());
1465 if (AccountUtils
.exists(newAccount
, getApplicationContext())) {
1466 // fail - not a new account, but an existing one; disallow
1467 RemoteOperationResult result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_NEW
);
1468 updateAuthStatusIconAndText(result
);
1470 Log_OC
.d(TAG
, result
.getLogMessage());
1474 mAccount
= newAccount
;
1476 if (isOAuth
|| isSaml
) {
1477 // with external authorizations, the password is never input in the app
1478 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
);
1480 mAccountMgr
.addAccountExplicitly(
1481 mAccount
, mPasswordInput
.getText().toString(), null
1485 /// add the new account as default in preferences, if there is none already
1486 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1487 if (defaultAccount
== null
) {
1488 SharedPreferences
.Editor editor
= PreferenceManager
1489 .getDefaultSharedPreferences(this).edit();
1490 editor
.putString("select_oc_account", accountName
);
1494 /// prepare result to return to the Authenticator
1495 // TODO check again what the Authenticator makes with it; probably has the same
1496 // effect as addAccountExplicitly, but it's not well done
1497 final Intent intent
= new Intent();
1498 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, MainApp
.getAccountType());
1499 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1501 intent.putExtra(AccountManager.KEY_AUTHTOKEN, MainApp.getAccountType()); */
1502 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1503 if (isOAuth
|| isSaml
) {
1504 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1506 /// add user data to the new account; TODO probably can be done in the last parameter
1507 // addAccountExplicitly, or in KEY_USERDATA
1508 mAccountMgr
.setUserData(
1509 mAccount
, Constants
.KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion()
1511 mAccountMgr
.setUserData(
1512 mAccount
, Constants
.KEY_OC_BASE_URL
, mServerInfo
.mBaseUrl
1516 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
, "TRUE");
1517 } else if (isOAuth
) {
1518 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
, "TRUE");
1521 setAccountAuthenticatorResult(intent
.getExtras());
1522 setResult(RESULT_OK
, intent
);
1530 * Starts and activity to open the 'new account' page in the ownCloud web site
1532 * @param view 'Account register' button
1534 public void onRegisterClick(View view
) {
1535 Intent register
= new Intent(
1536 Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.welcome_link_url
))
1538 setResult(RESULT_CANCELED
);
1539 startActivity(register
);
1544 * Updates the content and visibility state of the icon and text associated
1545 * to the last check on the ownCloud server.
1547 * @param serverStatusText Resource identifier of the text to show.
1548 * @param serverStatusIcon Resource identifier of the icon to show.
1550 private void showServerStatus() {
1551 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1552 mServerStatusView
.setVisibility(View
.INVISIBLE
);
1555 mServerStatusView
.setText(mServerStatusText
);
1556 mServerStatusView
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1557 mServerStatusView
.setVisibility(View
.VISIBLE
);
1564 * Updates the content and visibility state of the icon and text associated
1565 * to the interactions with the OAuth authorization server.
1567 private void showAuthStatus() {
1568 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1569 mAuthStatusView
.setVisibility(View
.INVISIBLE
);
1572 mAuthStatusView
.setText(mAuthStatusText
);
1573 mAuthStatusView
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1574 mAuthStatusView
.setVisibility(View
.VISIBLE
);
1579 private void showRefreshButton (boolean show
) {
1581 mRefreshButton
.setVisibility(View
.VISIBLE
);
1583 mRefreshButton
.setVisibility(View
.GONE
);
1588 * Called when the refresh button in the input field for ownCloud host is clicked.
1590 * Performs a new check on the URL in the input field.
1592 * @param view Refresh 'button'
1594 public void onRefreshClick(View view
) {
1600 * Called when the eye icon in the password field is clicked.
1602 * Toggles the visibility of the password in the field.
1604 public void onViewPasswordClick() {
1605 int selectionStart
= mPasswordInput
.getSelectionStart();
1606 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1607 if (isPasswordVisible()) {
1612 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1617 * Called when the checkbox for OAuth authorization is clicked.
1619 * Hides or shows the input fields for user & password.
1621 * @param view 'View password' 'button'
1623 public void onCheckClick(View view
) {
1624 CheckBox oAuth2Check
= (CheckBox
)view
;
1625 if (oAuth2Check
.isChecked()) {
1626 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1628 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1630 updateAuthenticationPreFragmentVisibility();
1635 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1637 * Used to trigger the authentication check when the user presses 'enter' after writing the
1638 * password, or to throw the server test when the only field on screen is the URL input field.
1641 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1642 if (actionId
== EditorInfo
.IME_ACTION_DONE
&& inputField
!= null
&&
1643 inputField
.equals(mPasswordInput
)) {
1644 if (mOkButton
.isEnabled()) {
1645 mOkButton
.performClick();
1648 } else if (actionId
== EditorInfo
.IME_ACTION_NEXT
&& inputField
!= null
&&
1649 inputField
.equals(mHostUrlInput
)) {
1650 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1651 equals(mAuthTokenType
)) {
1655 return false
; // always return false to grant that the software keyboard is hidden anyway
1659 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1661 private int fuzz
= 75;
1667 public boolean onTouch(View view
, MotionEvent event
) {
1668 Drawable rightDrawable
= null
;
1669 if (view
instanceof TextView
) {
1670 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1671 if (drawables
.length
> 2) {
1672 rightDrawable
= drawables
[2];
1675 if (rightDrawable
!= null
) {
1676 final int x
= (int) event
.getX();
1677 final int y
= (int) event
.getY();
1678 final Rect bounds
= rightDrawable
.getBounds();
1679 if ( x
>= (view
.getRight() - bounds
.width() - fuzz
) &&
1680 x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
) &&
1681 y
>= (view
.getPaddingTop() - fuzz
) &&
1682 y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1684 return onDrawableTouch(event
);
1690 public abstract boolean onDrawableTouch(final MotionEvent event
);
1694 private void getRemoteUserNameOperation(String sessionCookie
, boolean followRedirects
) {
1696 Intent getUserNameIntent
= new Intent();
1697 getUserNameIntent
.setAction(OperationsService
.ACTION_GET_USER_NAME
);
1698 getUserNameIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
1699 getUserNameIntent
.putExtra(OperationsService
.EXTRA_COOKIE
, sessionCookie
);
1701 if (mOperationsServiceBinder
!= null
) {
1702 //Log_OC.wtf(TAG, "starting getRemoteUserNameOperation..." );
1703 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(getUserNameIntent
);
1709 public void onSsoFinished(String sessionCookie
) {
1710 if (sessionCookie
!= null
&& sessionCookie
.length() > 0) {
1711 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1712 mAuthToken
= sessionCookie
;
1713 getRemoteUserNameOperation(sessionCookie
, true
);
1714 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1715 if (fd
!= null
&& fd
instanceof SherlockDialogFragment
) {
1716 Dialog d
= ((SherlockDialogFragment
)fd
).getDialog();
1717 if (d
!= null
&& d
.isShowing()) {
1724 Log_OC
.d(TAG
, "SSO failed");
1730 public boolean onTouchEvent(MotionEvent event
) {
1731 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1732 equals(mAuthTokenType
) &&
1733 mHostUrlInput
.hasFocus() && event
.getAction() == MotionEvent
.ACTION_DOWN
) {
1736 return super.onTouchEvent(event
);
1741 * Show untrusted cert dialog
1743 public void showUntrustedCertDialog(
1744 X509Certificate x509Certificate
, SslError error
, SslErrorHandler handler
1746 // Show a dialog with the certificate info
1747 SslUntrustedCertDialog dialog
= null
;
1748 if (x509Certificate
== null
) {
1749 dialog
= SslUntrustedCertDialog
.newInstanceForEmptySslError(error
, handler
);
1751 dialog
= SslUntrustedCertDialog
.
1752 newInstanceForFullSslError(x509Certificate
, error
, handler
);
1754 FragmentManager fm
= getSupportFragmentManager();
1755 FragmentTransaction ft
= fm
.beginTransaction();
1756 ft
.addToBackStack(null
);
1757 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1762 * Show untrusted cert dialog
1764 private void showUntrustedCertDialog(RemoteOperationResult result
) {
1765 // Show a dialog with the certificate info
1766 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.
1767 newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1768 FragmentManager fm
= getSupportFragmentManager();
1769 FragmentTransaction ft
= fm
.beginTransaction();
1770 ft
.addToBackStack(null
);
1771 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1776 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1778 public void onSavedCertificate() {
1779 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1781 // if SAML dialog is not shown,
1782 // the SslDialog was shown due to an SSL error in the server check
1788 * Called from SslValidatorDialog when a new server certificate could not be saved
1789 * when the user requested it.
1792 public void onFailedSavingCertificate() {
1793 dismissDialog(SAML_DIALOG_TAG
);
1794 Toast
.makeText(this, R
.string
.ssl_validator_not_saved
, Toast
.LENGTH_LONG
).show();
1798 public void onCancelCertificate() {
1799 dismissDialog(SAML_DIALOG_TAG
);
1803 private void doOnResumeAndBound() {
1804 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1805 mOperationsServiceBinder
.addOperationListener(AuthenticatorActivity
.this, mHandler
);
1806 if (mWaitingForOpId
<= Integer
.MAX_VALUE
) {
1807 mOperationsServiceBinder
.dispatchResultIfFinished((int)mWaitingForOpId
, this);
1810 if (mPendingAutoCheck
) {
1816 private void dismissDialog(String dialogTag
){
1817 Fragment frag
= getSupportFragmentManager().findFragmentByTag(dialogTag
);
1818 if (frag
!= null
&& frag
instanceof SherlockDialogFragment
) {
1819 SherlockDialogFragment dialog
= (SherlockDialogFragment
) frag
;
1826 * Implements callback methods for service binding.
1828 private class OperationsServiceConnection
implements ServiceConnection
{
1831 public void onServiceConnected(ComponentName component
, IBinder service
) {
1832 if (component
.equals(
1833 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1835 //Log_OC.wtf(TAG, "Operations service connected");
1836 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
1838 doOnResumeAndBound();
1847 public void onServiceDisconnected(ComponentName component
) {
1848 if (component
.equals(
1849 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1851 Log_OC
.e(TAG
, "Operations service crashed");
1852 mOperationsServiceBinder
= null
;
1859 * Create and show dialog for request authentication to the user
1863 public void createAuthenticationDialog(WebView webView
, HttpAuthHandler handler
) {
1865 // Show a dialog with the certificate info
1866 CredentialsDialogFragment dialog
=
1867 CredentialsDialogFragment
.newInstanceForCredentials(webView
, handler
);
1868 FragmentManager fm
= getSupportFragmentManager();
1869 FragmentTransaction ft
= fm
.beginTransaction();
1870 ft
.addToBackStack(null
);
1871 dialog
.setCancelable(false
);
1872 dialog
.show(ft
, CREDENTIALS_DIALOG_TAG
);
1874 if (!mIsFirstAuthAttempt
) {
1876 getApplicationContext(),
1877 getText(R
.string
.saml_authentication_wrong_pass
),
1881 mIsFirstAuthAttempt
= false
;
1886 * For retrieving the clicking on authentication cancel button
1888 public void doNegativeAuthenticatioDialogClick(){
1889 mIsFirstAuthAttempt
= true
;