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
.resources
.files
.ExistenceCheckRemoteOperation
;
75 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
76 import com
.owncloud
.android
.lib
.resources
.users
.GetRemoteUserNameOperation
;
77 import com
.owncloud
.android
.operations
.DetectAuthenticationMethodOperation
.AuthenticationMethod
;
78 import com
.owncloud
.android
.operations
.GetServerInfoOperation
;
79 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
80 import com
.owncloud
.android
.services
.OperationsService
;
81 import com
.owncloud
.android
.services
.OperationsService
.OperationsServiceBinder
;
82 import com
.owncloud
.android
.ui
.dialog
.CredentialsDialogFragment
;
83 import com
.owncloud
.android
.ui
.dialog
.IndeterminateProgressDialog
;
84 import com
.owncloud
.android
.ui
.dialog
.SamlWebViewDialog
;
85 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
86 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
87 import com
.owncloud
.android
.utils
.Log_OC
;
90 * This Activity is used to add an ownCloud account to the App
92 * @author Bartek Przybylski
93 * @author David A. Velasco
96 public class AuthenticatorActivity
extends AccountAuthenticatorActivity
97 implements OnRemoteOperationListener
, OnFocusChangeListener
, OnEditorActionListener
,
98 SsoWebViewClientListener
, OnSslUntrustedCertListener
{
100 private static final String TAG
= AuthenticatorActivity
.class.getSimpleName();
102 public static final String EXTRA_ACTION
= "ACTION";
103 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
105 private static final String KEY_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
107 private static final String KEY_HOST_URL_TEXT
= "HOST_URL_TEXT";
108 private static final String KEY_OC_VERSION
= "OC_VERSION";
109 private static final String KEY_SERVER_VALID
= "SERVER_VALID";
110 private static final String KEY_SERVER_CHECKED
= "SERVER_CHECKED";
111 private static final String KEY_SERVER_STATUS_TEXT
= "SERVER_STATUS_TEXT";
112 private static final String KEY_SERVER_STATUS_ICON
= "SERVER_STATUS_ICON";
113 private static final String KEY_IS_SSL_CONN
= "IS_SSL_CONN";
114 private static final String KEY_PASSWORD_EXPOSED
= "PASSWORD_VISIBLE";
115 private static final String KEY_AUTH_STATUS_TEXT
= "AUTH_STATUS_TEXT";
116 private static final String KEY_AUTH_STATUS_ICON
= "AUTH_STATUS_ICON";
117 private static final String KEY_SERVER_AUTH_METHOD
= "SERVER_AUTH_METHOD";
118 private static final String KEY_WAITING_FOR_OP_ID
= "WAITING_FOR_OP_ID";
119 private static final String KEY_AUTH_TOKEN
= "AUTH_TOKEN";
121 private static final String AUTH_ON
= "on";
122 private static final String AUTH_OPTIONAL
= "optional";
124 public static final byte ACTION_CREATE
= 0;
125 public static final byte ACTION_UPDATE_TOKEN
= 1; // requested by the user
126 public static final byte ACTION_UPDATE_EXPIRED_TOKEN
= 2; // detected by the app
128 private static final String UNTRUSTED_CERT_DIALOG_TAG
= "UNTRUSTED_CERT_DIALOG";
129 private static final String SAML_DIALOG_TAG
= "SAML_DIALOG";
130 private static final String WAIT_DIALOG_TAG
= "WAIT_DIALOG";
131 private static final String CREDENTIALS_DIALOG_TAG
= "CREDENTIALS_DIALOG";
132 private static final String KEY_AUTH_IS_FIRST_ATTEMPT_TAG
= "KEY_AUTH_IS_FIRST_ATTEMPT";
135 /// parameters from EXTRAs in starter Intent
136 private byte mAction
;
137 private Account mAccount
;
138 private String mAuthTokenType
;
141 /// activity-level references / state
142 private final Handler mHandler
= new Handler();
143 private ServiceConnection mOperationsServiceConnection
= null
;
144 private OperationsServiceBinder mOperationsServiceBinder
= null
;
145 private AccountManager mAccountMgr
;
146 private Uri mNewCapturedUriFromOAuth2Redirection
;
149 /// Server PRE-Fragment elements
150 private EditText mHostUrlInput
;
151 private View mRefreshButton
;
152 private TextView mServerStatusView
;
154 private TextWatcher mHostUrlInputWatcher
;
155 private int mServerStatusText
= 0, mServerStatusIcon
= 0;
157 private boolean mServerIsChecked
= false
;
158 private boolean mServerIsValid
= false
;
159 private boolean mPendingAutoCheck
= false
;
161 private GetServerInfoOperation
.ServerInfo mServerInfo
=
162 new GetServerInfoOperation
.ServerInfo();
165 /// Authentication PRE-Fragment elements
166 private CheckBox mOAuth2Check
;
167 private TextView mOAuthAuthEndpointText
;
168 private TextView mOAuthTokenEndpointText
;
169 private EditText mUsernameInput
;
170 private EditText mPasswordInput
;
171 private View mOkButton
;
172 private TextView mAuthStatusView
;
174 private int mAuthStatusText
= 0, mAuthStatusIcon
= 0;
176 private String mAuthToken
= "";
178 private boolean mIsFirstAuthAttempt
;
181 /// Identifier of operation in progress which result shouldn't be lost
182 private long mWaitingForOpId
= Long
.MAX_VALUE
;
188 * IMPORTANT ENTRY POINT 1: activity is shown to the user
191 protected void onCreate(Bundle savedInstanceState
) {
192 //Log_OC.wtf(TAG, "onCreate init");
193 super.onCreate(savedInstanceState
);
194 getWindow().requestFeature(Window
.FEATURE_NO_TITLE
);
196 mIsFirstAuthAttempt
= true
;
198 // bind to Operations Service
199 mOperationsServiceConnection
= new OperationsServiceConnection();
200 if (!bindService(new Intent(this, OperationsService
.class),
201 mOperationsServiceConnection
,
202 Context
.BIND_AUTO_CREATE
)) {
204 R
.string
.error_cant_bind_to_operations_service
,
210 /// init activity state
211 mAccountMgr
= AccountManager
.get(this);
212 mNewCapturedUriFromOAuth2Redirection
= null
;
215 mAction
= getIntent().getByteExtra(EXTRA_ACTION
, ACTION_CREATE
);
216 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
217 if (savedInstanceState
== null
) {
220 mAuthTokenType
= savedInstanceState
.getString(KEY_AUTH_TOKEN_TYPE
);
221 mWaitingForOpId
= savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
);
222 mIsFirstAuthAttempt
= savedInstanceState
.getBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
);
225 /// load user interface
226 setContentView(R
.layout
.account_setup
);
228 /// initialize general UI elements
229 initOverallUi(savedInstanceState
);
231 mOkButton
= findViewById(R
.id
.buttonOK
);
233 /// initialize block to be moved to single Fragment to check server and get info about it
234 initServerPreFragment(savedInstanceState
);
236 /// initialize block to be moved to single Fragment to retrieve and validate credentials
237 initAuthorizationPreFragment(savedInstanceState
);
239 //Log_OC.wtf(TAG, "onCreate end");
242 private void initAuthTokenType() {
244 getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
245 if (mAuthTokenType
== null
) {
246 if (mAccount
!= null
) {
247 boolean oAuthRequired
=
248 (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
) != null
);
249 boolean samlWebSsoRequired
=
250 (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
) != null
);
251 mAuthTokenType
= chooseAuthTokenType(oAuthRequired
, samlWebSsoRequired
);
254 boolean oAuthSupported
= AUTH_ON
.equals(getString(R
.string
.auth_method_oauth2
));
255 boolean samlWebSsoSupported
= AUTH_ON
.equals(getString(R
.string
.auth_method_saml_web_sso
));
256 mAuthTokenType
= chooseAuthTokenType(oAuthSupported
, samlWebSsoSupported
);
261 private String
chooseAuthTokenType(boolean oauth
, boolean saml
) {
263 return AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
265 return AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
267 return AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
273 * Configures elements in the user interface under direct control of the Activity.
275 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
277 private void initOverallUi(Bundle savedInstanceState
) {
279 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
280 boolean isWelcomeLinkVisible
= getResources().getBoolean(R
.bool
.show_welcome_link
);
282 String instructionsMessageText
= null
;
283 if (mAction
== ACTION_UPDATE_EXPIRED_TOKEN
) {
284 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
285 .equals(mAuthTokenType
)) {
286 instructionsMessageText
= getString(R
.string
.auth_expired_oauth_token_toast
);
288 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType())
289 .equals(mAuthTokenType
)) {
290 instructionsMessageText
= getString(R
.string
.auth_expired_saml_sso_token_toast
);
293 instructionsMessageText
= getString(R
.string
.auth_expired_basic_auth_toast
);
297 /// step 2 - set properties of UI elements (text, visibility, enabled...)
298 Button welcomeLink
= (Button
) findViewById(R
.id
.welcome_link
);
299 welcomeLink
.setVisibility(isWelcomeLinkVisible ? View
.VISIBLE
: View
.GONE
);
301 String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
303 TextView instructionsView
= (TextView
) findViewById(R
.id
.instructions_message
);
304 if (instructionsMessageText
!= null
) {
305 instructionsView
.setVisibility(View
.VISIBLE
);
306 instructionsView
.setText(instructionsMessageText
);
308 instructionsView
.setVisibility(View
.GONE
);
315 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
317 private void initServerPreFragment(Bundle savedInstanceState
) {
319 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
320 boolean isUrlInputAllowed
= getResources().getBoolean(R
.bool
.show_server_url_input
);
321 if (savedInstanceState
== null
) {
322 if (mAccount
!= null
) {
323 mServerInfo
.mBaseUrl
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_BASE_URL
);
324 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://"); // TODO do this in a setter for mBaseUrl
325 String ocVersion
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_VERSION
);
326 if (ocVersion
!= null
) {
327 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
330 mServerInfo
.mBaseUrl
= getString(R
.string
.server_url
).trim();
331 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
334 mServerStatusText
= savedInstanceState
.getInt(KEY_SERVER_STATUS_TEXT
);
335 mServerStatusIcon
= savedInstanceState
.getInt(KEY_SERVER_STATUS_ICON
);
337 mServerIsValid
= savedInstanceState
.getBoolean(KEY_SERVER_VALID
);
338 mServerIsChecked
= savedInstanceState
.getBoolean(KEY_SERVER_CHECKED
);
341 mServerInfo
.mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
342 mServerInfo
.mBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
343 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
344 if (ocVersion
!= null
) {
345 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
347 mServerInfo
.mAuthMethod
= AuthenticationMethod
.valueOf(
348 savedInstanceState
.getString(KEY_SERVER_AUTH_METHOD
));
352 /// step 2 - set properties of UI elements (text, visibility, enabled...)
353 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
354 mHostUrlInput
.setText(mServerInfo
.mBaseUrl
);
355 if (mAction
!= ACTION_CREATE
) {
356 /// lock things that should not change
357 mHostUrlInput
.setEnabled(false
);
358 mHostUrlInput
.setFocusable(false
);
360 if (isUrlInputAllowed
) {
361 mRefreshButton
= findViewById(R
.id
.embeddedRefreshButton
);
363 findViewById(R
.id
.hostUrlFrame
).setVisibility(View
.GONE
);
364 mRefreshButton
= findViewById(R
.id
.centeredRefreshButton
);
366 showRefreshButton(mServerIsChecked
&& !mServerIsValid
&&
367 mWaitingForOpId
> Integer
.MAX_VALUE
);
368 mServerStatusView
= (TextView
) findViewById(R
.id
.server_status_text
);
371 /// step 3 - bind some listeners and options
372 mHostUrlInput
.setImeOptions(EditorInfo
.IME_ACTION_NEXT
);
373 mHostUrlInput
.setOnEditorActionListener(this);
375 /// step 4 - create listeners that will be bound at onResume
376 mHostUrlInputWatcher
= new TextWatcher() {
379 public void afterTextChanged(Editable s
) {
380 if (mOkButton
.isEnabled() &&
381 !mServerInfo
.mBaseUrl
.equals(
382 normalizeUrl(s
.toString(), mServerInfo
.mIsSslConn
))) {
383 mOkButton
.setEnabled(false
);
388 public void beforeTextChanged(CharSequence s
, int start
, int count
, int after
) {
392 public void onTextChanged(CharSequence s
, int start
, int before
, int count
) {
393 if (mAuthStatusIcon
!= 0) {
394 Log_OC
.d(TAG
, "onTextChanged: hiding authentication status");
403 // TODO find out if this is really necessary, or if it can done in a different way
404 findViewById(R
.id
.scroll
).setOnTouchListener(new OnTouchListener() {
406 public boolean onTouch(View view
, MotionEvent event
) {
407 if (event
.getAction() == MotionEvent
.ACTION_DOWN
) {
408 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
) &&
409 mHostUrlInput
.hasFocus()) {
418 /// step 4 - mark automatic check to be started when OperationsService is ready
419 mPendingAutoCheck
= (savedInstanceState
== null
&&
420 (mAction
!= ACTION_CREATE
|| !isUrlInputAllowed
));
426 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
428 private void initAuthorizationPreFragment(Bundle savedInstanceState
) {
430 /// step 0 - get UI elements in layout
431 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
432 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
433 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
434 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
435 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
436 mAuthStatusView
= (TextView
) findViewById(R
.id
.auth_status_text
);
438 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
439 String presetUserName
= null
;
440 boolean isPasswordExposed
= false
;
441 if (savedInstanceState
== null
) {
442 if (mAccount
!= null
) {
443 presetUserName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
447 isPasswordExposed
= savedInstanceState
.getBoolean(KEY_PASSWORD_EXPOSED
, false
);
448 mAuthStatusText
= savedInstanceState
.getInt(KEY_AUTH_STATUS_TEXT
);
449 mAuthStatusIcon
= savedInstanceState
.getInt(KEY_AUTH_STATUS_ICON
);
450 mAuthToken
= savedInstanceState
.getString(KEY_AUTH_TOKEN
);
453 /// step 2 - set properties of UI elements (text, visibility, enabled...)
454 mOAuth2Check
.setChecked(
455 AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
456 .equals(mAuthTokenType
));
457 if (presetUserName
!= null
) {
458 mUsernameInput
.setText(presetUserName
);
460 if (mAction
!= ACTION_CREATE
) {
461 mUsernameInput
.setEnabled(false
);
462 mUsernameInput
.setFocusable(false
);
464 mPasswordInput
.setText(""); // clean password to avoid social hacking
465 if (isPasswordExposed
) {
468 updateAuthenticationPreFragmentVisibility();
470 mOkButton
.setEnabled(mServerIsValid
);
473 /// step 3 - bind listeners
474 // bindings for password input field
475 mPasswordInput
.setOnFocusChangeListener(this);
476 mPasswordInput
.setImeOptions(EditorInfo
.IME_ACTION_DONE
);
477 mPasswordInput
.setOnEditorActionListener(this);
478 mPasswordInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
480 public boolean onDrawableTouch(final MotionEvent event
) {
481 if (event
.getAction() == MotionEvent
.ACTION_UP
) {
482 AuthenticatorActivity
.this.onViewPasswordClick();
492 * Changes the visibility of input elements depending on
493 * the current authorization method.
495 private void updateAuthenticationPreFragmentVisibility () {
496 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
497 equals(mAuthTokenType
)) {
498 // SAML-based web Single Sign On
499 mOAuth2Check
.setVisibility(View
.GONE
);
500 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
501 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
502 mUsernameInput
.setVisibility(View
.GONE
);
503 mPasswordInput
.setVisibility(View
.GONE
);
506 if (mAction
== ACTION_CREATE
&&
507 AUTH_OPTIONAL
.equals(getString(R
.string
.auth_method_oauth2
))) {
508 mOAuth2Check
.setVisibility(View
.VISIBLE
);
510 mOAuth2Check
.setVisibility(View
.GONE
);
513 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
514 equals(mAuthTokenType
)) {
515 // OAuth 2 authorization
517 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
518 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
519 mUsernameInput
.setVisibility(View
.GONE
);
520 mPasswordInput
.setVisibility(View
.GONE
);
523 // basic HTTP authorization
524 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
525 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
526 mUsernameInput
.setVisibility(View
.VISIBLE
);
527 mPasswordInput
.setVisibility(View
.VISIBLE
);
535 * Saves relevant state before {@link #onPause()}
537 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag, intended to defer the
538 * processing of the redirection caught in {@link #onNewIntent(Intent)} until {@link #onResume()}
540 * See {@link #loadSavedInstanceState(Bundle)}
543 protected void onSaveInstanceState(Bundle outState
) {
544 //Log_OC.wtf(TAG, "onSaveInstanceState init" );
545 super.onSaveInstanceState(outState
);
548 outState
.putString(KEY_AUTH_TOKEN_TYPE
, mAuthTokenType
);
549 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mWaitingForOpId
);
551 /// Server PRE-fragment state
552 outState
.putInt(KEY_SERVER_STATUS_TEXT
, mServerStatusText
);
553 outState
.putInt(KEY_SERVER_STATUS_ICON
, mServerStatusIcon
);
554 outState
.putBoolean(KEY_SERVER_CHECKED
, mServerIsChecked
);
555 outState
.putBoolean(KEY_SERVER_VALID
, mServerIsValid
);
556 outState
.putBoolean(KEY_IS_SSL_CONN
, mServerInfo
.mIsSslConn
);
557 outState
.putString(KEY_HOST_URL_TEXT
, mServerInfo
.mBaseUrl
);
558 if (mServerInfo
.mVersion
!= null
) {
559 outState
.putString(KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion());
561 outState
.putString(KEY_SERVER_AUTH_METHOD
, mServerInfo
.mAuthMethod
.name());
563 /// Authentication PRE-fragment state
564 outState
.putBoolean(KEY_PASSWORD_EXPOSED
, isPasswordVisible());
565 outState
.putInt(KEY_AUTH_STATUS_ICON
, mAuthStatusIcon
);
566 outState
.putInt(KEY_AUTH_STATUS_TEXT
, mAuthStatusText
);
567 outState
.putString(KEY_AUTH_TOKEN
, mAuthToken
);
570 outState
.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
, mIsFirstAuthAttempt
);
572 //Log_OC.wtf(TAG, "onSaveInstanceState end" );
577 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION request
580 * To make this possible, this activity needs to be qualified with android:launchMode = "singleTask" in the
581 * AndroidManifest.xml file.
584 protected void onNewIntent (Intent intent
) {
585 Log_OC
.d(TAG
, "onNewIntent()");
586 Uri data
= intent
.getData();
587 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
588 mNewCapturedUriFromOAuth2Redirection
= data
;
594 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION, and
595 * deferred in {@link #onNewIntent(Intent)}, is processed here.
598 protected void onResume() {
599 //Log_OC.wtf(TAG, "onResume init" );
602 // bound here to avoid spurious changes triggered by Android on device rotations
603 mHostUrlInput
.setOnFocusChangeListener(this);
604 mHostUrlInput
.addTextChangedListener(mHostUrlInputWatcher
);
606 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
607 getOAuth2AccessTokenFromCapturedRedirection();
610 if (mOperationsServiceBinder
!= null
) {
611 doOnResumeAndBound();
614 //Log_OC.wtf(TAG, "onResume end" );
619 protected void onPause() {
620 //Log_OC.wtf(TAG, "onPause init" );
621 if (mOperationsServiceBinder
!= null
) {
622 //Log_OC.wtf(TAG, "unregistering to listen for operation callbacks" );
623 mOperationsServiceBinder
.removeOperationListener(this);
626 mHostUrlInput
.removeTextChangedListener(mHostUrlInputWatcher
);
627 mHostUrlInput
.setOnFocusChangeListener(null
);
630 //Log_OC.wtf(TAG, "onPause end" );
634 protected void onDestroy() {
636 mHostUrlInputWatcher
= null
;
638 if (mOperationsServiceConnection
!= null
) {
639 unbindService(mOperationsServiceConnection
);
640 mOperationsServiceBinder
= null
;
647 * Parses the redirection with the response to the GET AUTHORIZATION request to the
648 * oAuth server and requests for the access token (GET ACCESS TOKEN)
650 private void getOAuth2AccessTokenFromCapturedRedirection() {
651 /// Parse data from OAuth redirection
652 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
653 mNewCapturedUriFromOAuth2Redirection
= null
;
655 /// Showing the dialog with instructions for the user.
656 IndeterminateProgressDialog dialog
=
657 IndeterminateProgressDialog
.newInstance(R
.string
.auth_getting_authorization
, true
);
658 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
660 /// GET ACCESS TOKEN to the oAuth server
661 Intent getServerInfoIntent
= new Intent();
662 getServerInfoIntent
.setAction(OperationsService
.ACTION_OAUTH2_GET_ACCESS_TOKEN
);
664 getServerInfoIntent
.putExtra(
665 OperationsService
.EXTRA_SERVER_URL
,
666 mOAuthTokenEndpointText
.getText().toString().trim());
668 getServerInfoIntent
.putExtra(
669 OperationsService
.EXTRA_OAUTH2_QUERY_PARAMETERS
,
672 if (mOperationsServiceBinder
!= null
) {
673 //Log_OC.wtf(TAG, "getting access token..." );
674 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(getServerInfoIntent
);
681 * Handles the change of focus on the text inputs for the server URL and the password
683 public void onFocusChange(View view
, boolean hasFocus
) {
684 if (view
.getId() == R
.id
.hostUrlInput
) {
686 onUrlInputFocusLost((TextView
) view
);
689 showRefreshButton(false
);
692 } else if (view
.getId() == R
.id
.account_password
) {
693 onPasswordFocusChanged((TextView
) view
, hasFocus
);
699 * Handles changes in focus on the text input for the server URL.
701 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
702 * other field. The operation to check the existence of the server in the entered URL is
705 * When hasFocus: user 'comes back' to write again the server URL.
707 * @param hostInput TextView with the URL input field receiving the change of focus.
709 private void onUrlInputFocusLost(TextView hostInput
) {
710 if (!mServerInfo
.mBaseUrl
.equals(
711 normalizeUrl(mHostUrlInput
.getText().toString(), mServerInfo
.mIsSslConn
))) {
712 // check server again only if the user changed something in the field
715 mOkButton
.setEnabled(mServerIsValid
);
716 showRefreshButton(!mServerIsValid
);
721 private void checkOcServer() {
722 String uri
= mHostUrlInput
.getText().toString().trim();
723 mServerIsValid
= false
;
724 mServerIsChecked
= false
;
725 mOkButton
.setEnabled(false
);
726 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
727 showRefreshButton(false
);
729 if (uri
.length() != 0) {
730 mServerStatusText
= R
.string
.auth_testing_connection
;
731 mServerStatusIcon
= R
.drawable
.progress_small
;
734 Intent getServerInfoIntent
= new Intent();
735 getServerInfoIntent
.setAction(OperationsService
.ACTION_GET_SERVER_INFO
);
736 getServerInfoIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, uri
);
737 if (mOperationsServiceBinder
!= null
) {
738 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(getServerInfoIntent
);
740 Log_OC
.wtf(TAG
, "Server check tried with OperationService unbound!" );
744 mServerStatusText
= 0;
745 mServerStatusIcon
= 0;
752 * Handles changes in focus on the text input for the password (basic authorization).
754 * When (hasFocus), the button to toggle password visibility is shown.
756 * When (!hasFocus), the button is made invisible and the password is hidden.
758 * @param passwordInput TextView with the password input field receiving the change of focus.
759 * @param hasFocus 'True' if focus is received, 'false' if is lost
761 private void onPasswordFocusChanged(TextView passwordInput
, boolean hasFocus
) {
763 showViewPasswordButton();
766 hidePasswordButton();
771 private void showViewPasswordButton() {
772 int drawable
= R
.drawable
.ic_view
;
773 if (isPasswordVisible()) {
774 drawable
= R
.drawable
.ic_hide
;
776 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable
, 0);
779 private boolean isPasswordVisible() {
780 return ((mPasswordInput
.getInputType() & InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) == InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
783 private void hidePasswordButton() {
784 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
787 private void showPassword() {
788 mPasswordInput
.setInputType(InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
789 showViewPasswordButton();
792 private void hidePassword() {
793 mPasswordInput
.setInputType(InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
);
794 showViewPasswordButton();
798 * Checks the credentials of the user in the root of the ownCloud server
799 * before creating a new local account.
801 * For basic authorization, a check of existence of the root folder is
804 * For OAuth, starts the flow to get an access token; the credentials test
805 * is postponed until it is available.
807 * IMPORTANT ENTRY POINT 4
809 * @param view OK button
811 public void onOkClick(View view
) {
812 // this check should be unnecessary
813 if (mServerInfo
.mVersion
== null
||
814 !mServerInfo
.mVersion
.isVersionValid() ||
815 mServerInfo
.mBaseUrl
== null
||
816 mServerInfo
.mBaseUrl
.length() == 0) {
817 mServerStatusIcon
= R
.drawable
.common_error
;
818 mServerStatusText
= R
.string
.auth_wtf_reenter_URL
;
820 mOkButton
.setEnabled(false
);
821 //Log_OC.wtf(TAG, "The user was allowed to click 'connect' to an unchecked server!!");
825 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
826 startOauthorization();
827 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
828 startSamlBasedFederatedSingleSignOnAuthorization();
830 checkBasicAuthorization();
836 * Tests the credentials entered by the user performing a check of existence on
837 * the root folder of the ownCloud server.
839 private void checkBasicAuthorization() {
840 /// get basic credentials entered by user
841 String username
= mUsernameInput
.getText().toString();
842 String password
= mPasswordInput
.getText().toString();
844 /// be gentle with the user
845 IndeterminateProgressDialog dialog
=
846 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
847 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
849 /// validate credentials accessing the root folder
850 accessRootFolderRemoteOperation(username
, password
);
854 private void accessRootFolderRemoteOperation(String username
, String password
) {
855 Intent existenceCheckIntent
= new Intent();
856 existenceCheckIntent
.setAction(OperationsService
.ACTION_EXISTENCE_CHECK
);
857 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
858 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_REMOTE_PATH
, "/");
859 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_USERNAME
, username
);
860 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_PASSWORD
, password
);
861 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_AUTH_TOKEN
, mAuthToken
);
863 if (mOperationsServiceBinder
!= null
) {
864 //Log_OC.wtf(TAG, "starting existenceCheckRemoteOperation..." );
865 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(existenceCheckIntent
);
870 * Starts the OAuth 'grant type' flow to get an access token, with
871 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
873 private void startOauthorization() {
874 // be gentle with the user
875 mAuthStatusIcon
= R
.drawable
.progress_small
;
876 mAuthStatusText
= R
.string
.oauth_login_connection
;
879 // GET AUTHORIZATION request
880 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
881 Uri
.Builder uriBuilder
= uri
.buildUpon();
882 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
));
883 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
));
884 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
));
885 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
));
886 uri
= uriBuilder
.build();
887 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
888 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
894 * Starts the Web Single Sign On flow to get access to the root folder
897 private void startSamlBasedFederatedSingleSignOnAuthorization() {
898 // be gentle with the user
899 mAuthStatusIcon
= R
.drawable
.progress_small
;
900 mAuthStatusText
= R
.string
.auth_connecting_auth_server
;
902 IndeterminateProgressDialog dialog
=
903 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
904 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
906 /// validate credentials accessing the root folder
907 accessRootFolderRemoteOperation("", "");
912 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
914 * Dispatches the operation flow to the right method.
917 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
919 if (operation
instanceof GetServerInfoOperation
) {
920 if (operation
.hashCode() == mWaitingForOpId
) {
921 onGetServerInfoFinish(result
);
922 } // else nothing ; only the last check operation is considered;
923 // multiple can be started if the user amends a URL quickly
925 } else if (operation
instanceof OAuth2GetAccessToken
) {
926 onGetOAuthAccessTokenFinish(result
);
928 } else if (operation
instanceof ExistenceCheckRemoteOperation
) {
929 //Log_OC.wtf(TAG, "received detection response through callback" );
930 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
931 onSamlBasedFederatedSingleSignOnAuthorizationStart(result
);
934 onAuthorizationCheckFinish(result
);
936 } else if (operation
instanceof GetRemoteUserNameOperation
) {
937 onGetUserNameFinish(result
);
942 private void onGetUserNameFinish(RemoteOperationResult result
) {
943 mWaitingForOpId
= Long
.MAX_VALUE
;
944 if (result
.isSuccess()) {
945 boolean success
= false
;
946 String username
= (String
) result
.getData().get(0);
948 if ( mAction
== ACTION_CREATE
) {
949 mUsernameInput
.setText(username
);
950 success
= createAccount();
953 if (!mUsernameInput
.getText().toString().equals(username
)) {
954 // fail - not a new account, but an existing one; disallow
955 result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_THE_SAME
);
957 OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(
959 Uri.parse(mServerInfo.mBaseUrl),
960 OwnCloudCredentialsFactory.newSamlSsoCredentials(mAuthToken))
964 updateAuthStatusIconAndText(result
);
966 Log_OC
.d(TAG
, result
.getLogMessage());
976 updateStatusIconFailUserName();
978 Log_OC
.e(TAG
, "Access to user name failed: " + result
.getLogMessage());
983 private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperationResult result
) {
984 mWaitingForOpId
= Long
.MAX_VALUE
;
985 dismissDialog(WAIT_DIALOG_TAG
);
987 if (result
.isIdPRedirection()) {
988 String url
= result
.getRedirectedLocation();
989 String targetUrl
= mServerInfo
.mBaseUrl
990 + AccountUtils
.getWebdavPath(mServerInfo
.mVersion
, mAuthTokenType
);
993 SamlWebViewDialog dialog
= SamlWebViewDialog
.newInstance(url
, targetUrl
);
994 dialog
.show(getSupportFragmentManager(), SAML_DIALOG_TAG
);
1000 mAuthStatusIcon
= R
.drawable
.common_error
;
1001 mAuthStatusText
= R
.string
.auth_unsupported_auth_method
;
1009 * Processes the result of the server check performed when the user finishes the enter of the
1012 * @param operation Server check performed.
1013 * @param result Result of the check.
1015 private void onGetServerInfoFinish(RemoteOperationResult result
) {
1016 /// update activity state
1017 mServerIsChecked
= true
;
1018 mWaitingForOpId
= Long
.MAX_VALUE
;
1020 // update server status, but don't show it yet
1021 updateServerStatusIconAndText(result
);
1023 if (result
.isSuccess()) {
1025 // 1. connection succeeded, and we know if it's SSL or not
1026 // 2. server is installed
1027 // 3. we got the server version
1028 // 4. we got the authentication method required by the server
1029 mServerInfo
= (GetServerInfoOperation
.ServerInfo
) (result
.getData().get(0));
1031 if (!authSupported(mServerInfo
.mAuthMethod
)) {
1033 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1034 mServerIsValid
= false
;
1037 mServerIsValid
= true
;
1041 mServerIsValid
= false
;
1045 showRefreshButton(!mServerIsValid
);
1047 mOkButton
.setEnabled(mServerIsValid
);
1049 /// very special case (TODO: move to a common place for all the remote operations)
1050 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1051 showUntrustedCertDialog(result
);
1056 private boolean authSupported(AuthenticationMethod authMethod
) {
1057 String basic
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1058 String oAuth
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1059 String saml
= AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
1061 return (( mAuthTokenType
.equals(basic
) &&
1062 authMethod
.equals(AuthenticationMethod
.BASIC_HTTP_AUTH
) ) ||
1063 ( mAuthTokenType
.equals(oAuth
) &&
1064 authMethod
.equals(AuthenticationMethod
.BEARER_TOKEN
)) ||
1065 ( mAuthTokenType
.equals(saml
) &&
1066 authMethod
.equals(AuthenticationMethod
.SAML_WEB_SSO
))
1071 // TODO remove, if possible
1072 private String
normalizeUrl(String url
, boolean sslWhenUnprefixed
) {
1073 if (url
!= null
&& url
.length() > 0) {
1075 if (!url
.toLowerCase().startsWith("http://") &&
1076 !url
.toLowerCase().startsWith("https://")) {
1077 if (sslWhenUnprefixed
) {
1078 url
= "https://" + url
;
1080 url
= "http://" + url
;
1084 url
= trimUrlWebdav(url
);
1086 if (url
.endsWith("/")) {
1087 url
= url
.substring(0, url
.length() - 1);
1091 return (url
!= null ? url
: "");
1095 // TODO remove, if possible
1096 private String
trimUrlWebdav(String url
){
1097 if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_4_0
)){
1098 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_4_0
.length());
1099 } else if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_2_0
)){
1100 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_2_0
.length());
1101 } else if (url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_1_2
)){
1102 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_1_2
.length());
1104 return (url
!= null ? url
: "");
1109 * Chooses the right icon and text to show to the user for the received operation result.
1111 * @param result Result of a remote operation performed in this activity
1113 private void updateServerStatusIconAndText(RemoteOperationResult result
) {
1114 mServerStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1116 switch (result
.getCode()) {
1118 mServerStatusIcon
= android
.R
.drawable
.ic_secure
;
1119 mServerStatusText
= R
.string
.auth_secure_connection
;
1124 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1125 mServerStatusText
= R
.string
.auth_connection_established
;
1126 mServerStatusIcon
= R
.drawable
.ic_ok
;
1128 mServerStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1129 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1133 case NO_NETWORK_CONNECTION
:
1134 mServerStatusIcon
= R
.drawable
.no_network
;
1135 mServerStatusText
= R
.string
.auth_no_net_conn_title
;
1138 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1139 mServerStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1141 case BAD_OC_VERSION
:
1142 mServerStatusText
= R
.string
.auth_bad_oc_version_title
;
1144 case WRONG_CONNECTION
:
1145 mServerStatusText
= R
.string
.auth_wrong_connection_title
;
1148 mServerStatusText
= R
.string
.auth_timeout_title
;
1150 case INCORRECT_ADDRESS
:
1151 mServerStatusText
= R
.string
.auth_incorrect_address_title
;
1154 mServerStatusText
= R
.string
.auth_ssl_general_error_title
;
1157 mServerStatusText
= R
.string
.auth_unauthorized
;
1159 case HOST_NOT_AVAILABLE
:
1160 mServerStatusText
= R
.string
.auth_unknown_host_title
;
1162 case INSTANCE_NOT_CONFIGURED
:
1163 mServerStatusText
= R
.string
.auth_not_configured_title
;
1165 case FILE_NOT_FOUND
:
1166 mServerStatusText
= R
.string
.auth_incorrect_path_title
;
1169 mServerStatusText
= R
.string
.auth_oauth_error
;
1171 case OAUTH2_ERROR_ACCESS_DENIED
:
1172 mServerStatusText
= R
.string
.auth_oauth_error_access_denied
;
1174 case UNHANDLED_HTTP_CODE
:
1176 mServerStatusText
= R
.string
.auth_unknown_error_title
;
1178 case OK_REDIRECT_TO_NON_SECURE_CONNECTION
:
1179 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1180 mServerStatusText
= R
.string
.auth_redirect_non_secure_connection_title
;
1183 mServerStatusText
= 0;
1184 mServerStatusIcon
= 0;
1190 * Chooses the right icon and text to show to the user for the received operation result.
1192 * @param result Result of a remote operation performed in this activity
1194 private void updateAuthStatusIconAndText(RemoteOperationResult result
) {
1195 mAuthStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1197 switch (result
.getCode()) {
1199 mAuthStatusIcon
= android
.R
.drawable
.ic_secure
;
1200 mAuthStatusText
= R
.string
.auth_secure_connection
;
1205 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1206 mAuthStatusText
= R
.string
.auth_connection_established
;
1207 mAuthStatusIcon
= R
.drawable
.ic_ok
;
1209 mAuthStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1210 mAuthStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1214 case NO_NETWORK_CONNECTION
:
1215 mAuthStatusIcon
= R
.drawable
.no_network
;
1216 mAuthStatusText
= R
.string
.auth_no_net_conn_title
;
1219 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1220 mAuthStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1222 case BAD_OC_VERSION
:
1223 mAuthStatusText
= R
.string
.auth_bad_oc_version_title
;
1225 case WRONG_CONNECTION
:
1226 mAuthStatusText
= R
.string
.auth_wrong_connection_title
;
1229 mAuthStatusText
= R
.string
.auth_timeout_title
;
1231 case INCORRECT_ADDRESS
:
1232 mAuthStatusText
= R
.string
.auth_incorrect_address_title
;
1235 mAuthStatusText
= R
.string
.auth_ssl_general_error_title
;
1238 mAuthStatusText
= R
.string
.auth_unauthorized
;
1240 case HOST_NOT_AVAILABLE
:
1241 mAuthStatusText
= R
.string
.auth_unknown_host_title
;
1243 case INSTANCE_NOT_CONFIGURED
:
1244 mAuthStatusText
= R
.string
.auth_not_configured_title
;
1246 case FILE_NOT_FOUND
:
1247 mAuthStatusText
= R
.string
.auth_incorrect_path_title
;
1250 mAuthStatusText
= R
.string
.auth_oauth_error
;
1252 case OAUTH2_ERROR_ACCESS_DENIED
:
1253 mAuthStatusText
= R
.string
.auth_oauth_error_access_denied
;
1255 case ACCOUNT_NOT_NEW
:
1256 mAuthStatusText
= R
.string
.auth_account_not_new
;
1258 case ACCOUNT_NOT_THE_SAME
:
1259 mAuthStatusText
= R
.string
.auth_account_not_the_same
;
1261 case UNHANDLED_HTTP_CODE
:
1263 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
1266 mAuthStatusText
= 0;
1267 mAuthStatusIcon
= 0;
1272 private void updateStatusIconFailUserName(){
1273 mAuthStatusIcon
= R
.drawable
.common_error
;
1274 mAuthStatusText
= R
.string
.auth_fail_get_user_name
;
1277 private void updateServerStatusIconNoRegularAuth(){
1278 mServerStatusIcon
= R
.drawable
.common_error
;
1279 mServerStatusText
= R
.string
.auth_can_not_auth_against_server
;
1283 * Processes the result of the request for and access token send
1284 * to an OAuth authorization server.
1286 * @param result Result of the operation.
1288 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result
) {
1289 mWaitingForOpId
= Long
.MAX_VALUE
;
1290 dismissDialog(WAIT_DIALOG_TAG
);
1292 if (result
.isSuccess()) {
1293 /// be gentle with the user
1294 IndeterminateProgressDialog dialog
=
1295 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
1296 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
1298 /// time to test the retrieved access token on the ownCloud server
1299 @SuppressWarnings("unchecked")
1300 Map
<String
, String
> tokens
= (Map
<String
, String
>)(result
.getData().get(0));
1301 mAuthToken
= tokens
.get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
1302 //mAuthToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Constants.KEY_ACCESS_TOKEN);
1303 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mAuthToken
);
1305 accessRootFolderRemoteOperation("", "");
1308 updateAuthStatusIconAndText(result
);
1310 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1316 * Processes the result of the access check performed to try the user credentials.
1318 * Creates a new account through the AccountManager.
1320 * @param operation Access check performed.
1321 * @param result Result of the operation.
1323 private void onAuthorizationCheckFinish(RemoteOperationResult result
) {
1324 mWaitingForOpId
= Long
.MAX_VALUE
;
1325 dismissDialog(WAIT_DIALOG_TAG
);
1327 if (result
.isSuccess()) {
1328 Log_OC
.d(TAG
, "Successful access - time to save the account");
1330 boolean success
= false
;
1331 if (mAction
== ACTION_CREATE
) {
1332 success
= createAccount();
1343 } else if (result
.isServerFail() || result
.isException()) {
1344 /// server errors or exceptions in authorization take to requiring a new check of
1346 mServerIsChecked
= true
;
1347 mServerIsValid
= false
;
1348 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
1350 // update status icon and text
1351 updateServerStatusIconAndText(result
);
1353 mAuthStatusIcon
= 0;
1354 mAuthStatusText
= 0;
1357 // update input controls state
1358 showRefreshButton(true
);
1359 mOkButton
.setEnabled(false
);
1361 // very special case (TODO: move to a common place for all the remote operations) (dangerous here?)
1362 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1363 showUntrustedCertDialog(result
);
1366 } else { // authorization fail due to client side - probably wrong credentials
1367 updateAuthStatusIconAndText(result
);
1369 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1377 * Sets the proper response to get that the Account Authenticator that started this activity saves
1378 * a new authorization token for mAccount.
1380 private void updateToken() {
1381 Bundle response
= new Bundle();
1382 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1383 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
1385 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
1386 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1387 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1388 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1390 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
1392 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1393 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1394 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1397 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
1398 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
1400 setAccountAuthenticatorResult(response
);
1406 * Creates a new account through the Account Authenticator that started this activity.
1408 * This makes the account permanent.
1410 * TODO Decide how to name the OAuth accounts
1412 private boolean createAccount() {
1413 /// create and save new ownCloud account
1414 boolean isOAuth
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
);
1415 boolean isSaml
= AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
);
1417 Uri uri
= Uri
.parse(mServerInfo
.mBaseUrl
);
1418 String username
= mUsernameInput
.getText().toString().trim();
1420 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1422 String accountName
= com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.
1423 buildAccountName(uri
, username
);
1424 Account newAccount
= new Account(accountName
, MainApp
.getAccountType());
1425 if (AccountUtils
.exists(newAccount
, getApplicationContext())) {
1426 // fail - not a new account, but an existing one; disallow
1427 RemoteOperationResult result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_NEW
);
1428 updateAuthStatusIconAndText(result
);
1430 Log_OC
.d(TAG
, result
.getLogMessage());
1434 mAccount
= newAccount
;
1436 if (isOAuth
|| isSaml
) {
1437 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
); // with external authorizations, the password is never input in the app
1439 mAccountMgr
.addAccountExplicitly(mAccount
, mPasswordInput
.getText().toString(), null
);
1442 /// add the new account as default in preferences, if there is none already
1443 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1444 if (defaultAccount
== null
) {
1445 SharedPreferences
.Editor editor
= PreferenceManager
1446 .getDefaultSharedPreferences(this).edit();
1447 editor
.putString("select_oc_account", accountName
);
1451 /// prepare result to return to the Authenticator
1452 // TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done
1453 final Intent intent
= new Intent();
1454 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, MainApp
.getAccountType());
1455 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1457 intent.putExtra(AccountManager.KEY_AUTHTOKEN, MainApp.getAccountType()); */
1458 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1459 if (isOAuth
|| isSaml
) {
1460 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1462 /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
1463 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion());
1464 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_OC_BASE_URL
, mServerInfo
.mBaseUrl
);
1467 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
, "TRUE");
1468 } else if (isOAuth
) {
1469 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
, "TRUE");
1472 setAccountAuthenticatorResult(intent
.getExtras());
1473 setResult(RESULT_OK
, intent
);
1481 * Starts and activity to open the 'new account' page in the ownCloud web site
1483 * @param view 'Account register' button
1485 public void onRegisterClick(View view
) {
1486 Intent register
= new Intent(Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.welcome_link_url
)));
1487 setResult(RESULT_CANCELED
);
1488 startActivity(register
);
1493 * Updates the content and visibility state of the icon and text associated
1494 * to the last check on the ownCloud server.
1496 * @param serverStatusText Resource identifier of the text to show.
1497 * @param serverStatusIcon Resource identifier of the icon to show.
1499 private void showServerStatus() {
1500 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1501 mServerStatusView
.setVisibility(View
.INVISIBLE
);
1504 mServerStatusView
.setText(mServerStatusText
);
1505 mServerStatusView
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1506 mServerStatusView
.setVisibility(View
.VISIBLE
);
1513 * Updates the content and visibility state of the icon and text associated
1514 * to the interactions with the OAuth authorization server.
1516 private void showAuthStatus() {
1517 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1518 mAuthStatusView
.setVisibility(View
.INVISIBLE
);
1521 mAuthStatusView
.setText(mAuthStatusText
);
1522 mAuthStatusView
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1523 mAuthStatusView
.setVisibility(View
.VISIBLE
);
1528 private void showRefreshButton (boolean show
) {
1530 mRefreshButton
.setVisibility(View
.VISIBLE
);
1532 mRefreshButton
.setVisibility(View
.GONE
);
1537 * Called when the refresh button in the input field for ownCloud host is clicked.
1539 * Performs a new check on the URL in the input field.
1541 * @param view Refresh 'button'
1543 public void onRefreshClick(View view
) {
1549 * Called when the eye icon in the password field is clicked.
1551 * Toggles the visibility of the password in the field.
1553 public void onViewPasswordClick() {
1554 int selectionStart
= mPasswordInput
.getSelectionStart();
1555 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1556 if (isPasswordVisible()) {
1561 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1566 * Called when the checkbox for OAuth authorization is clicked.
1568 * Hides or shows the input fields for user & password.
1570 * @param view 'View password' 'button'
1572 public void onCheckClick(View view
) {
1573 CheckBox oAuth2Check
= (CheckBox
)view
;
1574 if (oAuth2Check
.isChecked()) {
1575 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1577 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1579 updateAuthenticationPreFragmentVisibility();
1584 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1586 * Used to trigger the authentication check when the user presses 'enter' after writing the password,
1587 * or to throw the server test when the only field on screen is the URL input field.
1590 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1591 if (actionId
== EditorInfo
.IME_ACTION_DONE
&& inputField
!= null
&& inputField
.equals(mPasswordInput
)) {
1592 if (mOkButton
.isEnabled()) {
1593 mOkButton
.performClick();
1596 } else if (actionId
== EditorInfo
.IME_ACTION_NEXT
&& inputField
!= null
&& inputField
.equals(mHostUrlInput
)) {
1597 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
1601 return false
; // always return false to grant that the software keyboard is hidden anyway
1605 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1607 private int fuzz
= 75;
1613 public boolean onTouch(View view
, MotionEvent event
) {
1614 Drawable rightDrawable
= null
;
1615 if (view
instanceof TextView
) {
1616 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1617 if (drawables
.length
> 2) {
1618 rightDrawable
= drawables
[2];
1621 if (rightDrawable
!= null
) {
1622 final int x
= (int) event
.getX();
1623 final int y
= (int) event
.getY();
1624 final Rect bounds
= rightDrawable
.getBounds();
1625 if (x
>= (view
.getRight() - bounds
.width() - fuzz
) && x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
)
1626 && y
>= (view
.getPaddingTop() - fuzz
) && y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1628 return onDrawableTouch(event
);
1634 public abstract boolean onDrawableTouch(final MotionEvent event
);
1638 private void getRemoteUserNameOperation(String sessionCookie
, boolean followRedirects
) {
1640 Intent getUserNameIntent
= new Intent();
1641 getUserNameIntent
.setAction(OperationsService
.ACTION_GET_USER_NAME
);
1642 getUserNameIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
1643 getUserNameIntent
.putExtra(OperationsService
.EXTRA_COOKIE
, sessionCookie
);
1645 if (mOperationsServiceBinder
!= null
) {
1646 //Log_OC.wtf(TAG, "starting getRemoteUserNameOperation..." );
1647 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(getUserNameIntent
);
1653 public void onSsoFinished(String sessionCookie
) {
1654 if (sessionCookie
!= null
&& sessionCookie
.length() > 0) {
1655 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1656 mAuthToken
= sessionCookie
;
1657 getRemoteUserNameOperation(sessionCookie
, true
);
1658 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1659 if (fd
!= null
&& fd
instanceof SherlockDialogFragment
) {
1660 Dialog d
= ((SherlockDialogFragment
)fd
).getDialog();
1661 if (d
!= null
&& d
.isShowing()) {
1668 Log_OC
.d(TAG
, "SSO failed");
1674 public boolean onTouchEvent(MotionEvent event
) {
1675 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
) &&
1676 mHostUrlInput
.hasFocus() && event
.getAction() == MotionEvent
.ACTION_DOWN
) {
1679 return super.onTouchEvent(event
);
1684 * Show untrusted cert dialog
1686 public void showUntrustedCertDialog(X509Certificate x509Certificate
, SslError error
, SslErrorHandler handler
) {
1687 // Show a dialog with the certificate info
1688 SslUntrustedCertDialog dialog
= null
;
1689 if (x509Certificate
== null
) {
1690 dialog
= SslUntrustedCertDialog
.newInstanceForEmptySslError(error
, handler
);
1692 dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(x509Certificate
, error
, handler
);
1694 FragmentManager fm
= getSupportFragmentManager();
1695 FragmentTransaction ft
= fm
.beginTransaction();
1696 ft
.addToBackStack(null
);
1697 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1702 * Show untrusted cert dialog
1704 private void showUntrustedCertDialog(RemoteOperationResult result
) {
1705 // Show a dialog with the certificate info
1706 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1707 FragmentManager fm
= getSupportFragmentManager();
1708 FragmentTransaction ft
= fm
.beginTransaction();
1709 ft
.addToBackStack(null
);
1710 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1715 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1717 public void onSavedCertificate() {
1718 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1720 // if SAML dialog is not shown, the SslDialog was shown due to an SSL error in the server check
1726 * Called from SslValidatorDialog when a new server certificate could not be saved
1727 * when the user requested it.
1730 public void onFailedSavingCertificate() {
1731 dismissDialog(SAML_DIALOG_TAG
);
1732 Toast
.makeText(this, R
.string
.ssl_validator_not_saved
, Toast
.LENGTH_LONG
).show();
1736 public void onCancelCertificate() {
1737 dismissDialog(SAML_DIALOG_TAG
);
1741 private void doOnResumeAndBound() {
1742 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1743 mOperationsServiceBinder
.addOperationListener(AuthenticatorActivity
.this, mHandler
);
1744 if (mWaitingForOpId
<= Integer
.MAX_VALUE
) {
1745 mOperationsServiceBinder
.dispatchResultIfFinished((int)mWaitingForOpId
, this);
1748 if (mPendingAutoCheck
) {
1754 private void dismissDialog(String dialogTag
){
1755 Fragment frag
= getSupportFragmentManager().findFragmentByTag(dialogTag
);
1756 if (frag
!= null
&& frag
instanceof SherlockDialogFragment
) {
1757 SherlockDialogFragment dialog
= (SherlockDialogFragment
) frag
;
1764 * Implements callback methods for service binding.
1766 private class OperationsServiceConnection
implements ServiceConnection
{
1769 public void onServiceConnected(ComponentName component
, IBinder service
) {
1770 if (component
.equals(new ComponentName(AuthenticatorActivity
.this, OperationsService
.class))) {
1771 //Log_OC.wtf(TAG, "Operations service connected");
1772 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
1774 doOnResumeAndBound();
1783 public void onServiceDisconnected(ComponentName component
) {
1784 if (component
.equals(new ComponentName(AuthenticatorActivity
.this, OperationsService
.class))) {
1785 Log_OC
.e(TAG
, "Operations service crashed");
1786 mOperationsServiceBinder
= null
;
1793 * Create and show dialog for request authentication to the user
1797 public void createAuthenticationDialog(WebView webView
, HttpAuthHandler handler
) {
1799 // Show a dialog with the certificate info
1800 CredentialsDialogFragment dialog
= CredentialsDialogFragment
.newInstanceForCredentials(webView
, handler
);
1801 FragmentManager fm
= getSupportFragmentManager();
1802 FragmentTransaction ft
= fm
.beginTransaction();
1803 ft
.addToBackStack(null
);
1804 dialog
.setCancelable(false
);
1805 dialog
.show(ft
, CREDENTIALS_DIALOG_TAG
);
1807 if (!mIsFirstAuthAttempt
) {
1808 Toast
.makeText(getApplicationContext(), getText(R
.string
.saml_authentication_wrong_pass
), Toast
.LENGTH_LONG
).show();
1810 mIsFirstAuthAttempt
= false
;
1815 * For retrieving the clicking on authentication cancel button
1817 public void doNegativeAuthenticatioDialogClick(){
1818 mIsFirstAuthAttempt
= true
;