1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.authentication
;
21 import java
.io
.IOException
;
22 import java
.security
.cert
.X509Certificate
;
25 import android
.accounts
.Account
;
26 import android
.accounts
.AccountManager
;
27 import android
.accounts
.AuthenticatorException
;
28 import android
.accounts
.OperationCanceledException
;
29 import android
.app
.Dialog
;
30 import android
.content
.ComponentName
;
31 import android
.content
.Context
;
32 import android
.content
.Intent
;
33 import android
.content
.ServiceConnection
;
34 import android
.content
.SharedPreferences
;
35 import android
.graphics
.Rect
;
36 import android
.graphics
.drawable
.Drawable
;
37 import android
.net
.Uri
;
38 import android
.net
.http
.SslError
;
39 import android
.os
.Bundle
;
40 import android
.os
.Handler
;
41 import android
.os
.IBinder
;
42 import android
.preference
.PreferenceManager
;
43 import android
.support
.v4
.app
.Fragment
;
44 import android
.support
.v4
.app
.FragmentManager
;
45 import android
.support
.v4
.app
.FragmentTransaction
;
46 import android
.text
.Editable
;
47 import android
.text
.InputType
;
48 import android
.text
.TextWatcher
;
49 import android
.view
.KeyEvent
;
50 import android
.view
.MotionEvent
;
51 import android
.view
.View
;
52 import android
.view
.View
.OnFocusChangeListener
;
53 import android
.view
.View
.OnTouchListener
;
54 import android
.view
.Window
;
55 import android
.view
.inputmethod
.EditorInfo
;
56 import android
.webkit
.HttpAuthHandler
;
57 import android
.webkit
.SslErrorHandler
;
58 import android
.webkit
.WebView
;
59 import android
.widget
.Button
;
60 import android
.widget
.CheckBox
;
61 import android
.widget
.EditText
;
62 import android
.widget
.TextView
;
63 import android
.widget
.TextView
.OnEditorActionListener
;
64 import android
.widget
.Toast
;
66 import com
.actionbarsherlock
.app
.SherlockDialogFragment
;
67 import com
.owncloud
.android
.MainApp
;
68 import com
.owncloud
.android
.R
;
69 import com
.owncloud
.android
.authentication
.SsoWebViewClient
.SsoWebViewClientListener
;
70 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
71 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
72 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
73 import com
.owncloud
.android
.lib
.common
.accounts
.AccountTypeUtils
;
74 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.Constants
;
75 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
76 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
79 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
80 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
81 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
82 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
83 import com
.owncloud
.android
.lib
.resources
.users
.GetRemoteUserNameOperation
;
84 import com
.owncloud
.android
.operations
.DetectAuthenticationMethodOperation
.AuthenticationMethod
;
85 import com
.owncloud
.android
.operations
.GetServerInfoOperation
;
86 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
87 import com
.owncloud
.android
.services
.OperationsService
;
88 import com
.owncloud
.android
.services
.OperationsService
.OperationsServiceBinder
;
89 import com
.owncloud
.android
.ui
.dialog
.CredentialsDialogFragment
;
90 import com
.owncloud
.android
.ui
.dialog
.IndeterminateProgressDialog
;
91 import com
.owncloud
.android
.ui
.dialog
.SamlWebViewDialog
;
92 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
93 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
94 import com
.owncloud
.android
.utils
.DisplayUtils
;
97 * This Activity is used to add an ownCloud account to the App
99 * @author Bartek Przybylski
100 * @author David A. Velasco
103 public class AuthenticatorActivity
extends AccountAuthenticatorActivity
104 implements OnRemoteOperationListener
, OnFocusChangeListener
, OnEditorActionListener
,
105 SsoWebViewClientListener
, OnSslUntrustedCertListener
{
107 private static final String TAG
= AuthenticatorActivity
.class.getSimpleName();
109 public static final String EXTRA_ACTION
= "ACTION";
110 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
112 private static final String KEY_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
114 private static final String KEY_HOST_URL_TEXT
= "HOST_URL_TEXT";
115 private static final String KEY_OC_VERSION
= "OC_VERSION";
116 private static final String KEY_SERVER_VALID
= "SERVER_VALID";
117 private static final String KEY_SERVER_CHECKED
= "SERVER_CHECKED";
118 private static final String KEY_SERVER_STATUS_TEXT
= "SERVER_STATUS_TEXT";
119 private static final String KEY_SERVER_STATUS_ICON
= "SERVER_STATUS_ICON";
120 private static final String KEY_IS_SSL_CONN
= "IS_SSL_CONN";
121 private static final String KEY_PASSWORD_EXPOSED
= "PASSWORD_VISIBLE";
122 private static final String KEY_AUTH_STATUS_TEXT
= "AUTH_STATUS_TEXT";
123 private static final String KEY_AUTH_STATUS_ICON
= "AUTH_STATUS_ICON";
124 private static final String KEY_SERVER_AUTH_METHOD
= "SERVER_AUTH_METHOD";
125 private static final String KEY_WAITING_FOR_OP_ID
= "WAITING_FOR_OP_ID";
126 private static final String KEY_AUTH_TOKEN
= "AUTH_TOKEN";
128 private static final String AUTH_ON
= "on";
129 private static final String AUTH_OPTIONAL
= "optional";
131 public static final byte ACTION_CREATE
= 0;
132 public static final byte ACTION_UPDATE_TOKEN
= 1; // requested by the user
133 public static final byte ACTION_UPDATE_EXPIRED_TOKEN
= 2; // detected by the app
135 private static final String UNTRUSTED_CERT_DIALOG_TAG
= "UNTRUSTED_CERT_DIALOG";
136 private static final String SAML_DIALOG_TAG
= "SAML_DIALOG";
137 private static final String WAIT_DIALOG_TAG
= "WAIT_DIALOG";
138 private static final String CREDENTIALS_DIALOG_TAG
= "CREDENTIALS_DIALOG";
139 private static final String KEY_AUTH_IS_FIRST_ATTEMPT_TAG
= "KEY_AUTH_IS_FIRST_ATTEMPT";
142 /// parameters from EXTRAs in starter Intent
143 private byte mAction
;
144 private Account mAccount
;
145 private String mAuthTokenType
;
148 /// activity-level references / state
149 private final Handler mHandler
= new Handler();
150 private ServiceConnection mOperationsServiceConnection
= null
;
151 private OperationsServiceBinder mOperationsServiceBinder
= null
;
152 private AccountManager mAccountMgr
;
153 private Uri mNewCapturedUriFromOAuth2Redirection
;
156 /// Server PRE-Fragment elements
157 private EditText mHostUrlInput
;
158 private View mRefreshButton
;
159 private TextView mServerStatusView
;
161 private TextWatcher mHostUrlInputWatcher
;
162 private int mServerStatusText
= 0, mServerStatusIcon
= 0;
164 private boolean mServerIsChecked
= false
;
165 private boolean mServerIsValid
= false
;
166 private boolean mPendingAutoCheck
= false
;
168 private GetServerInfoOperation
.ServerInfo mServerInfo
=
169 new GetServerInfoOperation
.ServerInfo();
172 /// Authentication PRE-Fragment elements
173 private CheckBox mOAuth2Check
;
174 private TextView mOAuthAuthEndpointText
;
175 private TextView mOAuthTokenEndpointText
;
176 private EditText mUsernameInput
;
177 private EditText mPasswordInput
;
178 private View mOkButton
;
179 private TextView mAuthStatusView
;
181 private int mAuthStatusText
= 0, mAuthStatusIcon
= 0;
183 private String mAuthToken
= "";
185 private boolean mIsFirstAuthAttempt
;
188 /// Identifier of operation in progress which result shouldn't be lost
189 private long mWaitingForOpId
= Long
.MAX_VALUE
;
195 * IMPORTANT ENTRY POINT 1: activity is shown to the user
198 protected void onCreate(Bundle savedInstanceState
) {
199 //Log_OC.wtf(TAG, "onCreate init");
200 super.onCreate(savedInstanceState
);
201 getWindow().requestFeature(Window
.FEATURE_NO_TITLE
);
203 mIsFirstAuthAttempt
= true
;
205 // bind to Operations Service
206 mOperationsServiceConnection
= new OperationsServiceConnection();
207 if (!bindService(new Intent(this, OperationsService
.class),
208 mOperationsServiceConnection
,
209 Context
.BIND_AUTO_CREATE
)) {
211 R
.string
.error_cant_bind_to_operations_service
,
217 /// init activity state
218 mAccountMgr
= AccountManager
.get(this);
219 mNewCapturedUriFromOAuth2Redirection
= null
;
222 mAction
= getIntent().getByteExtra(EXTRA_ACTION
, ACTION_CREATE
);
223 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
224 if (savedInstanceState
== null
) {
227 mAuthTokenType
= savedInstanceState
.getString(KEY_AUTH_TOKEN_TYPE
);
228 mWaitingForOpId
= savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
);
229 mIsFirstAuthAttempt
= savedInstanceState
.getBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
);
234 /// load user interface
235 setContentView(R
.layout
.account_setup
);
237 /// initialize general UI elements
238 initOverallUi(savedInstanceState
);
240 mOkButton
= findViewById(R
.id
.buttonOK
);
242 /// initialize block to be moved to single Fragment to check server and get info about it
243 initServerPreFragment(savedInstanceState
);
245 /// initialize block to be moved to single Fragment to retrieve and validate credentials
246 initAuthorizationPreFragment(savedInstanceState
);
248 //Log_OC.wtf(TAG, "onCreate end");
251 private void initAuthTokenType() {
253 getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
254 if (mAuthTokenType
== null
) {
255 if (mAccount
!= null
) {
256 boolean oAuthRequired
=
257 (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
) != null
);
258 boolean samlWebSsoRequired
= (
259 mAccountMgr
.getUserData(
260 mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
263 mAuthTokenType
= chooseAuthTokenType(oAuthRequired
, samlWebSsoRequired
);
266 boolean oAuthSupported
= AUTH_ON
.equals(getString(R
.string
.auth_method_oauth2
));
267 boolean samlWebSsoSupported
=
268 AUTH_ON
.equals(getString(R
.string
.auth_method_saml_web_sso
));
269 mAuthTokenType
= chooseAuthTokenType(oAuthSupported
, samlWebSsoSupported
);
274 private String
chooseAuthTokenType(boolean oauth
, boolean saml
) {
276 return AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
278 return AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
280 return AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
286 * Configures elements in the user interface under direct control of the Activity.
288 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
290 private void initOverallUi(Bundle savedInstanceState
) {
292 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
293 boolean isWelcomeLinkVisible
= getResources().getBoolean(R
.bool
.show_welcome_link
);
295 String instructionsMessageText
= null
;
296 if (mAction
== ACTION_UPDATE_EXPIRED_TOKEN
) {
297 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
298 .equals(mAuthTokenType
)) {
299 instructionsMessageText
= getString(R
.string
.auth_expired_oauth_token_toast
);
301 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType())
302 .equals(mAuthTokenType
)) {
303 instructionsMessageText
= getString(R
.string
.auth_expired_saml_sso_token_toast
);
306 instructionsMessageText
= getString(R
.string
.auth_expired_basic_auth_toast
);
310 /// step 2 - set properties of UI elements (text, visibility, enabled...)
311 Button welcomeLink
= (Button
) findViewById(R
.id
.welcome_link
);
312 welcomeLink
.setVisibility(isWelcomeLinkVisible ? View
.VISIBLE
: View
.GONE
);
314 String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
316 TextView instructionsView
= (TextView
) findViewById(R
.id
.instructions_message
);
317 if (instructionsMessageText
!= null
) {
318 instructionsView
.setVisibility(View
.VISIBLE
);
319 instructionsView
.setText(instructionsMessageText
);
321 instructionsView
.setVisibility(View
.GONE
);
328 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
330 private void initServerPreFragment(Bundle savedInstanceState
) {
332 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
333 boolean isUrlInputAllowed
= getResources().getBoolean(R
.bool
.show_server_url_input
);
334 if (savedInstanceState
== null
) {
335 if (mAccount
!= null
) {
336 mServerInfo
.mBaseUrl
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_BASE_URL
);
337 // TODO do next in a setter for mBaseUrl
338 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
339 String ocVersion
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_VERSION
);
340 if (ocVersion
!= null
) {
341 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
344 mServerInfo
.mBaseUrl
= getString(R
.string
.server_url
).trim();
345 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
348 mServerStatusText
= savedInstanceState
.getInt(KEY_SERVER_STATUS_TEXT
);
349 mServerStatusIcon
= savedInstanceState
.getInt(KEY_SERVER_STATUS_ICON
);
351 mServerIsValid
= savedInstanceState
.getBoolean(KEY_SERVER_VALID
);
352 mServerIsChecked
= savedInstanceState
.getBoolean(KEY_SERVER_CHECKED
);
355 mServerInfo
.mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
356 mServerInfo
.mBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
357 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
358 if (ocVersion
!= null
) {
359 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
361 mServerInfo
.mAuthMethod
= AuthenticationMethod
.valueOf(
362 savedInstanceState
.getString(KEY_SERVER_AUTH_METHOD
));
366 /// step 2 - set properties of UI elements (text, visibility, enabled...)
367 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
368 // Convert IDN to Unicode
369 mHostUrlInput
.setText(DisplayUtils
.convertIdn(mServerInfo
.mBaseUrl
, false
));
370 if (mAction
!= ACTION_CREATE
) {
371 /// lock things that should not change
372 mHostUrlInput
.setEnabled(false
);
373 mHostUrlInput
.setFocusable(false
);
375 if (isUrlInputAllowed
) {
376 mRefreshButton
= findViewById(R
.id
.embeddedRefreshButton
);
378 findViewById(R
.id
.hostUrlFrame
).setVisibility(View
.GONE
);
379 mRefreshButton
= findViewById(R
.id
.centeredRefreshButton
);
381 showRefreshButton(mServerIsChecked
&& !mServerIsValid
&&
382 mWaitingForOpId
> Integer
.MAX_VALUE
);
383 mServerStatusView
= (TextView
) findViewById(R
.id
.server_status_text
);
386 /// step 3 - bind some listeners and options
387 mHostUrlInput
.setImeOptions(EditorInfo
.IME_ACTION_NEXT
);
388 mHostUrlInput
.setOnEditorActionListener(this);
390 /// step 4 - create listeners that will be bound at onResume
391 mHostUrlInputWatcher
= new TextWatcher() {
394 public void afterTextChanged(Editable s
) {
395 if (mOkButton
.isEnabled() &&
396 !mServerInfo
.mBaseUrl
.equals(
397 normalizeUrl(s
.toString(), mServerInfo
.mIsSslConn
))) {
398 mOkButton
.setEnabled(false
);
403 public void beforeTextChanged(CharSequence s
, int start
, int count
, int after
) {
407 public void onTextChanged(CharSequence s
, int start
, int before
, int count
) {
408 if (mAuthStatusIcon
!= 0) {
409 Log_OC
.d(TAG
, "onTextChanged: hiding authentication status");
418 // TODO find out if this is really necessary, or if it can done in a different way
419 findViewById(R
.id
.scroll
).setOnTouchListener(new OnTouchListener() {
421 public boolean onTouch(View view
, MotionEvent event
) {
422 if (event
.getAction() == MotionEvent
.ACTION_DOWN
) {
424 AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(
425 MainApp
.getAccountType()
426 ).equals(mAuthTokenType
) &&
427 mHostUrlInput
.hasFocus()
437 /// step 4 - mark automatic check to be started when OperationsService is ready
438 mPendingAutoCheck
= (savedInstanceState
== null
&&
439 (mAction
!= ACTION_CREATE
|| !isUrlInputAllowed
));
445 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
447 private void initAuthorizationPreFragment(Bundle savedInstanceState
) {
449 /// step 0 - get UI elements in layout
450 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
451 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
452 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
453 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
454 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
455 mAuthStatusView
= (TextView
) findViewById(R
.id
.auth_status_text
);
457 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
458 String presetUserName
= null
;
459 boolean isPasswordExposed
= false
;
460 if (savedInstanceState
== null
) {
461 if (mAccount
!= null
) {
462 presetUserName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
466 isPasswordExposed
= savedInstanceState
.getBoolean(KEY_PASSWORD_EXPOSED
, false
);
467 mAuthStatusText
= savedInstanceState
.getInt(KEY_AUTH_STATUS_TEXT
);
468 mAuthStatusIcon
= savedInstanceState
.getInt(KEY_AUTH_STATUS_ICON
);
469 mAuthToken
= savedInstanceState
.getString(KEY_AUTH_TOKEN
);
472 /// step 2 - set properties of UI elements (text, visibility, enabled...)
473 mOAuth2Check
.setChecked(
474 AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
475 .equals(mAuthTokenType
));
476 if (presetUserName
!= null
) {
477 mUsernameInput
.setText(presetUserName
);
479 if (mAction
!= ACTION_CREATE
) {
480 mUsernameInput
.setEnabled(false
);
481 mUsernameInput
.setFocusable(false
);
483 mPasswordInput
.setText(""); // clean password to avoid social hacking
484 if (isPasswordExposed
) {
487 updateAuthenticationPreFragmentVisibility();
489 mOkButton
.setEnabled(mServerIsValid
);
492 /// step 3 - bind listeners
493 // bindings for password input field
494 mPasswordInput
.setOnFocusChangeListener(this);
495 mPasswordInput
.setImeOptions(EditorInfo
.IME_ACTION_DONE
);
496 mPasswordInput
.setOnEditorActionListener(this);
497 mPasswordInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
499 public boolean onDrawableTouch(final MotionEvent event
) {
500 if (event
.getAction() == MotionEvent
.ACTION_UP
) {
501 AuthenticatorActivity
.this.onViewPasswordClick();
511 * Changes the visibility of input elements depending on
512 * the current authorization method.
514 private void updateAuthenticationPreFragmentVisibility () {
515 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
516 equals(mAuthTokenType
)) {
517 // SAML-based web Single Sign On
518 mOAuth2Check
.setVisibility(View
.GONE
);
519 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
520 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
521 mUsernameInput
.setVisibility(View
.GONE
);
522 mPasswordInput
.setVisibility(View
.GONE
);
525 if (mAction
== ACTION_CREATE
&&
526 AUTH_OPTIONAL
.equals(getString(R
.string
.auth_method_oauth2
))) {
527 mOAuth2Check
.setVisibility(View
.VISIBLE
);
529 mOAuth2Check
.setVisibility(View
.GONE
);
532 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
533 equals(mAuthTokenType
)) {
534 // OAuth 2 authorization
536 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
537 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
538 mUsernameInput
.setVisibility(View
.GONE
);
539 mPasswordInput
.setVisibility(View
.GONE
);
542 // basic HTTP authorization
543 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
544 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
545 mUsernameInput
.setVisibility(View
.VISIBLE
);
546 mPasswordInput
.setVisibility(View
.VISIBLE
);
554 * Saves relevant state before {@link #onPause()}
556 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag,
557 * intended to defer the processing of the redirection caught in
558 * {@link #onNewIntent(Intent)} until {@link #onResume()}
560 * See {@link #onSaveInstanceState(Bundle)}
563 protected void onSaveInstanceState(Bundle outState
) {
564 //Log_OC.wtf(TAG, "onSaveInstanceState init" );
565 super.onSaveInstanceState(outState
);
568 outState
.putString(KEY_AUTH_TOKEN_TYPE
, mAuthTokenType
);
569 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mWaitingForOpId
);
571 /// Server PRE-fragment state
572 outState
.putInt(KEY_SERVER_STATUS_TEXT
, mServerStatusText
);
573 outState
.putInt(KEY_SERVER_STATUS_ICON
, mServerStatusIcon
);
574 outState
.putBoolean(KEY_SERVER_CHECKED
, mServerIsChecked
);
575 outState
.putBoolean(KEY_SERVER_VALID
, mServerIsValid
);
576 outState
.putBoolean(KEY_IS_SSL_CONN
, mServerInfo
.mIsSslConn
);
577 outState
.putString(KEY_HOST_URL_TEXT
, mServerInfo
.mBaseUrl
);
578 if (mServerInfo
.mVersion
!= null
) {
579 outState
.putString(KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion());
581 outState
.putString(KEY_SERVER_AUTH_METHOD
, mServerInfo
.mAuthMethod
.name());
583 /// Authentication PRE-fragment state
584 outState
.putBoolean(KEY_PASSWORD_EXPOSED
, isPasswordVisible());
585 outState
.putInt(KEY_AUTH_STATUS_ICON
, mAuthStatusIcon
);
586 outState
.putInt(KEY_AUTH_STATUS_TEXT
, mAuthStatusText
);
587 outState
.putString(KEY_AUTH_TOKEN
, mAuthToken
);
590 outState
.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
, mIsFirstAuthAttempt
);
592 //Log_OC.wtf(TAG, "onSaveInstanceState end" );
597 * The redirection triggered by the OAuth authentication server as response to the
598 * GET AUTHORIZATION request is caught here.
600 * To make this possible, this activity needs to be qualified with android:launchMode =
601 * "singleTask" in the AndroidManifest.xml file.
604 protected void onNewIntent (Intent intent
) {
605 Log_OC
.d(TAG
, "onNewIntent()");
606 Uri data
= intent
.getData();
607 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
608 mNewCapturedUriFromOAuth2Redirection
= data
;
614 * The redirection triggered by the OAuth authentication server as response to the
615 * GET AUTHORIZATION, and deferred in {@link #onNewIntent(Intent)}, is processed here.
618 protected void onResume() {
619 //Log_OC.wtf(TAG, "onResume init" );
622 // bound here to avoid spurious changes triggered by Android on device rotations
623 mHostUrlInput
.setOnFocusChangeListener(this);
624 mHostUrlInput
.addTextChangedListener(mHostUrlInputWatcher
);
626 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
627 getOAuth2AccessTokenFromCapturedRedirection();
630 if (mOperationsServiceBinder
!= null
) {
631 doOnResumeAndBound();
634 //Log_OC.wtf(TAG, "onResume end" );
639 protected void onPause() {
640 //Log_OC.wtf(TAG, "onPause init" );
641 if (mOperationsServiceBinder
!= null
) {
642 //Log_OC.wtf(TAG, "unregistering to listen for operation callbacks" );
643 mOperationsServiceBinder
.removeOperationListener(this);
646 mHostUrlInput
.removeTextChangedListener(mHostUrlInputWatcher
);
647 mHostUrlInput
.setOnFocusChangeListener(null
);
650 //Log_OC.wtf(TAG, "onPause end" );
654 protected void onDestroy() {
656 mHostUrlInputWatcher
= null
;
658 if (mOperationsServiceConnection
!= null
) {
659 unbindService(mOperationsServiceConnection
);
660 mOperationsServiceBinder
= null
;
667 * Parses the redirection with the response to the GET AUTHORIZATION request to the
668 * oAuth server and requests for the access token (GET ACCESS TOKEN)
670 private void getOAuth2AccessTokenFromCapturedRedirection() {
671 /// Parse data from OAuth redirection
672 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
673 mNewCapturedUriFromOAuth2Redirection
= null
;
675 /// Showing the dialog with instructions for the user.
676 IndeterminateProgressDialog dialog
=
677 IndeterminateProgressDialog
.newInstance(R
.string
.auth_getting_authorization
, true
);
678 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
680 /// GET ACCESS TOKEN to the oAuth server
681 Intent getServerInfoIntent
= new Intent();
682 getServerInfoIntent
.setAction(OperationsService
.ACTION_OAUTH2_GET_ACCESS_TOKEN
);
684 getServerInfoIntent
.putExtra(
685 OperationsService
.EXTRA_SERVER_URL
,
686 mOAuthTokenEndpointText
.getText().toString().trim());
688 getServerInfoIntent
.putExtra(
689 OperationsService
.EXTRA_OAUTH2_QUERY_PARAMETERS
,
692 if (mOperationsServiceBinder
!= null
) {
693 //Log_OC.wtf(TAG, "getting access token..." );
694 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
701 * Handles the change of focus on the text inputs for the server URL and the password
703 public void onFocusChange(View view
, boolean hasFocus
) {
704 if (view
.getId() == R
.id
.hostUrlInput
) {
706 onUrlInputFocusLost((TextView
) view
);
709 showRefreshButton(false
);
712 } else if (view
.getId() == R
.id
.account_password
) {
713 onPasswordFocusChanged((TextView
) view
, hasFocus
);
719 * Handles changes in focus on the text input for the server URL.
721 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
722 * other field. The operation to check the existence of the server in the entered URL is
725 * When hasFocus: user 'comes back' to write again the server URL.
727 * @param hostInput TextView with the URL input field receiving the change of focus.
729 private void onUrlInputFocusLost(TextView hostInput
) {
730 if (!mServerInfo
.mBaseUrl
.equals(
731 normalizeUrl(mHostUrlInput
.getText().toString(), mServerInfo
.mIsSslConn
))) {
732 // check server again only if the user changed something in the field
735 mOkButton
.setEnabled(mServerIsValid
);
736 showRefreshButton(!mServerIsValid
);
741 private void checkOcServer() {
742 String uri
= mHostUrlInput
.getText().toString().trim();
743 mServerIsValid
= false
;
744 mServerIsChecked
= false
;
745 mOkButton
.setEnabled(false
);
746 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
747 showRefreshButton(false
);
749 if (uri
.length() != 0) {
750 // Handle internationalized domain names
751 uri
= DisplayUtils
.convertIdn(uri
, true
);
752 mServerStatusText
= R
.string
.auth_testing_connection
;
753 mServerStatusIcon
= R
.drawable
.progress_small
;
756 Intent getServerInfoIntent
= new Intent();
757 getServerInfoIntent
.setAction(OperationsService
.ACTION_GET_SERVER_INFO
);
758 getServerInfoIntent
.putExtra(
759 OperationsService
.EXTRA_SERVER_URL
,
760 normalizeUrlSuffix(uri
)
762 if (mOperationsServiceBinder
!= null
) {
763 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
765 Log_OC
.wtf(TAG
, "Server check tried with OperationService unbound!" );
769 mServerStatusText
= 0;
770 mServerStatusIcon
= 0;
777 * Handles changes in focus on the text input for the password (basic authorization).
779 * When (hasFocus), the button to toggle password visibility is shown.
781 * When (!hasFocus), the button is made invisible and the password is hidden.
783 * @param passwordInput TextView with the password input field receiving the change of focus.
784 * @param hasFocus 'True' if focus is received, 'false' if is lost
786 private void onPasswordFocusChanged(TextView passwordInput
, boolean hasFocus
) {
788 showViewPasswordButton();
791 hidePasswordButton();
796 private void showViewPasswordButton() {
797 int drawable
= R
.drawable
.ic_view
;
798 if (isPasswordVisible()) {
799 drawable
= R
.drawable
.ic_hide
;
801 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable
, 0);
804 private boolean isPasswordVisible() {
805 return ((mPasswordInput
.getInputType() & InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) ==
806 InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
809 private void hidePasswordButton() {
810 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
813 private void showPassword() {
814 mPasswordInput
.setInputType(
815 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
817 showViewPasswordButton();
820 private void hidePassword() {
821 mPasswordInput
.setInputType(
822 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
824 showViewPasswordButton();
828 * Checks the credentials of the user in the root of the ownCloud server
829 * before creating a new local account.
831 * For basic authorization, a check of existence of the root folder is
834 * For OAuth, starts the flow to get an access token; the credentials test
835 * is postponed until it is available.
837 * IMPORTANT ENTRY POINT 4
839 * @param view OK button
841 public void onOkClick(View view
) {
842 // this check should be unnecessary
843 if (mServerInfo
.mVersion
== null
||
844 !mServerInfo
.mVersion
.isVersionValid() ||
845 mServerInfo
.mBaseUrl
== null
||
846 mServerInfo
.mBaseUrl
.length() == 0) {
847 mServerStatusIcon
= R
.drawable
.common_error
;
848 mServerStatusText
= R
.string
.auth_wtf_reenter_URL
;
850 mOkButton
.setEnabled(false
);
851 //Log_OC.wtf(TAG, "The user was allowed to click 'connect' to an unchecked server!!");
855 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
856 equals(mAuthTokenType
)) {
858 startOauthorization();
859 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
860 equals(mAuthTokenType
)) {
862 startSamlBasedFederatedSingleSignOnAuthorization();
864 checkBasicAuthorization();
870 * Tests the credentials entered by the user performing a check of existence on
871 * the root folder of the ownCloud server.
873 private void checkBasicAuthorization() {
874 /// get basic credentials entered by user
875 String username
= mUsernameInput
.getText().toString();
876 String password
= mPasswordInput
.getText().toString();
878 /// be gentle with the user
879 IndeterminateProgressDialog dialog
=
880 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
881 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
883 /// validate credentials accessing the root folder
884 accessRootFolderRemoteOperation(username
, password
);
888 private void accessRootFolderRemoteOperation(String username
, String password
) {
889 // delete the account if the token has changed
890 if (mAction
== ACTION_UPDATE_TOKEN
|| mAction
== ACTION_UPDATE_EXPIRED_TOKEN
) {
891 // Remove the cookies in AccountManager
892 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_COOKIES
, null
);
895 Intent existenceCheckIntent
= new Intent();
896 existenceCheckIntent
.setAction(OperationsService
.ACTION_EXISTENCE_CHECK
);
897 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
898 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_REMOTE_PATH
, "/");
899 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_USERNAME
, username
);
900 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_PASSWORD
, password
);
901 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_AUTH_TOKEN
, mAuthToken
);
903 if (mOperationsServiceBinder
!= null
) {
904 //Log_OC.wtf(TAG, "starting existenceCheckRemoteOperation..." );
905 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(existenceCheckIntent
);
910 * Starts the OAuth 'grant type' flow to get an access token, with
911 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
913 private void startOauthorization() {
914 // be gentle with the user
915 mAuthStatusIcon
= R
.drawable
.progress_small
;
916 mAuthStatusText
= R
.string
.oauth_login_connection
;
919 // GET AUTHORIZATION request
920 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
921 Uri
.Builder uriBuilder
= uri
.buildUpon();
922 uriBuilder
.appendQueryParameter(
923 OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
)
925 uriBuilder
.appendQueryParameter(
926 OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
)
928 uriBuilder
.appendQueryParameter(
929 OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
)
931 uriBuilder
.appendQueryParameter(
932 OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
)
934 uri
= uriBuilder
.build();
935 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
936 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
942 * Starts the Web Single Sign On flow to get access to the root folder
945 private void startSamlBasedFederatedSingleSignOnAuthorization() {
946 // be gentle with the user
947 mAuthStatusIcon
= R
.drawable
.progress_small
;
948 mAuthStatusText
= R
.string
.auth_connecting_auth_server
;
950 IndeterminateProgressDialog dialog
=
951 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
952 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
954 /// validate credentials accessing the root folder
955 accessRootFolderRemoteOperation("", "");
960 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
962 * Dispatches the operation flow to the right method.
965 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
967 if (operation
instanceof GetServerInfoOperation
) {
968 if (operation
.hashCode() == mWaitingForOpId
) {
969 onGetServerInfoFinish(result
);
970 } // else nothing ; only the last check operation is considered;
971 // multiple can be started if the user amends a URL quickly
973 } else if (operation
instanceof OAuth2GetAccessToken
) {
974 onGetOAuthAccessTokenFinish(result
);
976 } else if (operation
instanceof ExistenceCheckRemoteOperation
) {
977 //Log_OC.wtf(TAG, "received detection response through callback" );
978 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
979 equals(mAuthTokenType
)) {
980 onSamlBasedFederatedSingleSignOnAuthorizationStart(result
);
983 onAuthorizationCheckFinish(result
);
985 } else if (operation
instanceof GetRemoteUserNameOperation
) {
986 onGetUserNameFinish(result
);
991 private void onGetUserNameFinish(RemoteOperationResult result
) {
992 mWaitingForOpId
= Long
.MAX_VALUE
;
993 if (result
.isSuccess()) {
994 boolean success
= false
;
995 String username
= (String
) result
.getData().get(0);
997 if ( mAction
== ACTION_CREATE
) {
998 mUsernameInput
.setText(username
);
999 success
= createAccount();
1002 if (!mUsernameInput
.getText().toString().equals(username
)) {
1003 // fail - not a new account, but an existing one; disallow
1004 result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_THE_SAME
);
1006 OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(
1007 new OwnCloudAccount(
1008 Uri.parse(mServerInfo.mBaseUrl),
1009 OwnCloudCredentialsFactory.newSamlSsoCredentials(mAuthToken))
1013 updateAuthStatusIconAndText(result
);
1015 Log_OC
.d(TAG
, result
.getLogMessage());
1025 updateStatusIconFailUserName();
1027 Log_OC
.e(TAG
, "Access to user name failed: " + result
.getLogMessage());
1032 private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperationResult result
) {
1033 mWaitingForOpId
= Long
.MAX_VALUE
;
1034 dismissDialog(WAIT_DIALOG_TAG
);
1036 if (result
.isIdPRedirection()) {
1037 String targetUrl
= mServerInfo
.mBaseUrl
1038 + AccountUtils
.getWebdavPath(mServerInfo
.mVersion
, mAuthTokenType
);
1041 SamlWebViewDialog dialog
= SamlWebViewDialog
.newInstance(targetUrl
, targetUrl
);
1042 dialog
.show(getSupportFragmentManager(), SAML_DIALOG_TAG
);
1044 mAuthStatusIcon
= 0;
1045 mAuthStatusText
= 0;
1048 mAuthStatusIcon
= R
.drawable
.common_error
;
1049 mAuthStatusText
= R
.string
.auth_unsupported_auth_method
;
1057 * Processes the result of the server check performed when the user finishes the enter of the
1060 * @param result Result of the check.
1062 private void onGetServerInfoFinish(RemoteOperationResult result
) {
1063 /// update activity state
1064 mServerIsChecked
= true
;
1065 mWaitingForOpId
= Long
.MAX_VALUE
;
1067 // update server status, but don't show it yet
1068 updateServerStatusIconAndText(result
);
1070 if (result
.isSuccess()) {
1072 // 1. connection succeeded, and we know if it's SSL or not
1073 // 2. server is installed
1074 // 3. we got the server version
1075 // 4. we got the authentication method required by the server
1076 mServerInfo
= (GetServerInfoOperation
.ServerInfo
) (result
.getData().get(0));
1078 if (!authSupported(mServerInfo
.mAuthMethod
)) {
1080 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1081 mServerIsValid
= false
;
1084 mServerIsValid
= true
;
1088 mServerIsValid
= false
;
1092 showRefreshButton(!mServerIsValid
);
1094 mOkButton
.setEnabled(mServerIsValid
);
1096 /// very special case (TODO: move to a common place for all the remote operations)
1097 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1098 showUntrustedCertDialog(result
);
1103 private boolean authSupported(AuthenticationMethod authMethod
) {
1104 String basic
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1105 String oAuth
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1106 String saml
= AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
1108 return (( mAuthTokenType
.equals(basic
) &&
1109 authMethod
.equals(AuthenticationMethod
.BASIC_HTTP_AUTH
) ) ||
1110 ( mAuthTokenType
.equals(oAuth
) &&
1111 authMethod
.equals(AuthenticationMethod
.BEARER_TOKEN
)) ||
1112 ( mAuthTokenType
.equals(saml
) &&
1113 authMethod
.equals(AuthenticationMethod
.SAML_WEB_SSO
))
1118 // TODO remove, if possible
1119 private String
normalizeUrl(String url
, boolean sslWhenUnprefixed
) {
1120 if (url
!= null
&& url
.length() > 0) {
1122 if (!url
.toLowerCase().startsWith("http://") &&
1123 !url
.toLowerCase().startsWith("https://")) {
1124 if (sslWhenUnprefixed
) {
1125 url
= "https://" + url
;
1127 url
= "http://" + url
;
1131 url
= normalizeUrlSuffix(url
);
1133 return (url
!= null ? url
: "");
1137 private String
normalizeUrlSuffix(String url
) {
1138 if (url
.endsWith("/")) {
1139 url
= url
.substring(0, url
.length() - 1);
1141 url
= trimUrlWebdav(url
);
1146 // TODO remove, if possible
1147 private String
trimUrlWebdav(String url
){
1148 if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_4_0
)){
1149 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_4_0
.length());
1150 } else if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_2_0
)){
1151 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_2_0
.length());
1152 } else if (url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_1_2
)){
1153 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_1_2
.length());
1155 return (url
!= null ? url
: "");
1160 * Chooses the right icon and text to show to the user for the received operation result.
1162 * @param result Result of a remote operation performed in this activity
1164 private void updateServerStatusIconAndText(RemoteOperationResult result
) {
1165 mServerStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1167 switch (result
.getCode()) {
1169 mServerStatusIcon
= android
.R
.drawable
.ic_secure
;
1170 mServerStatusText
= R
.string
.auth_secure_connection
;
1175 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1176 mServerStatusText
= R
.string
.auth_connection_established
;
1177 mServerStatusIcon
= R
.drawable
.ic_ok
;
1179 mServerStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1180 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1184 case NO_NETWORK_CONNECTION
:
1185 mServerStatusIcon
= R
.drawable
.no_network
;
1186 mServerStatusText
= R
.string
.auth_no_net_conn_title
;
1189 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1190 mServerStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1192 case BAD_OC_VERSION
:
1193 mServerStatusText
= R
.string
.auth_bad_oc_version_title
;
1195 case WRONG_CONNECTION
:
1196 mServerStatusText
= R
.string
.auth_wrong_connection_title
;
1199 mServerStatusText
= R
.string
.auth_timeout_title
;
1201 case INCORRECT_ADDRESS
:
1202 mServerStatusText
= R
.string
.auth_incorrect_address_title
;
1205 mServerStatusText
= R
.string
.auth_ssl_general_error_title
;
1208 mServerStatusText
= R
.string
.auth_unauthorized
;
1210 case HOST_NOT_AVAILABLE
:
1211 mServerStatusText
= R
.string
.auth_unknown_host_title
;
1213 case INSTANCE_NOT_CONFIGURED
:
1214 mServerStatusText
= R
.string
.auth_not_configured_title
;
1216 case FILE_NOT_FOUND
:
1217 mServerStatusText
= R
.string
.auth_incorrect_path_title
;
1220 mServerStatusText
= R
.string
.auth_oauth_error
;
1222 case OAUTH2_ERROR_ACCESS_DENIED
:
1223 mServerStatusText
= R
.string
.auth_oauth_error_access_denied
;
1225 case UNHANDLED_HTTP_CODE
:
1227 mServerStatusText
= R
.string
.auth_unknown_error_title
;
1229 case OK_REDIRECT_TO_NON_SECURE_CONNECTION
:
1230 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1231 mServerStatusText
= R
.string
.auth_redirect_non_secure_connection_title
;
1234 mServerStatusText
= 0;
1235 mServerStatusIcon
= 0;
1241 * Chooses the right icon and text to show to the user for the received operation result.
1243 * @param result Result of a remote operation performed in this activity
1245 private void updateAuthStatusIconAndText(RemoteOperationResult result
) {
1246 mAuthStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1248 switch (result
.getCode()) {
1250 mAuthStatusIcon
= android
.R
.drawable
.ic_secure
;
1251 mAuthStatusText
= R
.string
.auth_secure_connection
;
1256 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1257 mAuthStatusText
= R
.string
.auth_connection_established
;
1258 mAuthStatusIcon
= R
.drawable
.ic_ok
;
1260 mAuthStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1261 mAuthStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1265 case NO_NETWORK_CONNECTION
:
1266 mAuthStatusIcon
= R
.drawable
.no_network
;
1267 mAuthStatusText
= R
.string
.auth_no_net_conn_title
;
1270 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1271 mAuthStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1273 case BAD_OC_VERSION
:
1274 mAuthStatusText
= R
.string
.auth_bad_oc_version_title
;
1276 case WRONG_CONNECTION
:
1277 mAuthStatusText
= R
.string
.auth_wrong_connection_title
;
1280 mAuthStatusText
= R
.string
.auth_timeout_title
;
1282 case INCORRECT_ADDRESS
:
1283 mAuthStatusText
= R
.string
.auth_incorrect_address_title
;
1286 mAuthStatusText
= R
.string
.auth_ssl_general_error_title
;
1289 mAuthStatusText
= R
.string
.auth_unauthorized
;
1291 case HOST_NOT_AVAILABLE
:
1292 mAuthStatusText
= R
.string
.auth_unknown_host_title
;
1294 case INSTANCE_NOT_CONFIGURED
:
1295 mAuthStatusText
= R
.string
.auth_not_configured_title
;
1297 case FILE_NOT_FOUND
:
1298 mAuthStatusText
= R
.string
.auth_incorrect_path_title
;
1301 mAuthStatusText
= R
.string
.auth_oauth_error
;
1303 case OAUTH2_ERROR_ACCESS_DENIED
:
1304 mAuthStatusText
= R
.string
.auth_oauth_error_access_denied
;
1306 case ACCOUNT_NOT_NEW
:
1307 mAuthStatusText
= R
.string
.auth_account_not_new
;
1309 case ACCOUNT_NOT_THE_SAME
:
1310 mAuthStatusText
= R
.string
.auth_account_not_the_same
;
1312 case UNHANDLED_HTTP_CODE
:
1314 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
1317 mAuthStatusText
= 0;
1318 mAuthStatusIcon
= 0;
1323 private void updateStatusIconFailUserName(){
1324 mAuthStatusIcon
= R
.drawable
.common_error
;
1325 mAuthStatusText
= R
.string
.auth_fail_get_user_name
;
1328 private void updateServerStatusIconNoRegularAuth(){
1329 mServerStatusIcon
= R
.drawable
.common_error
;
1330 mServerStatusText
= R
.string
.auth_can_not_auth_against_server
;
1334 * Processes the result of the request for and access token send
1335 * to an OAuth authorization server.
1337 * @param result Result of the operation.
1339 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result
) {
1340 mWaitingForOpId
= Long
.MAX_VALUE
;
1341 dismissDialog(WAIT_DIALOG_TAG
);
1343 if (result
.isSuccess()) {
1344 /// be gentle with the user
1345 IndeterminateProgressDialog dialog
=
1346 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
1347 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
1349 /// time to test the retrieved access token on the ownCloud server
1350 @SuppressWarnings("unchecked")
1351 Map
<String
, String
> tokens
= (Map
<String
, String
>)(result
.getData().get(0));
1352 mAuthToken
= tokens
.get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
1353 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mAuthToken
);
1355 accessRootFolderRemoteOperation("", "");
1358 updateAuthStatusIconAndText(result
);
1360 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1366 * Processes the result of the access check performed to try the user credentials.
1368 * Creates a new account through the AccountManager.
1370 * @param result Result of the operation.
1372 private void onAuthorizationCheckFinish(RemoteOperationResult result
) {
1373 mWaitingForOpId
= Long
.MAX_VALUE
;
1374 dismissDialog(WAIT_DIALOG_TAG
);
1376 if (result
.isSuccess()) {
1377 Log_OC
.d(TAG
, "Successful access - time to save the account");
1379 boolean success
= false
;
1380 if (mAction
== ACTION_CREATE
) {
1381 success
= createAccount();
1392 } else if (result
.isServerFail() || result
.isException()) {
1393 /// server errors or exceptions in authorization take to requiring a new check of
1395 mServerIsChecked
= true
;
1396 mServerIsValid
= false
;
1397 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
1399 // update status icon and text
1400 updateServerStatusIconAndText(result
);
1402 mAuthStatusIcon
= 0;
1403 mAuthStatusText
= 0;
1406 // update input controls state
1407 showRefreshButton(true
);
1408 mOkButton
.setEnabled(false
);
1410 // very special case (TODO: move to a common place for all the remote operations)
1411 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1412 showUntrustedCertDialog(result
);
1415 } else { // authorization fail due to client side - probably wrong credentials
1416 updateAuthStatusIconAndText(result
);
1418 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1426 * Sets the proper response to get that the Account Authenticator that started this activity
1427 * saves a new authorization token for mAccount.
1429 private void updateToken() {
1430 Bundle response
= new Bundle();
1431 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1432 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
1434 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
1435 equals(mAuthTokenType
)) {
1436 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1437 // the next line is necessary, notifications are calling directly to the
1438 // AuthenticatorActivity to update, without AccountManager intervention
1439 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1441 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1442 equals(mAuthTokenType
)) {
1444 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1445 // the next line is necessary; by now, notifications are calling directly to the
1446 // AuthenticatorActivity to update, without AccountManager intervention
1447 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1450 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
1451 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
1453 setAccountAuthenticatorResult(response
);
1459 * Creates a new account through the Account Authenticator that started this activity.
1461 * This makes the account permanent.
1463 * TODO Decide how to name the OAuth accounts
1465 private boolean createAccount() {
1466 /// create and save new ownCloud account
1467 boolean isOAuth
= AccountTypeUtils
.
1468 getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
);
1469 boolean isSaml
= AccountTypeUtils
.
1470 getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
);
1472 Uri uri
= Uri
.parse(mServerInfo
.mBaseUrl
);
1473 String username
= mUsernameInput
.getText().toString().trim();
1475 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1477 String accountName
= com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.
1478 buildAccountName(uri
, username
);
1479 Account newAccount
= new Account(accountName
, MainApp
.getAccountType());
1480 if (AccountUtils
.exists(newAccount
, getApplicationContext())) {
1481 // fail - not a new account, but an existing one; disallow
1482 RemoteOperationResult result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_NEW
);
1483 updateAuthStatusIconAndText(result
);
1485 Log_OC
.d(TAG
, result
.getLogMessage());
1489 mAccount
= newAccount
;
1491 if (isOAuth
|| isSaml
) {
1492 // with external authorizations, the password is never input in the app
1493 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
);
1495 mAccountMgr
.addAccountExplicitly(
1496 mAccount
, mPasswordInput
.getText().toString(), null
1500 /// add the new account as default in preferences, if there is none already
1501 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1502 if (defaultAccount
== null
) {
1503 SharedPreferences
.Editor editor
= PreferenceManager
1504 .getDefaultSharedPreferences(this).edit();
1505 editor
.putString("select_oc_account", accountName
);
1509 /// prepare result to return to the Authenticator
1510 // TODO check again what the Authenticator makes with it; probably has the same
1511 // effect as addAccountExplicitly, but it's not well done
1512 final Intent intent
= new Intent();
1513 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, MainApp
.getAccountType());
1514 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1516 intent.putExtra(AccountManager.KEY_AUTHTOKEN, MainApp.getAccountType()); */
1517 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1518 if (isOAuth
|| isSaml
) {
1519 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1521 /// add user data to the new account; TODO probably can be done in the last parameter
1522 // addAccountExplicitly, or in KEY_USERDATA
1523 mAccountMgr
.setUserData(
1524 mAccount
, Constants
.KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion()
1526 mAccountMgr
.setUserData(
1527 mAccount
, Constants
.KEY_OC_BASE_URL
, mServerInfo
.mBaseUrl
1531 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
, "TRUE");
1532 } else if (isOAuth
) {
1533 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
, "TRUE");
1536 setAccountAuthenticatorResult(intent
.getExtras());
1537 setResult(RESULT_OK
, intent
);
1545 * Starts and activity to open the 'new account' page in the ownCloud web site
1547 * @param view 'Account register' button
1549 public void onRegisterClick(View view
) {
1550 Intent register
= new Intent(
1551 Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.welcome_link_url
))
1553 setResult(RESULT_CANCELED
);
1554 startActivity(register
);
1559 * Updates the content and visibility state of the icon and text associated
1560 * to the last check on the ownCloud server.
1562 private void showServerStatus() {
1563 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1564 mServerStatusView
.setVisibility(View
.INVISIBLE
);
1567 mServerStatusView
.setText(mServerStatusText
);
1568 mServerStatusView
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1569 mServerStatusView
.setVisibility(View
.VISIBLE
);
1576 * Updates the content and visibility state of the icon and text associated
1577 * to the interactions with the OAuth authorization server.
1579 private void showAuthStatus() {
1580 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1581 mAuthStatusView
.setVisibility(View
.INVISIBLE
);
1584 mAuthStatusView
.setText(mAuthStatusText
);
1585 mAuthStatusView
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1586 mAuthStatusView
.setVisibility(View
.VISIBLE
);
1591 private void showRefreshButton (boolean show
) {
1593 mRefreshButton
.setVisibility(View
.VISIBLE
);
1595 mRefreshButton
.setVisibility(View
.GONE
);
1600 * Called when the refresh button in the input field for ownCloud host is clicked.
1602 * Performs a new check on the URL in the input field.
1604 * @param view Refresh 'button'
1606 public void onRefreshClick(View view
) {
1612 * Called when the eye icon in the password field is clicked.
1614 * Toggles the visibility of the password in the field.
1616 public void onViewPasswordClick() {
1617 int selectionStart
= mPasswordInput
.getSelectionStart();
1618 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1619 if (isPasswordVisible()) {
1624 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1629 * Called when the checkbox for OAuth authorization is clicked.
1631 * Hides or shows the input fields for user & password.
1633 * @param view 'View password' 'button'
1635 public void onCheckClick(View view
) {
1636 CheckBox oAuth2Check
= (CheckBox
)view
;
1637 if (oAuth2Check
.isChecked()) {
1638 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1640 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1642 updateAuthenticationPreFragmentVisibility();
1647 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1649 * Used to trigger the authentication check when the user presses 'enter' after writing the
1650 * password, or to throw the server test when the only field on screen is the URL input field.
1653 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1654 if (actionId
== EditorInfo
.IME_ACTION_DONE
&& inputField
!= null
&&
1655 inputField
.equals(mPasswordInput
)) {
1656 if (mOkButton
.isEnabled()) {
1657 mOkButton
.performClick();
1660 } else if (actionId
== EditorInfo
.IME_ACTION_NEXT
&& inputField
!= null
&&
1661 inputField
.equals(mHostUrlInput
)) {
1662 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1663 equals(mAuthTokenType
)) {
1667 return false
; // always return false to grant that the software keyboard is hidden anyway
1671 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1673 private int fuzz
= 75;
1679 public boolean onTouch(View view
, MotionEvent event
) {
1680 Drawable rightDrawable
= null
;
1681 if (view
instanceof TextView
) {
1682 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1683 if (drawables
.length
> 2) {
1684 rightDrawable
= drawables
[2];
1687 if (rightDrawable
!= null
) {
1688 final int x
= (int) event
.getX();
1689 final int y
= (int) event
.getY();
1690 final Rect bounds
= rightDrawable
.getBounds();
1691 if ( x
>= (view
.getRight() - bounds
.width() - fuzz
) &&
1692 x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
) &&
1693 y
>= (view
.getPaddingTop() - fuzz
) &&
1694 y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1696 return onDrawableTouch(event
);
1702 public abstract boolean onDrawableTouch(final MotionEvent event
);
1706 private void getRemoteUserNameOperation(String sessionCookie
, boolean followRedirects
) {
1708 Intent getUserNameIntent
= new Intent();
1709 getUserNameIntent
.setAction(OperationsService
.ACTION_GET_USER_NAME
);
1710 getUserNameIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
1711 getUserNameIntent
.putExtra(OperationsService
.EXTRA_COOKIE
, sessionCookie
);
1713 if (mOperationsServiceBinder
!= null
) {
1714 //Log_OC.wtf(TAG, "starting getRemoteUserNameOperation..." );
1715 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getUserNameIntent
);
1721 public void onSsoFinished(String sessionCookie
) {
1722 if (sessionCookie
!= null
&& sessionCookie
.length() > 0) {
1723 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1724 mAuthToken
= sessionCookie
;
1725 getRemoteUserNameOperation(sessionCookie
, true
);
1726 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1727 if (fd
!= null
&& fd
instanceof SherlockDialogFragment
) {
1728 Dialog d
= ((SherlockDialogFragment
)fd
).getDialog();
1729 if (d
!= null
&& d
.isShowing()) {
1736 Log_OC
.d(TAG
, "SSO failed");
1742 public boolean onTouchEvent(MotionEvent event
) {
1743 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1744 equals(mAuthTokenType
) &&
1745 mHostUrlInput
.hasFocus() && event
.getAction() == MotionEvent
.ACTION_DOWN
) {
1748 return super.onTouchEvent(event
);
1753 * Show untrusted cert dialog
1755 public void showUntrustedCertDialog(
1756 X509Certificate x509Certificate
, SslError error
, SslErrorHandler handler
1758 // Show a dialog with the certificate info
1759 SslUntrustedCertDialog dialog
= null
;
1760 if (x509Certificate
== null
) {
1761 dialog
= SslUntrustedCertDialog
.newInstanceForEmptySslError(error
, handler
);
1763 dialog
= SslUntrustedCertDialog
.
1764 newInstanceForFullSslError(x509Certificate
, error
, handler
);
1766 FragmentManager fm
= getSupportFragmentManager();
1767 FragmentTransaction ft
= fm
.beginTransaction();
1768 ft
.addToBackStack(null
);
1769 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1774 * Show untrusted cert dialog
1776 private void showUntrustedCertDialog(RemoteOperationResult result
) {
1777 // Show a dialog with the certificate info
1778 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.
1779 newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1780 FragmentManager fm
= getSupportFragmentManager();
1781 FragmentTransaction ft
= fm
.beginTransaction();
1782 ft
.addToBackStack(null
);
1783 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1788 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1790 public void onSavedCertificate() {
1791 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1793 // if SAML dialog is not shown,
1794 // the SslDialog was shown due to an SSL error in the server check
1800 * Called from SslValidatorDialog when a new server certificate could not be saved
1801 * when the user requested it.
1804 public void onFailedSavingCertificate() {
1805 dismissDialog(SAML_DIALOG_TAG
);
1806 Toast
.makeText(this, R
.string
.ssl_validator_not_saved
, Toast
.LENGTH_LONG
).show();
1810 public void onCancelCertificate() {
1811 dismissDialog(SAML_DIALOG_TAG
);
1815 private void doOnResumeAndBound() {
1816 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1817 mOperationsServiceBinder
.addOperationListener(AuthenticatorActivity
.this, mHandler
);
1818 if (mWaitingForOpId
<= Integer
.MAX_VALUE
) {
1819 mOperationsServiceBinder
.dispatchResultIfFinished((int)mWaitingForOpId
, this);
1822 if (mPendingAutoCheck
) {
1828 private void dismissDialog(String dialogTag
){
1829 Fragment frag
= getSupportFragmentManager().findFragmentByTag(dialogTag
);
1830 if (frag
!= null
&& frag
instanceof SherlockDialogFragment
) {
1831 SherlockDialogFragment dialog
= (SherlockDialogFragment
) frag
;
1838 * Implements callback methods for service binding.
1840 private class OperationsServiceConnection
implements ServiceConnection
{
1843 public void onServiceConnected(ComponentName component
, IBinder service
) {
1844 if (component
.equals(
1845 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1847 //Log_OC.wtf(TAG, "Operations service connected");
1848 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
1850 doOnResumeAndBound();
1859 public void onServiceDisconnected(ComponentName component
) {
1860 if (component
.equals(
1861 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1863 Log_OC
.e(TAG
, "Operations service crashed");
1864 mOperationsServiceBinder
= null
;
1871 * Create and show dialog for request authentication to the user
1875 public void createAuthenticationDialog(WebView webView
, HttpAuthHandler handler
) {
1877 // Show a dialog with the certificate info
1878 CredentialsDialogFragment dialog
=
1879 CredentialsDialogFragment
.newInstanceForCredentials(webView
, handler
);
1880 FragmentManager fm
= getSupportFragmentManager();
1881 FragmentTransaction ft
= fm
.beginTransaction();
1882 ft
.addToBackStack(null
);
1883 dialog
.setCancelable(false
);
1884 dialog
.show(ft
, CREDENTIALS_DIALOG_TAG
);
1886 if (!mIsFirstAuthAttempt
) {
1888 getApplicationContext(),
1889 getText(R
.string
.saml_authentication_wrong_pass
),
1893 mIsFirstAuthAttempt
= false
;
1898 * For retrieving the clicking on authentication cancel button
1900 public void doNegativeAuthenticatioDialogClick(){
1901 mIsFirstAuthAttempt
= true
;