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
;
88 import com
.owncloud
.android
.utils
.DisplayUtils
;
91 * This Activity is used to add an ownCloud account to the App
93 * @author Bartek Przybylski
94 * @author David A. Velasco
97 public class AuthenticatorActivity
extends AccountAuthenticatorActivity
98 implements OnRemoteOperationListener
, OnFocusChangeListener
, OnEditorActionListener
,
99 SsoWebViewClientListener
, OnSslUntrustedCertListener
{
101 private static final String TAG
= AuthenticatorActivity
.class.getSimpleName();
103 public static final String EXTRA_ACTION
= "ACTION";
104 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
106 private static final String KEY_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
108 private static final String KEY_HOST_URL_TEXT
= "HOST_URL_TEXT";
109 private static final String KEY_OC_VERSION
= "OC_VERSION";
110 private static final String KEY_SERVER_VALID
= "SERVER_VALID";
111 private static final String KEY_SERVER_CHECKED
= "SERVER_CHECKED";
112 private static final String KEY_SERVER_STATUS_TEXT
= "SERVER_STATUS_TEXT";
113 private static final String KEY_SERVER_STATUS_ICON
= "SERVER_STATUS_ICON";
114 private static final String KEY_IS_SSL_CONN
= "IS_SSL_CONN";
115 private static final String KEY_PASSWORD_EXPOSED
= "PASSWORD_VISIBLE";
116 private static final String KEY_AUTH_STATUS_TEXT
= "AUTH_STATUS_TEXT";
117 private static final String KEY_AUTH_STATUS_ICON
= "AUTH_STATUS_ICON";
118 private static final String KEY_SERVER_AUTH_METHOD
= "SERVER_AUTH_METHOD";
119 private static final String KEY_WAITING_FOR_OP_ID
= "WAITING_FOR_OP_ID";
120 private static final String KEY_AUTH_TOKEN
= "AUTH_TOKEN";
122 private static final String AUTH_ON
= "on";
123 private static final String AUTH_OPTIONAL
= "optional";
125 public static final byte ACTION_CREATE
= 0;
126 public static final byte ACTION_UPDATE_TOKEN
= 1; // requested by the user
127 public static final byte ACTION_UPDATE_EXPIRED_TOKEN
= 2; // detected by the app
129 private static final String UNTRUSTED_CERT_DIALOG_TAG
= "UNTRUSTED_CERT_DIALOG";
130 private static final String SAML_DIALOG_TAG
= "SAML_DIALOG";
131 private static final String WAIT_DIALOG_TAG
= "WAIT_DIALOG";
132 private static final String CREDENTIALS_DIALOG_TAG
= "CREDENTIALS_DIALOG";
133 private static final String KEY_AUTH_IS_FIRST_ATTEMPT_TAG
= "KEY_AUTH_IS_FIRST_ATTEMPT";
136 /// parameters from EXTRAs in starter Intent
137 private byte mAction
;
138 private Account mAccount
;
139 private String mAuthTokenType
;
142 /// activity-level references / state
143 private final Handler mHandler
= new Handler();
144 private ServiceConnection mOperationsServiceConnection
= null
;
145 private OperationsServiceBinder mOperationsServiceBinder
= null
;
146 private AccountManager mAccountMgr
;
147 private Uri mNewCapturedUriFromOAuth2Redirection
;
150 /// Server PRE-Fragment elements
151 private EditText mHostUrlInput
;
152 private View mRefreshButton
;
153 private TextView mServerStatusView
;
155 private TextWatcher mHostUrlInputWatcher
;
156 private int mServerStatusText
= 0, mServerStatusIcon
= 0;
158 private boolean mServerIsChecked
= false
;
159 private boolean mServerIsValid
= false
;
160 private boolean mPendingAutoCheck
= false
;
162 private GetServerInfoOperation
.ServerInfo mServerInfo
=
163 new GetServerInfoOperation
.ServerInfo();
166 /// Authentication PRE-Fragment elements
167 private CheckBox mOAuth2Check
;
168 private TextView mOAuthAuthEndpointText
;
169 private TextView mOAuthTokenEndpointText
;
170 private EditText mUsernameInput
;
171 private EditText mPasswordInput
;
172 private View mOkButton
;
173 private TextView mAuthStatusView
;
175 private int mAuthStatusText
= 0, mAuthStatusIcon
= 0;
177 private String mAuthToken
= "";
179 private boolean mIsFirstAuthAttempt
;
182 /// Identifier of operation in progress which result shouldn't be lost
183 private long mWaitingForOpId
= Long
.MAX_VALUE
;
189 * IMPORTANT ENTRY POINT 1: activity is shown to the user
192 protected void onCreate(Bundle savedInstanceState
) {
193 //Log_OC.wtf(TAG, "onCreate init");
194 super.onCreate(savedInstanceState
);
195 getWindow().requestFeature(Window
.FEATURE_NO_TITLE
);
197 mIsFirstAuthAttempt
= true
;
199 // bind to Operations Service
200 mOperationsServiceConnection
= new OperationsServiceConnection();
201 if (!bindService(new Intent(this, OperationsService
.class),
202 mOperationsServiceConnection
,
203 Context
.BIND_AUTO_CREATE
)) {
205 R
.string
.error_cant_bind_to_operations_service
,
211 /// init activity state
212 mAccountMgr
= AccountManager
.get(this);
213 mNewCapturedUriFromOAuth2Redirection
= null
;
216 mAction
= getIntent().getByteExtra(EXTRA_ACTION
, ACTION_CREATE
);
217 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
218 if (savedInstanceState
== null
) {
221 mAuthTokenType
= savedInstanceState
.getString(KEY_AUTH_TOKEN_TYPE
);
222 mWaitingForOpId
= savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
);
223 mIsFirstAuthAttempt
= savedInstanceState
.getBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
);
226 /// load user interface
227 setContentView(R
.layout
.account_setup
);
229 /// initialize general UI elements
230 initOverallUi(savedInstanceState
);
232 mOkButton
= findViewById(R
.id
.buttonOK
);
234 /// initialize block to be moved to single Fragment to check server and get info about it
235 initServerPreFragment(savedInstanceState
);
237 /// initialize block to be moved to single Fragment to retrieve and validate credentials
238 initAuthorizationPreFragment(savedInstanceState
);
240 //Log_OC.wtf(TAG, "onCreate end");
243 private void initAuthTokenType() {
245 getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
246 if (mAuthTokenType
== null
) {
247 if (mAccount
!= null
) {
248 boolean oAuthRequired
=
249 (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
) != null
);
250 boolean samlWebSsoRequired
= (
251 mAccountMgr
.getUserData(
252 mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
255 mAuthTokenType
= chooseAuthTokenType(oAuthRequired
, samlWebSsoRequired
);
258 boolean oAuthSupported
= AUTH_ON
.equals(getString(R
.string
.auth_method_oauth2
));
259 boolean samlWebSsoSupported
=
260 AUTH_ON
.equals(getString(R
.string
.auth_method_saml_web_sso
));
261 mAuthTokenType
= chooseAuthTokenType(oAuthSupported
, samlWebSsoSupported
);
266 private String
chooseAuthTokenType(boolean oauth
, boolean saml
) {
268 return AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
270 return AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
272 return AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
278 * Configures elements in the user interface under direct control of the Activity.
280 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
282 private void initOverallUi(Bundle savedInstanceState
) {
284 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
285 boolean isWelcomeLinkVisible
= getResources().getBoolean(R
.bool
.show_welcome_link
);
287 String instructionsMessageText
= null
;
288 if (mAction
== ACTION_UPDATE_EXPIRED_TOKEN
) {
289 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
290 .equals(mAuthTokenType
)) {
291 instructionsMessageText
= getString(R
.string
.auth_expired_oauth_token_toast
);
293 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType())
294 .equals(mAuthTokenType
)) {
295 instructionsMessageText
= getString(R
.string
.auth_expired_saml_sso_token_toast
);
298 instructionsMessageText
= getString(R
.string
.auth_expired_basic_auth_toast
);
302 /// step 2 - set properties of UI elements (text, visibility, enabled...)
303 Button welcomeLink
= (Button
) findViewById(R
.id
.welcome_link
);
304 welcomeLink
.setVisibility(isWelcomeLinkVisible ? View
.VISIBLE
: View
.GONE
);
306 String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
308 TextView instructionsView
= (TextView
) findViewById(R
.id
.instructions_message
);
309 if (instructionsMessageText
!= null
) {
310 instructionsView
.setVisibility(View
.VISIBLE
);
311 instructionsView
.setText(instructionsMessageText
);
313 instructionsView
.setVisibility(View
.GONE
);
320 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
322 private void initServerPreFragment(Bundle savedInstanceState
) {
324 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
325 boolean isUrlInputAllowed
= getResources().getBoolean(R
.bool
.show_server_url_input
);
326 if (savedInstanceState
== null
) {
327 if (mAccount
!= null
) {
328 mServerInfo
.mBaseUrl
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_BASE_URL
);
329 // TODO do next in a setter for mBaseUrl
330 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
331 String ocVersion
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_VERSION
);
332 if (ocVersion
!= null
) {
333 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
336 mServerInfo
.mBaseUrl
= getString(R
.string
.server_url
).trim();
337 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
340 mServerStatusText
= savedInstanceState
.getInt(KEY_SERVER_STATUS_TEXT
);
341 mServerStatusIcon
= savedInstanceState
.getInt(KEY_SERVER_STATUS_ICON
);
343 mServerIsValid
= savedInstanceState
.getBoolean(KEY_SERVER_VALID
);
344 mServerIsChecked
= savedInstanceState
.getBoolean(KEY_SERVER_CHECKED
);
347 mServerInfo
.mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
348 mServerInfo
.mBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
349 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
350 if (ocVersion
!= null
) {
351 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
353 mServerInfo
.mAuthMethod
= AuthenticationMethod
.valueOf(
354 savedInstanceState
.getString(KEY_SERVER_AUTH_METHOD
));
358 /// step 2 - set properties of UI elements (text, visibility, enabled...)
359 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
360 // Convert IDN to Unicode
361 mHostUrlInput
.setText(DisplayUtils
.convertIdn(mServerInfo
.mBaseUrl
, false
));
362 if (mAction
!= ACTION_CREATE
) {
363 /// lock things that should not change
364 mHostUrlInput
.setEnabled(false
);
365 mHostUrlInput
.setFocusable(false
);
367 if (isUrlInputAllowed
) {
368 mRefreshButton
= findViewById(R
.id
.embeddedRefreshButton
);
370 findViewById(R
.id
.hostUrlFrame
).setVisibility(View
.GONE
);
371 mRefreshButton
= findViewById(R
.id
.centeredRefreshButton
);
373 showRefreshButton(mServerIsChecked
&& !mServerIsValid
&&
374 mWaitingForOpId
> Integer
.MAX_VALUE
);
375 mServerStatusView
= (TextView
) findViewById(R
.id
.server_status_text
);
378 /// step 3 - bind some listeners and options
379 mHostUrlInput
.setImeOptions(EditorInfo
.IME_ACTION_NEXT
);
380 mHostUrlInput
.setOnEditorActionListener(this);
382 /// step 4 - create listeners that will be bound at onResume
383 mHostUrlInputWatcher
= new TextWatcher() {
386 public void afterTextChanged(Editable s
) {
387 if (mOkButton
.isEnabled() &&
388 !mServerInfo
.mBaseUrl
.equals(
389 normalizeUrl(s
.toString(), mServerInfo
.mIsSslConn
))) {
390 mOkButton
.setEnabled(false
);
395 public void beforeTextChanged(CharSequence s
, int start
, int count
, int after
) {
399 public void onTextChanged(CharSequence s
, int start
, int before
, int count
) {
400 if (mAuthStatusIcon
!= 0) {
401 Log_OC
.d(TAG
, "onTextChanged: hiding authentication status");
410 // TODO find out if this is really necessary, or if it can done in a different way
411 findViewById(R
.id
.scroll
).setOnTouchListener(new OnTouchListener() {
413 public boolean onTouch(View view
, MotionEvent event
) {
414 if (event
.getAction() == MotionEvent
.ACTION_DOWN
) {
416 AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(
417 MainApp
.getAccountType()
418 ).equals(mAuthTokenType
) &&
419 mHostUrlInput
.hasFocus()
429 /// step 4 - mark automatic check to be started when OperationsService is ready
430 mPendingAutoCheck
= (savedInstanceState
== null
&&
431 (mAction
!= ACTION_CREATE
|| !isUrlInputAllowed
));
437 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
439 private void initAuthorizationPreFragment(Bundle savedInstanceState
) {
441 /// step 0 - get UI elements in layout
442 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
443 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
444 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
445 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
446 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
447 mAuthStatusView
= (TextView
) findViewById(R
.id
.auth_status_text
);
449 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
450 String presetUserName
= null
;
451 boolean isPasswordExposed
= false
;
452 if (savedInstanceState
== null
) {
453 if (mAccount
!= null
) {
454 presetUserName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
458 isPasswordExposed
= savedInstanceState
.getBoolean(KEY_PASSWORD_EXPOSED
, false
);
459 mAuthStatusText
= savedInstanceState
.getInt(KEY_AUTH_STATUS_TEXT
);
460 mAuthStatusIcon
= savedInstanceState
.getInt(KEY_AUTH_STATUS_ICON
);
461 mAuthToken
= savedInstanceState
.getString(KEY_AUTH_TOKEN
);
464 /// step 2 - set properties of UI elements (text, visibility, enabled...)
465 mOAuth2Check
.setChecked(
466 AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
467 .equals(mAuthTokenType
));
468 if (presetUserName
!= null
) {
469 mUsernameInput
.setText(presetUserName
);
471 if (mAction
!= ACTION_CREATE
) {
472 mUsernameInput
.setEnabled(false
);
473 mUsernameInput
.setFocusable(false
);
475 mPasswordInput
.setText(""); // clean password to avoid social hacking
476 if (isPasswordExposed
) {
479 updateAuthenticationPreFragmentVisibility();
481 mOkButton
.setEnabled(mServerIsValid
);
484 /// step 3 - bind listeners
485 // bindings for password input field
486 mPasswordInput
.setOnFocusChangeListener(this);
487 mPasswordInput
.setImeOptions(EditorInfo
.IME_ACTION_DONE
);
488 mPasswordInput
.setOnEditorActionListener(this);
489 mPasswordInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
491 public boolean onDrawableTouch(final MotionEvent event
) {
492 if (event
.getAction() == MotionEvent
.ACTION_UP
) {
493 AuthenticatorActivity
.this.onViewPasswordClick();
503 * Changes the visibility of input elements depending on
504 * the current authorization method.
506 private void updateAuthenticationPreFragmentVisibility () {
507 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
508 equals(mAuthTokenType
)) {
509 // SAML-based web Single Sign On
510 mOAuth2Check
.setVisibility(View
.GONE
);
511 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
512 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
513 mUsernameInput
.setVisibility(View
.GONE
);
514 mPasswordInput
.setVisibility(View
.GONE
);
517 if (mAction
== ACTION_CREATE
&&
518 AUTH_OPTIONAL
.equals(getString(R
.string
.auth_method_oauth2
))) {
519 mOAuth2Check
.setVisibility(View
.VISIBLE
);
521 mOAuth2Check
.setVisibility(View
.GONE
);
524 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
525 equals(mAuthTokenType
)) {
526 // OAuth 2 authorization
528 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
529 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
530 mUsernameInput
.setVisibility(View
.GONE
);
531 mPasswordInput
.setVisibility(View
.GONE
);
534 // basic HTTP authorization
535 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
536 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
537 mUsernameInput
.setVisibility(View
.VISIBLE
);
538 mPasswordInput
.setVisibility(View
.VISIBLE
);
546 * Saves relevant state before {@link #onPause()}
548 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag,
549 * intended to defer the processing of the redirection caught in
550 * {@link #onNewIntent(Intent)} until {@link #onResume()}
552 * See {@link #loadSavedInstanceState(Bundle)}
555 protected void onSaveInstanceState(Bundle outState
) {
556 //Log_OC.wtf(TAG, "onSaveInstanceState init" );
557 super.onSaveInstanceState(outState
);
560 outState
.putString(KEY_AUTH_TOKEN_TYPE
, mAuthTokenType
);
561 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mWaitingForOpId
);
563 /// Server PRE-fragment state
564 outState
.putInt(KEY_SERVER_STATUS_TEXT
, mServerStatusText
);
565 outState
.putInt(KEY_SERVER_STATUS_ICON
, mServerStatusIcon
);
566 outState
.putBoolean(KEY_SERVER_CHECKED
, mServerIsChecked
);
567 outState
.putBoolean(KEY_SERVER_VALID
, mServerIsValid
);
568 outState
.putBoolean(KEY_IS_SSL_CONN
, mServerInfo
.mIsSslConn
);
569 outState
.putString(KEY_HOST_URL_TEXT
, mServerInfo
.mBaseUrl
);
570 if (mServerInfo
.mVersion
!= null
) {
571 outState
.putString(KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion());
573 outState
.putString(KEY_SERVER_AUTH_METHOD
, mServerInfo
.mAuthMethod
.name());
575 /// Authentication PRE-fragment state
576 outState
.putBoolean(KEY_PASSWORD_EXPOSED
, isPasswordVisible());
577 outState
.putInt(KEY_AUTH_STATUS_ICON
, mAuthStatusIcon
);
578 outState
.putInt(KEY_AUTH_STATUS_TEXT
, mAuthStatusText
);
579 outState
.putString(KEY_AUTH_TOKEN
, mAuthToken
);
582 outState
.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
, mIsFirstAuthAttempt
);
584 //Log_OC.wtf(TAG, "onSaveInstanceState end" );
589 * The redirection triggered by the OAuth authentication server as response to the
590 * GET AUTHORIZATION request is caught here.
592 * To make this possible, this activity needs to be qualified with android:launchMode =
593 * "singleTask" in the AndroidManifest.xml file.
596 protected void onNewIntent (Intent intent
) {
597 Log_OC
.d(TAG
, "onNewIntent()");
598 Uri data
= intent
.getData();
599 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
600 mNewCapturedUriFromOAuth2Redirection
= data
;
606 * The redirection triggered by the OAuth authentication server as response to the
607 * GET AUTHORIZATION, and deferred in {@link #onNewIntent(Intent)}, is processed here.
610 protected void onResume() {
611 //Log_OC.wtf(TAG, "onResume init" );
614 // bound here to avoid spurious changes triggered by Android on device rotations
615 mHostUrlInput
.setOnFocusChangeListener(this);
616 mHostUrlInput
.addTextChangedListener(mHostUrlInputWatcher
);
618 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
619 getOAuth2AccessTokenFromCapturedRedirection();
622 if (mOperationsServiceBinder
!= null
) {
623 doOnResumeAndBound();
626 //Log_OC.wtf(TAG, "onResume end" );
631 protected void onPause() {
632 //Log_OC.wtf(TAG, "onPause init" );
633 if (mOperationsServiceBinder
!= null
) {
634 //Log_OC.wtf(TAG, "unregistering to listen for operation callbacks" );
635 mOperationsServiceBinder
.removeOperationListener(this);
638 mHostUrlInput
.removeTextChangedListener(mHostUrlInputWatcher
);
639 mHostUrlInput
.setOnFocusChangeListener(null
);
642 //Log_OC.wtf(TAG, "onPause end" );
646 protected void onDestroy() {
648 mHostUrlInputWatcher
= null
;
650 if (mOperationsServiceConnection
!= null
) {
651 unbindService(mOperationsServiceConnection
);
652 mOperationsServiceBinder
= null
;
659 * Parses the redirection with the response to the GET AUTHORIZATION request to the
660 * oAuth server and requests for the access token (GET ACCESS TOKEN)
662 private void getOAuth2AccessTokenFromCapturedRedirection() {
663 /// Parse data from OAuth redirection
664 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
665 mNewCapturedUriFromOAuth2Redirection
= null
;
667 /// Showing the dialog with instructions for the user.
668 IndeterminateProgressDialog dialog
=
669 IndeterminateProgressDialog
.newInstance(R
.string
.auth_getting_authorization
, true
);
670 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
672 /// GET ACCESS TOKEN to the oAuth server
673 Intent getServerInfoIntent
= new Intent();
674 getServerInfoIntent
.setAction(OperationsService
.ACTION_OAUTH2_GET_ACCESS_TOKEN
);
676 getServerInfoIntent
.putExtra(
677 OperationsService
.EXTRA_SERVER_URL
,
678 mOAuthTokenEndpointText
.getText().toString().trim());
680 getServerInfoIntent
.putExtra(
681 OperationsService
.EXTRA_OAUTH2_QUERY_PARAMETERS
,
684 if (mOperationsServiceBinder
!= null
) {
685 //Log_OC.wtf(TAG, "getting access token..." );
686 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
693 * Handles the change of focus on the text inputs for the server URL and the password
695 public void onFocusChange(View view
, boolean hasFocus
) {
696 if (view
.getId() == R
.id
.hostUrlInput
) {
698 onUrlInputFocusLost((TextView
) view
);
701 showRefreshButton(false
);
704 } else if (view
.getId() == R
.id
.account_password
) {
705 onPasswordFocusChanged((TextView
) view
, hasFocus
);
711 * Handles changes in focus on the text input for the server URL.
713 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
714 * other field. The operation to check the existence of the server in the entered URL is
717 * When hasFocus: user 'comes back' to write again the server URL.
719 * @param hostInput TextView with the URL input field receiving the change of focus.
721 private void onUrlInputFocusLost(TextView hostInput
) {
722 if (!mServerInfo
.mBaseUrl
.equals(
723 normalizeUrl(mHostUrlInput
.getText().toString(), mServerInfo
.mIsSslConn
))) {
724 // check server again only if the user changed something in the field
727 mOkButton
.setEnabled(mServerIsValid
);
728 showRefreshButton(!mServerIsValid
);
733 private void checkOcServer() {
734 String uri
= mHostUrlInput
.getText().toString().trim();
735 mServerIsValid
= false
;
736 mServerIsChecked
= false
;
737 mOkButton
.setEnabled(false
);
738 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
739 showRefreshButton(false
);
741 if (uri
.length() != 0) {
742 // Handle internationalized domain names
743 uri
= DisplayUtils
.convertIdn(uri
, true
);
744 mServerStatusText
= R
.string
.auth_testing_connection
;
745 mServerStatusIcon
= R
.drawable
.progress_small
;
748 Intent getServerInfoIntent
= new Intent();
749 getServerInfoIntent
.setAction(OperationsService
.ACTION_GET_SERVER_INFO
);
750 getServerInfoIntent
.putExtra(
751 OperationsService
.EXTRA_SERVER_URL
,
752 normalizeUrlSuffix(uri
)
754 if (mOperationsServiceBinder
!= null
) {
755 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
757 Log_OC
.wtf(TAG
, "Server check tried with OperationService unbound!" );
761 mServerStatusText
= 0;
762 mServerStatusIcon
= 0;
769 * Handles changes in focus on the text input for the password (basic authorization).
771 * When (hasFocus), the button to toggle password visibility is shown.
773 * When (!hasFocus), the button is made invisible and the password is hidden.
775 * @param passwordInput TextView with the password input field receiving the change of focus.
776 * @param hasFocus 'True' if focus is received, 'false' if is lost
778 private void onPasswordFocusChanged(TextView passwordInput
, boolean hasFocus
) {
780 showViewPasswordButton();
783 hidePasswordButton();
788 private void showViewPasswordButton() {
789 int drawable
= R
.drawable
.ic_view
;
790 if (isPasswordVisible()) {
791 drawable
= R
.drawable
.ic_hide
;
793 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable
, 0);
796 private boolean isPasswordVisible() {
797 return ((mPasswordInput
.getInputType() & InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) ==
798 InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
801 private void hidePasswordButton() {
802 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
805 private void showPassword() {
806 mPasswordInput
.setInputType(
807 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
809 showViewPasswordButton();
812 private void hidePassword() {
813 mPasswordInput
.setInputType(
814 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
816 showViewPasswordButton();
820 * Checks the credentials of the user in the root of the ownCloud server
821 * before creating a new local account.
823 * For basic authorization, a check of existence of the root folder is
826 * For OAuth, starts the flow to get an access token; the credentials test
827 * is postponed until it is available.
829 * IMPORTANT ENTRY POINT 4
831 * @param view OK button
833 public void onOkClick(View view
) {
834 // this check should be unnecessary
835 if (mServerInfo
.mVersion
== null
||
836 !mServerInfo
.mVersion
.isVersionValid() ||
837 mServerInfo
.mBaseUrl
== null
||
838 mServerInfo
.mBaseUrl
.length() == 0) {
839 mServerStatusIcon
= R
.drawable
.common_error
;
840 mServerStatusText
= R
.string
.auth_wtf_reenter_URL
;
842 mOkButton
.setEnabled(false
);
843 //Log_OC.wtf(TAG, "The user was allowed to click 'connect' to an unchecked server!!");
847 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
848 equals(mAuthTokenType
)) {
850 startOauthorization();
851 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
852 equals(mAuthTokenType
)) {
854 startSamlBasedFederatedSingleSignOnAuthorization();
856 checkBasicAuthorization();
862 * Tests the credentials entered by the user performing a check of existence on
863 * the root folder of the ownCloud server.
865 private void checkBasicAuthorization() {
866 /// get basic credentials entered by user
867 String username
= mUsernameInput
.getText().toString();
868 String password
= mPasswordInput
.getText().toString();
870 /// be gentle with the user
871 IndeterminateProgressDialog dialog
=
872 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
873 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
875 /// validate credentials accessing the root folder
876 accessRootFolderRemoteOperation(username
, password
);
880 private void accessRootFolderRemoteOperation(String username
, String password
) {
881 Intent existenceCheckIntent
= new Intent();
882 existenceCheckIntent
.setAction(OperationsService
.ACTION_EXISTENCE_CHECK
);
883 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
884 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_REMOTE_PATH
, "/");
885 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_USERNAME
, username
);
886 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_PASSWORD
, password
);
887 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_AUTH_TOKEN
, mAuthToken
);
889 if (mOperationsServiceBinder
!= null
) {
890 //Log_OC.wtf(TAG, "starting existenceCheckRemoteOperation..." );
891 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(existenceCheckIntent
);
896 * Starts the OAuth 'grant type' flow to get an access token, with
897 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
899 private void startOauthorization() {
900 // be gentle with the user
901 mAuthStatusIcon
= R
.drawable
.progress_small
;
902 mAuthStatusText
= R
.string
.oauth_login_connection
;
905 // GET AUTHORIZATION request
906 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
907 Uri
.Builder uriBuilder
= uri
.buildUpon();
908 uriBuilder
.appendQueryParameter(
909 OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
)
911 uriBuilder
.appendQueryParameter(
912 OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
)
914 uriBuilder
.appendQueryParameter(
915 OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
)
917 uriBuilder
.appendQueryParameter(
918 OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
)
920 uri
= uriBuilder
.build();
921 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
922 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
928 * Starts the Web Single Sign On flow to get access to the root folder
931 private void startSamlBasedFederatedSingleSignOnAuthorization() {
932 // be gentle with the user
933 mAuthStatusIcon
= R
.drawable
.progress_small
;
934 mAuthStatusText
= R
.string
.auth_connecting_auth_server
;
936 IndeterminateProgressDialog dialog
=
937 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
938 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
940 /// validate credentials accessing the root folder
941 accessRootFolderRemoteOperation("", "");
946 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
948 * Dispatches the operation flow to the right method.
951 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
953 if (operation
instanceof GetServerInfoOperation
) {
954 if (operation
.hashCode() == mWaitingForOpId
) {
955 onGetServerInfoFinish(result
);
956 } // else nothing ; only the last check operation is considered;
957 // multiple can be started if the user amends a URL quickly
959 } else if (operation
instanceof OAuth2GetAccessToken
) {
960 onGetOAuthAccessTokenFinish(result
);
962 } else if (operation
instanceof ExistenceCheckRemoteOperation
) {
963 //Log_OC.wtf(TAG, "received detection response through callback" );
964 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
965 equals(mAuthTokenType
)) {
966 onSamlBasedFederatedSingleSignOnAuthorizationStart(result
);
969 onAuthorizationCheckFinish(result
);
971 } else if (operation
instanceof GetRemoteUserNameOperation
) {
972 onGetUserNameFinish(result
);
977 private void onGetUserNameFinish(RemoteOperationResult result
) {
978 mWaitingForOpId
= Long
.MAX_VALUE
;
979 if (result
.isSuccess()) {
980 boolean success
= false
;
981 String username
= (String
) result
.getData().get(0);
983 if ( mAction
== ACTION_CREATE
) {
984 mUsernameInput
.setText(username
);
985 success
= createAccount();
988 if (!mUsernameInput
.getText().toString().equals(username
)) {
989 // fail - not a new account, but an existing one; disallow
990 result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_THE_SAME
);
992 OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(
994 Uri.parse(mServerInfo.mBaseUrl),
995 OwnCloudCredentialsFactory.newSamlSsoCredentials(mAuthToken))
999 updateAuthStatusIconAndText(result
);
1001 Log_OC
.d(TAG
, result
.getLogMessage());
1011 updateStatusIconFailUserName();
1013 Log_OC
.e(TAG
, "Access to user name failed: " + result
.getLogMessage());
1018 private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperationResult result
) {
1019 mWaitingForOpId
= Long
.MAX_VALUE
;
1020 dismissDialog(WAIT_DIALOG_TAG
);
1022 if (result
.isIdPRedirection()) {
1023 String url
= result
.getRedirectedLocation();
1024 String targetUrl
= mServerInfo
.mBaseUrl
1025 + AccountUtils
.getWebdavPath(mServerInfo
.mVersion
, mAuthTokenType
);
1028 SamlWebViewDialog dialog
= SamlWebViewDialog
.newInstance(url
, targetUrl
);
1029 dialog
.show(getSupportFragmentManager(), SAML_DIALOG_TAG
);
1031 mAuthStatusIcon
= 0;
1032 mAuthStatusText
= 0;
1035 mAuthStatusIcon
= R
.drawable
.common_error
;
1036 mAuthStatusText
= R
.string
.auth_unsupported_auth_method
;
1044 * Processes the result of the server check performed when the user finishes the enter of the
1047 * @param operation Server check performed.
1048 * @param result Result of the check.
1050 private void onGetServerInfoFinish(RemoteOperationResult result
) {
1051 /// update activity state
1052 mServerIsChecked
= true
;
1053 mWaitingForOpId
= Long
.MAX_VALUE
;
1055 // update server status, but don't show it yet
1056 updateServerStatusIconAndText(result
);
1058 if (result
.isSuccess()) {
1060 // 1. connection succeeded, and we know if it's SSL or not
1061 // 2. server is installed
1062 // 3. we got the server version
1063 // 4. we got the authentication method required by the server
1064 mServerInfo
= (GetServerInfoOperation
.ServerInfo
) (result
.getData().get(0));
1066 if (!authSupported(mServerInfo
.mAuthMethod
)) {
1068 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1069 mServerIsValid
= false
;
1072 mServerIsValid
= true
;
1076 mServerIsValid
= false
;
1080 showRefreshButton(!mServerIsValid
);
1082 mOkButton
.setEnabled(mServerIsValid
);
1084 /// very special case (TODO: move to a common place for all the remote operations)
1085 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1086 showUntrustedCertDialog(result
);
1091 private boolean authSupported(AuthenticationMethod authMethod
) {
1092 String basic
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1093 String oAuth
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1094 String saml
= AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
1096 return (( mAuthTokenType
.equals(basic
) &&
1097 authMethod
.equals(AuthenticationMethod
.BASIC_HTTP_AUTH
) ) ||
1098 ( mAuthTokenType
.equals(oAuth
) &&
1099 authMethod
.equals(AuthenticationMethod
.BEARER_TOKEN
)) ||
1100 ( mAuthTokenType
.equals(saml
) &&
1101 authMethod
.equals(AuthenticationMethod
.SAML_WEB_SSO
))
1106 // TODO remove, if possible
1107 private String
normalizeUrl(String url
, boolean sslWhenUnprefixed
) {
1108 if (url
!= null
&& url
.length() > 0) {
1110 if (!url
.toLowerCase().startsWith("http://") &&
1111 !url
.toLowerCase().startsWith("https://")) {
1112 if (sslWhenUnprefixed
) {
1113 url
= "https://" + url
;
1115 url
= "http://" + url
;
1119 url
= normalizeUrlSuffix(url
);
1121 return (url
!= null ? url
: "");
1125 private String
normalizeUrlSuffix(String url
) {
1126 if (url
.endsWith("/")) {
1127 url
= url
.substring(0, url
.length() - 1);
1129 url
= trimUrlWebdav(url
);
1134 // TODO remove, if possible
1135 private String
trimUrlWebdav(String url
){
1136 if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_4_0
)){
1137 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_4_0
.length());
1138 } else if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_2_0
)){
1139 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_2_0
.length());
1140 } else if (url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_1_2
)){
1141 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_1_2
.length());
1143 return (url
!= null ? url
: "");
1148 * Chooses the right icon and text to show to the user for the received operation result.
1150 * @param result Result of a remote operation performed in this activity
1152 private void updateServerStatusIconAndText(RemoteOperationResult result
) {
1153 mServerStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1155 switch (result
.getCode()) {
1157 mServerStatusIcon
= android
.R
.drawable
.ic_secure
;
1158 mServerStatusText
= R
.string
.auth_secure_connection
;
1163 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1164 mServerStatusText
= R
.string
.auth_connection_established
;
1165 mServerStatusIcon
= R
.drawable
.ic_ok
;
1167 mServerStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1168 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1172 case NO_NETWORK_CONNECTION
:
1173 mServerStatusIcon
= R
.drawable
.no_network
;
1174 mServerStatusText
= R
.string
.auth_no_net_conn_title
;
1177 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1178 mServerStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1180 case BAD_OC_VERSION
:
1181 mServerStatusText
= R
.string
.auth_bad_oc_version_title
;
1183 case WRONG_CONNECTION
:
1184 mServerStatusText
= R
.string
.auth_wrong_connection_title
;
1187 mServerStatusText
= R
.string
.auth_timeout_title
;
1189 case INCORRECT_ADDRESS
:
1190 mServerStatusText
= R
.string
.auth_incorrect_address_title
;
1193 mServerStatusText
= R
.string
.auth_ssl_general_error_title
;
1196 mServerStatusText
= R
.string
.auth_unauthorized
;
1198 case HOST_NOT_AVAILABLE
:
1199 mServerStatusText
= R
.string
.auth_unknown_host_title
;
1201 case INSTANCE_NOT_CONFIGURED
:
1202 mServerStatusText
= R
.string
.auth_not_configured_title
;
1204 case FILE_NOT_FOUND
:
1205 mServerStatusText
= R
.string
.auth_incorrect_path_title
;
1208 mServerStatusText
= R
.string
.auth_oauth_error
;
1210 case OAUTH2_ERROR_ACCESS_DENIED
:
1211 mServerStatusText
= R
.string
.auth_oauth_error_access_denied
;
1213 case UNHANDLED_HTTP_CODE
:
1215 mServerStatusText
= R
.string
.auth_unknown_error_title
;
1217 case OK_REDIRECT_TO_NON_SECURE_CONNECTION
:
1218 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1219 mServerStatusText
= R
.string
.auth_redirect_non_secure_connection_title
;
1222 mServerStatusText
= 0;
1223 mServerStatusIcon
= 0;
1229 * Chooses the right icon and text to show to the user for the received operation result.
1231 * @param result Result of a remote operation performed in this activity
1233 private void updateAuthStatusIconAndText(RemoteOperationResult result
) {
1234 mAuthStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1236 switch (result
.getCode()) {
1238 mAuthStatusIcon
= android
.R
.drawable
.ic_secure
;
1239 mAuthStatusText
= R
.string
.auth_secure_connection
;
1244 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1245 mAuthStatusText
= R
.string
.auth_connection_established
;
1246 mAuthStatusIcon
= R
.drawable
.ic_ok
;
1248 mAuthStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1249 mAuthStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1253 case NO_NETWORK_CONNECTION
:
1254 mAuthStatusIcon
= R
.drawable
.no_network
;
1255 mAuthStatusText
= R
.string
.auth_no_net_conn_title
;
1258 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1259 mAuthStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1261 case BAD_OC_VERSION
:
1262 mAuthStatusText
= R
.string
.auth_bad_oc_version_title
;
1264 case WRONG_CONNECTION
:
1265 mAuthStatusText
= R
.string
.auth_wrong_connection_title
;
1268 mAuthStatusText
= R
.string
.auth_timeout_title
;
1270 case INCORRECT_ADDRESS
:
1271 mAuthStatusText
= R
.string
.auth_incorrect_address_title
;
1274 mAuthStatusText
= R
.string
.auth_ssl_general_error_title
;
1277 mAuthStatusText
= R
.string
.auth_unauthorized
;
1279 case HOST_NOT_AVAILABLE
:
1280 mAuthStatusText
= R
.string
.auth_unknown_host_title
;
1282 case INSTANCE_NOT_CONFIGURED
:
1283 mAuthStatusText
= R
.string
.auth_not_configured_title
;
1285 case FILE_NOT_FOUND
:
1286 mAuthStatusText
= R
.string
.auth_incorrect_path_title
;
1289 mAuthStatusText
= R
.string
.auth_oauth_error
;
1291 case OAUTH2_ERROR_ACCESS_DENIED
:
1292 mAuthStatusText
= R
.string
.auth_oauth_error_access_denied
;
1294 case ACCOUNT_NOT_NEW
:
1295 mAuthStatusText
= R
.string
.auth_account_not_new
;
1297 case ACCOUNT_NOT_THE_SAME
:
1298 mAuthStatusText
= R
.string
.auth_account_not_the_same
;
1300 case UNHANDLED_HTTP_CODE
:
1302 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
1305 mAuthStatusText
= 0;
1306 mAuthStatusIcon
= 0;
1311 private void updateStatusIconFailUserName(){
1312 mAuthStatusIcon
= R
.drawable
.common_error
;
1313 mAuthStatusText
= R
.string
.auth_fail_get_user_name
;
1316 private void updateServerStatusIconNoRegularAuth(){
1317 mServerStatusIcon
= R
.drawable
.common_error
;
1318 mServerStatusText
= R
.string
.auth_can_not_auth_against_server
;
1322 * Processes the result of the request for and access token send
1323 * to an OAuth authorization server.
1325 * @param result Result of the operation.
1327 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result
) {
1328 mWaitingForOpId
= Long
.MAX_VALUE
;
1329 dismissDialog(WAIT_DIALOG_TAG
);
1331 if (result
.isSuccess()) {
1332 /// be gentle with the user
1333 IndeterminateProgressDialog dialog
=
1334 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
1335 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
1337 /// time to test the retrieved access token on the ownCloud server
1338 @SuppressWarnings("unchecked")
1339 Map
<String
, String
> tokens
= (Map
<String
, String
>)(result
.getData().get(0));
1340 mAuthToken
= tokens
.get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
1341 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mAuthToken
);
1343 accessRootFolderRemoteOperation("", "");
1346 updateAuthStatusIconAndText(result
);
1348 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1354 * Processes the result of the access check performed to try the user credentials.
1356 * Creates a new account through the AccountManager.
1358 * @param operation Access check performed.
1359 * @param result Result of the operation.
1361 private void onAuthorizationCheckFinish(RemoteOperationResult result
) {
1362 mWaitingForOpId
= Long
.MAX_VALUE
;
1363 dismissDialog(WAIT_DIALOG_TAG
);
1365 if (result
.isSuccess()) {
1366 Log_OC
.d(TAG
, "Successful access - time to save the account");
1368 boolean success
= false
;
1369 if (mAction
== ACTION_CREATE
) {
1370 success
= createAccount();
1381 } else if (result
.isServerFail() || result
.isException()) {
1382 /// server errors or exceptions in authorization take to requiring a new check of
1384 mServerIsChecked
= true
;
1385 mServerIsValid
= false
;
1386 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
1388 // update status icon and text
1389 updateServerStatusIconAndText(result
);
1391 mAuthStatusIcon
= 0;
1392 mAuthStatusText
= 0;
1395 // update input controls state
1396 showRefreshButton(true
);
1397 mOkButton
.setEnabled(false
);
1399 // very special case (TODO: move to a common place for all the remote operations)
1400 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1401 showUntrustedCertDialog(result
);
1404 } else { // authorization fail due to client side - probably wrong credentials
1405 updateAuthStatusIconAndText(result
);
1407 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1415 * Sets the proper response to get that the Account Authenticator that started this activity
1416 * saves a new authorization token for mAccount.
1418 private void updateToken() {
1419 Bundle response
= new Bundle();
1420 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1421 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
1423 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
1424 equals(mAuthTokenType
)) {
1425 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1426 // the next line is necessary, notifications are calling directly to the
1427 // AuthenticatorActivity to update, without AccountManager intervention
1428 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1430 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1431 equals(mAuthTokenType
)) {
1433 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1434 // the next line is necessary; by now, notifications are calling directly to the
1435 // AuthenticatorActivity to update, without AccountManager intervention
1436 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1439 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
1440 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
1442 setAccountAuthenticatorResult(response
);
1448 * Creates a new account through the Account Authenticator that started this activity.
1450 * This makes the account permanent.
1452 * TODO Decide how to name the OAuth accounts
1454 private boolean createAccount() {
1455 /// create and save new ownCloud account
1456 boolean isOAuth
= AccountTypeUtils
.
1457 getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
);
1458 boolean isSaml
= AccountTypeUtils
.
1459 getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
);
1461 Uri uri
= Uri
.parse(mServerInfo
.mBaseUrl
);
1462 String username
= mUsernameInput
.getText().toString().trim();
1464 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1466 String accountName
= com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.
1467 buildAccountName(uri
, username
);
1468 Account newAccount
= new Account(accountName
, MainApp
.getAccountType());
1469 if (AccountUtils
.exists(newAccount
, getApplicationContext())) {
1470 // fail - not a new account, but an existing one; disallow
1471 RemoteOperationResult result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_NEW
);
1472 updateAuthStatusIconAndText(result
);
1474 Log_OC
.d(TAG
, result
.getLogMessage());
1478 mAccount
= newAccount
;
1480 if (isOAuth
|| isSaml
) {
1481 // with external authorizations, the password is never input in the app
1482 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
);
1484 mAccountMgr
.addAccountExplicitly(
1485 mAccount
, mPasswordInput
.getText().toString(), null
1489 /// add the new account as default in preferences, if there is none already
1490 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1491 if (defaultAccount
== null
) {
1492 SharedPreferences
.Editor editor
= PreferenceManager
1493 .getDefaultSharedPreferences(this).edit();
1494 editor
.putString("select_oc_account", accountName
);
1498 /// prepare result to return to the Authenticator
1499 // TODO check again what the Authenticator makes with it; probably has the same
1500 // effect as addAccountExplicitly, but it's not well done
1501 final Intent intent
= new Intent();
1502 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, MainApp
.getAccountType());
1503 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1505 intent.putExtra(AccountManager.KEY_AUTHTOKEN, MainApp.getAccountType()); */
1506 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1507 if (isOAuth
|| isSaml
) {
1508 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1510 /// add user data to the new account; TODO probably can be done in the last parameter
1511 // addAccountExplicitly, or in KEY_USERDATA
1512 mAccountMgr
.setUserData(
1513 mAccount
, Constants
.KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion()
1515 mAccountMgr
.setUserData(
1516 mAccount
, Constants
.KEY_OC_BASE_URL
, mServerInfo
.mBaseUrl
1520 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
, "TRUE");
1521 } else if (isOAuth
) {
1522 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
, "TRUE");
1525 setAccountAuthenticatorResult(intent
.getExtras());
1526 setResult(RESULT_OK
, intent
);
1534 * Starts and activity to open the 'new account' page in the ownCloud web site
1536 * @param view 'Account register' button
1538 public void onRegisterClick(View view
) {
1539 Intent register
= new Intent(
1540 Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.welcome_link_url
))
1542 setResult(RESULT_CANCELED
);
1543 startActivity(register
);
1548 * Updates the content and visibility state of the icon and text associated
1549 * to the last check on the ownCloud server.
1551 * @param serverStatusText Resource identifier of the text to show.
1552 * @param serverStatusIcon Resource identifier of the icon to show.
1554 private void showServerStatus() {
1555 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1556 mServerStatusView
.setVisibility(View
.INVISIBLE
);
1559 mServerStatusView
.setText(mServerStatusText
);
1560 mServerStatusView
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1561 mServerStatusView
.setVisibility(View
.VISIBLE
);
1568 * Updates the content and visibility state of the icon and text associated
1569 * to the interactions with the OAuth authorization server.
1571 private void showAuthStatus() {
1572 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1573 mAuthStatusView
.setVisibility(View
.INVISIBLE
);
1576 mAuthStatusView
.setText(mAuthStatusText
);
1577 mAuthStatusView
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1578 mAuthStatusView
.setVisibility(View
.VISIBLE
);
1583 private void showRefreshButton (boolean show
) {
1585 mRefreshButton
.setVisibility(View
.VISIBLE
);
1587 mRefreshButton
.setVisibility(View
.GONE
);
1592 * Called when the refresh button in the input field for ownCloud host is clicked.
1594 * Performs a new check on the URL in the input field.
1596 * @param view Refresh 'button'
1598 public void onRefreshClick(View view
) {
1604 * Called when the eye icon in the password field is clicked.
1606 * Toggles the visibility of the password in the field.
1608 public void onViewPasswordClick() {
1609 int selectionStart
= mPasswordInput
.getSelectionStart();
1610 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1611 if (isPasswordVisible()) {
1616 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1621 * Called when the checkbox for OAuth authorization is clicked.
1623 * Hides or shows the input fields for user & password.
1625 * @param view 'View password' 'button'
1627 public void onCheckClick(View view
) {
1628 CheckBox oAuth2Check
= (CheckBox
)view
;
1629 if (oAuth2Check
.isChecked()) {
1630 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1632 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1634 updateAuthenticationPreFragmentVisibility();
1639 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1641 * Used to trigger the authentication check when the user presses 'enter' after writing the
1642 * password, or to throw the server test when the only field on screen is the URL input field.
1645 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1646 if (actionId
== EditorInfo
.IME_ACTION_DONE
&& inputField
!= null
&&
1647 inputField
.equals(mPasswordInput
)) {
1648 if (mOkButton
.isEnabled()) {
1649 mOkButton
.performClick();
1652 } else if (actionId
== EditorInfo
.IME_ACTION_NEXT
&& inputField
!= null
&&
1653 inputField
.equals(mHostUrlInput
)) {
1654 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1655 equals(mAuthTokenType
)) {
1659 return false
; // always return false to grant that the software keyboard is hidden anyway
1663 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1665 private int fuzz
= 75;
1671 public boolean onTouch(View view
, MotionEvent event
) {
1672 Drawable rightDrawable
= null
;
1673 if (view
instanceof TextView
) {
1674 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1675 if (drawables
.length
> 2) {
1676 rightDrawable
= drawables
[2];
1679 if (rightDrawable
!= null
) {
1680 final int x
= (int) event
.getX();
1681 final int y
= (int) event
.getY();
1682 final Rect bounds
= rightDrawable
.getBounds();
1683 if ( x
>= (view
.getRight() - bounds
.width() - fuzz
) &&
1684 x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
) &&
1685 y
>= (view
.getPaddingTop() - fuzz
) &&
1686 y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1688 return onDrawableTouch(event
);
1694 public abstract boolean onDrawableTouch(final MotionEvent event
);
1698 private void getRemoteUserNameOperation(String sessionCookie
, boolean followRedirects
) {
1700 Intent getUserNameIntent
= new Intent();
1701 getUserNameIntent
.setAction(OperationsService
.ACTION_GET_USER_NAME
);
1702 getUserNameIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
1703 getUserNameIntent
.putExtra(OperationsService
.EXTRA_COOKIE
, sessionCookie
);
1705 if (mOperationsServiceBinder
!= null
) {
1706 //Log_OC.wtf(TAG, "starting getRemoteUserNameOperation..." );
1707 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getUserNameIntent
);
1713 public void onSsoFinished(String sessionCookie
) {
1714 if (sessionCookie
!= null
&& sessionCookie
.length() > 0) {
1715 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1716 mAuthToken
= sessionCookie
;
1717 getRemoteUserNameOperation(sessionCookie
, true
);
1718 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1719 if (fd
!= null
&& fd
instanceof SherlockDialogFragment
) {
1720 Dialog d
= ((SherlockDialogFragment
)fd
).getDialog();
1721 if (d
!= null
&& d
.isShowing()) {
1728 Log_OC
.d(TAG
, "SSO failed");
1734 public boolean onTouchEvent(MotionEvent event
) {
1735 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1736 equals(mAuthTokenType
) &&
1737 mHostUrlInput
.hasFocus() && event
.getAction() == MotionEvent
.ACTION_DOWN
) {
1740 return super.onTouchEvent(event
);
1745 * Show untrusted cert dialog
1747 public void showUntrustedCertDialog(
1748 X509Certificate x509Certificate
, SslError error
, SslErrorHandler handler
1750 // Show a dialog with the certificate info
1751 SslUntrustedCertDialog dialog
= null
;
1752 if (x509Certificate
== null
) {
1753 dialog
= SslUntrustedCertDialog
.newInstanceForEmptySslError(error
, handler
);
1755 dialog
= SslUntrustedCertDialog
.
1756 newInstanceForFullSslError(x509Certificate
, error
, handler
);
1758 FragmentManager fm
= getSupportFragmentManager();
1759 FragmentTransaction ft
= fm
.beginTransaction();
1760 ft
.addToBackStack(null
);
1761 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1766 * Show untrusted cert dialog
1768 private void showUntrustedCertDialog(RemoteOperationResult result
) {
1769 // Show a dialog with the certificate info
1770 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.
1771 newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1772 FragmentManager fm
= getSupportFragmentManager();
1773 FragmentTransaction ft
= fm
.beginTransaction();
1774 ft
.addToBackStack(null
);
1775 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1780 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1782 public void onSavedCertificate() {
1783 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1785 // if SAML dialog is not shown,
1786 // the SslDialog was shown due to an SSL error in the server check
1792 * Called from SslValidatorDialog when a new server certificate could not be saved
1793 * when the user requested it.
1796 public void onFailedSavingCertificate() {
1797 dismissDialog(SAML_DIALOG_TAG
);
1798 Toast
.makeText(this, R
.string
.ssl_validator_not_saved
, Toast
.LENGTH_LONG
).show();
1802 public void onCancelCertificate() {
1803 dismissDialog(SAML_DIALOG_TAG
);
1807 private void doOnResumeAndBound() {
1808 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1809 mOperationsServiceBinder
.addOperationListener(AuthenticatorActivity
.this, mHandler
);
1810 if (mWaitingForOpId
<= Integer
.MAX_VALUE
) {
1811 mOperationsServiceBinder
.dispatchResultIfFinished((int)mWaitingForOpId
, this);
1814 if (mPendingAutoCheck
) {
1820 private void dismissDialog(String dialogTag
){
1821 Fragment frag
= getSupportFragmentManager().findFragmentByTag(dialogTag
);
1822 if (frag
!= null
&& frag
instanceof SherlockDialogFragment
) {
1823 SherlockDialogFragment dialog
= (SherlockDialogFragment
) frag
;
1830 * Implements callback methods for service binding.
1832 private class OperationsServiceConnection
implements ServiceConnection
{
1835 public void onServiceConnected(ComponentName component
, IBinder service
) {
1836 if (component
.equals(
1837 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1839 //Log_OC.wtf(TAG, "Operations service connected");
1840 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
1842 doOnResumeAndBound();
1851 public void onServiceDisconnected(ComponentName component
) {
1852 if (component
.equals(
1853 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1855 Log_OC
.e(TAG
, "Operations service crashed");
1856 mOperationsServiceBinder
= null
;
1863 * Create and show dialog for request authentication to the user
1867 public void createAuthenticationDialog(WebView webView
, HttpAuthHandler handler
) {
1869 // Show a dialog with the certificate info
1870 CredentialsDialogFragment dialog
=
1871 CredentialsDialogFragment
.newInstanceForCredentials(webView
, handler
);
1872 FragmentManager fm
= getSupportFragmentManager();
1873 FragmentTransaction ft
= fm
.beginTransaction();
1874 ft
.addToBackStack(null
);
1875 dialog
.setCancelable(false
);
1876 dialog
.show(ft
, CREDENTIALS_DIALOG_TAG
);
1878 if (!mIsFirstAuthAttempt
) {
1880 getApplicationContext(),
1881 getText(R
.string
.saml_authentication_wrong_pass
),
1885 mIsFirstAuthAttempt
= false
;
1890 * For retrieving the clicking on authentication cancel button
1892 public void doNegativeAuthenticatioDialogClick(){
1893 mIsFirstAuthAttempt
= true
;