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
.SslErrorHandler
;
54 import android
.widget
.Button
;
55 import android
.widget
.CheckBox
;
56 import android
.widget
.EditText
;
57 import android
.widget
.TextView
;
58 import android
.widget
.TextView
.OnEditorActionListener
;
59 import android
.widget
.Toast
;
61 import com
.actionbarsherlock
.app
.SherlockDialogFragment
;
62 import com
.owncloud
.android
.MainApp
;
63 import com
.owncloud
.android
.R
;
64 import com
.owncloud
.android
.authentication
.SsoWebViewClient
.SsoWebViewClientListener
;
65 import com
.owncloud
.android
.lib
.common
.accounts
.AccountTypeUtils
;
66 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.Constants
;
67 import com
.owncloud
.android
.operations
.DetectAuthenticationMethodOperation
.AuthenticationMethod
;
68 import com
.owncloud
.android
.operations
.GetServerInfoOperation
;
69 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
71 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
72 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
73 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
74 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
75 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
76 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
77 import com
.owncloud
.android
.lib
.resources
.users
.GetRemoteUserNameOperation
;
79 import com
.owncloud
.android
.services
.OperationsService
;
80 import com
.owncloud
.android
.services
.OperationsService
.OperationsServiceBinder
;
81 import com
.owncloud
.android
.ui
.dialog
.IndeterminateProgressDialog
;
82 import com
.owncloud
.android
.ui
.dialog
.SamlWebViewDialog
;
83 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
84 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
85 import com
.owncloud
.android
.utils
.Log_OC
;
86 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
89 * This Activity is used to add an ownCloud account to the App
91 * @author Bartek Przybylski
92 * @author David A. Velasco
95 public class AuthenticatorActivity
extends AccountAuthenticatorActivity
96 implements OnRemoteOperationListener
, OnFocusChangeListener
, OnEditorActionListener
,
97 SsoWebViewClientListener
, OnSslUntrustedCertListener
{
99 private static final String TAG
= AuthenticatorActivity
.class.getSimpleName();
101 public static final String EXTRA_ACTION
= "ACTION";
102 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
104 private static final String KEY_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
106 private static final String KEY_HOST_URL_TEXT
= "HOST_URL_TEXT";
107 private static final String KEY_OC_VERSION
= "OC_VERSION";
108 private static final String KEY_SERVER_VALID
= "SERVER_VALID";
109 private static final String KEY_SERVER_CHECKED
= "SERVER_CHECKED";
110 private static final String KEY_SERVER_STATUS_TEXT
= "SERVER_STATUS_TEXT";
111 private static final String KEY_SERVER_STATUS_ICON
= "SERVER_STATUS_ICON";
112 private static final String KEY_IS_SSL_CONN
= "IS_SSL_CONN";
113 private static final String KEY_PASSWORD_EXPOSED
= "PASSWORD_VISIBLE";
114 private static final String KEY_AUTH_STATUS_TEXT
= "AUTH_STATUS_TEXT";
115 private static final String KEY_AUTH_STATUS_ICON
= "AUTH_STATUS_ICON";
116 private static final String KEY_SERVER_AUTH_METHOD
= "SERVER_AUTH_METHOD";
117 private static final String KEY_WAITING_FOR_OP_ID
= "WAITING_FOR_OP_ID";
118 private static final String KEY_AUTH_TOKEN
= "AUTH_TOKEN";
120 private static final String AUTH_ON
= "on";
121 private static final String AUTH_OPTIONAL
= "optional";
123 public static final byte ACTION_CREATE
= 0;
124 public static final byte ACTION_UPDATE_TOKEN
= 1; // requested by the user
125 public static final byte ACTION_UPDATE_EXPIRED_TOKEN
= 2; // detected by the app
127 private static final String UNTRUSTED_CERT_DIALOG_TAG
= "UNTRUSTED_CERT_DIALOG";
128 private static final String SAML_DIALOG_TAG
= "SAML_DIALOG";
129 private static final String WAIT_DIALOG_TAG
= "WAIT_DIALOG";
132 /// parameters from EXTRAs in starter Intent
133 private byte mAction
;
134 private Account mAccount
;
135 private String mAuthTokenType
;
138 /// activity-level references / state
139 private final Handler mHandler
= new Handler();
140 private ServiceConnection mOperationsServiceConnection
= null
;
141 private OperationsServiceBinder mOperationsServiceBinder
= null
;
142 private AccountManager mAccountMgr
;
143 private Uri mNewCapturedUriFromOAuth2Redirection
;
146 /// Server PRE-Fragment elements
147 private EditText mHostUrlInput
;
148 private View mRefreshButton
;
149 private TextView mServerStatusView
;
151 private TextWatcher mHostUrlInputWatcher
;
152 private int mServerStatusText
= 0, mServerStatusIcon
= 0;
154 private boolean mServerIsChecked
= false
;
155 private boolean mServerIsValid
= false
;
156 private boolean mPendingAutoCheck
= false
;
158 private GetServerInfoOperation
.ServerInfo mServerInfo
=
159 new GetServerInfoOperation
.ServerInfo();
162 /// Authentication PRE-Fragment elements
163 private CheckBox mOAuth2Check
;
164 private TextView mOAuthAuthEndpointText
;
165 private TextView mOAuthTokenEndpointText
;
166 private EditText mUsernameInput
;
167 private EditText mPasswordInput
;
168 private View mOkButton
;
169 private TextView mAuthStatusView
;
171 private int mAuthStatusText
= 0, mAuthStatusIcon
= 0;
173 private String mAuthToken
= "";
176 /// Identifier of operation in progress which result shouldn't be lost
177 private long mWaitingForOpId
= Long
.MAX_VALUE
;
183 * IMPORTANT ENTRY POINT 1: activity is shown to the user
186 protected void onCreate(Bundle savedInstanceState
) {
187 //Log_OC.wtf(TAG, "onCreate init");
188 super.onCreate(savedInstanceState
);
189 getWindow().requestFeature(Window
.FEATURE_NO_TITLE
);
191 // bind to Operations Service
192 mOperationsServiceConnection
= new OperationsServiceConnection();
193 if (!bindService(new Intent(this, OperationsService
.class),
194 mOperationsServiceConnection
,
195 Context
.BIND_AUTO_CREATE
)) {
197 R
.string
.error_cant_bind_to_operations_service
,
203 /// init activity state
204 mAccountMgr
= AccountManager
.get(this);
205 mNewCapturedUriFromOAuth2Redirection
= null
;
208 mAction
= getIntent().getByteExtra(EXTRA_ACTION
, ACTION_CREATE
);
209 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
210 if (savedInstanceState
== null
) {
213 mAuthTokenType
= savedInstanceState
.getString(KEY_AUTH_TOKEN_TYPE
);
214 mWaitingForOpId
= savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
);
217 /// load user interface
218 setContentView(R
.layout
.account_setup
);
220 /// initialize general UI elements
221 initOverallUi(savedInstanceState
);
223 mOkButton
= findViewById(R
.id
.buttonOK
);
225 /// initialize block to be moved to single Fragment to check server and get info about it
226 initServerPreFragment(savedInstanceState
);
228 /// initialize block to be moved to single Fragment to retrieve and validate credentials
229 initAuthorizationPreFragment(savedInstanceState
);
231 //Log_OC.wtf(TAG, "onCreate end");
234 private void initAuthTokenType() {
236 getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
237 if (mAuthTokenType
== null
) {
238 if (mAccount
!= null
) {
239 boolean oAuthRequired
=
240 (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
) != null
);
241 boolean samlWebSsoRequired
=
242 (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
) != null
);
243 mAuthTokenType
= chooseAuthTokenType(oAuthRequired
, samlWebSsoRequired
);
246 boolean oAuthSupported
= AUTH_ON
.equals(getString(R
.string
.auth_method_oauth2
));
247 boolean samlWebSsoSupported
= AUTH_ON
.equals(getString(R
.string
.auth_method_saml_web_sso
));
248 mAuthTokenType
= chooseAuthTokenType(oAuthSupported
, samlWebSsoSupported
);
253 private String
chooseAuthTokenType(boolean oauth
, boolean saml
) {
255 return AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
257 return AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
259 return AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
265 * Configures elements in the user interface under direct control of the Activity.
267 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
269 private void initOverallUi(Bundle savedInstanceState
) {
271 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
272 boolean isWelcomeLinkVisible
= getResources().getBoolean(R
.bool
.show_welcome_link
);
274 String instructionsMessageText
= null
;
275 if (mAction
== ACTION_UPDATE_EXPIRED_TOKEN
) {
276 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
277 .equals(mAuthTokenType
)) {
278 instructionsMessageText
= getString(R
.string
.auth_expired_oauth_token_toast
);
280 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType())
281 .equals(mAuthTokenType
)) {
282 instructionsMessageText
= getString(R
.string
.auth_expired_saml_sso_token_toast
);
285 instructionsMessageText
= getString(R
.string
.auth_expired_basic_auth_toast
);
289 /// step 2 - set properties of UI elements (text, visibility, enabled...)
290 Button welcomeLink
= (Button
) findViewById(R
.id
.welcome_link
);
291 welcomeLink
.setVisibility(isWelcomeLinkVisible ? View
.VISIBLE
: View
.GONE
);
293 String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
295 TextView instructionsView
= (TextView
) findViewById(R
.id
.instructions_message
);
296 if (instructionsMessageText
!= null
) {
297 instructionsView
.setVisibility(View
.VISIBLE
);
298 instructionsView
.setText(instructionsMessageText
);
300 instructionsView
.setVisibility(View
.GONE
);
307 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
309 private void initServerPreFragment(Bundle savedInstanceState
) {
311 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
312 boolean isUrlInputAllowed
= getResources().getBoolean(R
.bool
.show_server_url_input
);
313 if (savedInstanceState
== null
) {
314 if (mAccount
!= null
) {
315 mServerInfo
.mBaseUrl
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_BASE_URL
);
316 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://"); // TODO do this in a setter for mBaseUrl
317 String ocVersion
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_VERSION
);
318 if (ocVersion
!= null
) {
319 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
322 mServerInfo
.mBaseUrl
= getString(R
.string
.server_url
).trim();
323 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
326 mServerStatusText
= savedInstanceState
.getInt(KEY_SERVER_STATUS_TEXT
);
327 mServerStatusIcon
= savedInstanceState
.getInt(KEY_SERVER_STATUS_ICON
);
329 mServerIsValid
= savedInstanceState
.getBoolean(KEY_SERVER_VALID
);
330 mServerIsChecked
= savedInstanceState
.getBoolean(KEY_SERVER_CHECKED
);
333 mServerInfo
.mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
334 mServerInfo
.mBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
335 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
336 if (ocVersion
!= null
) {
337 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
339 mServerInfo
.mAuthMethod
= AuthenticationMethod
.valueOf(
340 savedInstanceState
.getString(KEY_SERVER_AUTH_METHOD
));
344 /// step 2 - set properties of UI elements (text, visibility, enabled...)
345 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
346 mHostUrlInput
.setText(mServerInfo
.mBaseUrl
);
347 if (mAction
!= ACTION_CREATE
) {
348 /// lock things that should not change
349 mHostUrlInput
.setEnabled(false
);
350 mHostUrlInput
.setFocusable(false
);
352 if (isUrlInputAllowed
) {
353 mRefreshButton
= findViewById(R
.id
.embeddedRefreshButton
);
355 findViewById(R
.id
.hostUrlFrame
).setVisibility(View
.GONE
);
356 mRefreshButton
= findViewById(R
.id
.centeredRefreshButton
);
358 showRefreshButton(mServerIsChecked
&& !mServerIsValid
&&
359 mWaitingForOpId
> Integer
.MAX_VALUE
);
360 mServerStatusView
= (TextView
) findViewById(R
.id
.server_status_text
);
363 /// step 3 - bind some listeners and options
364 mHostUrlInput
.setImeOptions(EditorInfo
.IME_ACTION_NEXT
);
365 mHostUrlInput
.setOnEditorActionListener(this);
367 /// step 4 - create listeners that will be bound at onResume
368 mHostUrlInputWatcher
= new TextWatcher() {
371 public void afterTextChanged(Editable s
) {
372 if (mOkButton
.isEnabled() &&
373 !mServerInfo
.mBaseUrl
.equals(
374 normalizeUrl(s
.toString(), mServerInfo
.mIsSslConn
))) {
375 mOkButton
.setEnabled(false
);
380 public void beforeTextChanged(CharSequence s
, int start
, int count
, int after
) {
384 public void onTextChanged(CharSequence s
, int start
, int before
, int count
) {
385 if (mAuthStatusIcon
!= 0) {
386 Log_OC
.d(TAG
, "onTextChanged: hiding authentication status");
395 // TODO find out if this is really necessary, or if it can done in a different way
396 findViewById(R
.id
.scroll
).setOnTouchListener(new OnTouchListener() {
398 public boolean onTouch(View view
, MotionEvent event
) {
399 if (event
.getAction() == MotionEvent
.ACTION_DOWN
) {
400 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
) &&
401 mHostUrlInput
.hasFocus()) {
410 /// step 4 - mark automatic check to be started when OperationsService is ready
411 mPendingAutoCheck
= (savedInstanceState
== null
&&
412 (mAction
!= ACTION_CREATE
|| !isUrlInputAllowed
));
418 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
420 private void initAuthorizationPreFragment(Bundle savedInstanceState
) {
422 /// step 0 - get UI elements in layout
423 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
424 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
425 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
426 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
427 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
428 mAuthStatusView
= (TextView
) findViewById(R
.id
.auth_status_text
);
430 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
431 String presetUserName
= null
;
432 boolean isPasswordExposed
= false
;
433 if (savedInstanceState
== null
) {
434 if (mAccount
!= null
) {
435 presetUserName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
439 isPasswordExposed
= savedInstanceState
.getBoolean(KEY_PASSWORD_EXPOSED
, false
);
440 mAuthStatusText
= savedInstanceState
.getInt(KEY_AUTH_STATUS_TEXT
);
441 mAuthStatusIcon
= savedInstanceState
.getInt(KEY_AUTH_STATUS_ICON
);
442 mAuthToken
= savedInstanceState
.getString(KEY_AUTH_TOKEN
);
445 /// step 2 - set properties of UI elements (text, visibility, enabled...)
446 mOAuth2Check
.setChecked(
447 AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
448 .equals(mAuthTokenType
));
449 if (presetUserName
!= null
) {
450 mUsernameInput
.setText(presetUserName
);
452 if (mAction
!= ACTION_CREATE
) {
453 mUsernameInput
.setEnabled(false
);
454 mUsernameInput
.setFocusable(false
);
456 mPasswordInput
.setText(""); // clean password to avoid social hacking
457 if (isPasswordExposed
) {
460 updateAuthenticationPreFragmentVisibility();
462 mOkButton
.setEnabled(mServerIsValid
);
465 /// step 3 - bind listeners
466 // bindings for password input field
467 mPasswordInput
.setOnFocusChangeListener(this);
468 mPasswordInput
.setImeOptions(EditorInfo
.IME_ACTION_DONE
);
469 mPasswordInput
.setOnEditorActionListener(this);
470 mPasswordInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
472 public boolean onDrawableTouch(final MotionEvent event
) {
473 if (event
.getAction() == MotionEvent
.ACTION_UP
) {
474 AuthenticatorActivity
.this.onViewPasswordClick();
484 * Changes the visibility of input elements depending on
485 * the current authorization method.
487 private void updateAuthenticationPreFragmentVisibility () {
488 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
489 equals(mAuthTokenType
)) {
490 // SAML-based web Single Sign On
491 mOAuth2Check
.setVisibility(View
.GONE
);
492 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
493 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
494 mUsernameInput
.setVisibility(View
.GONE
);
495 mPasswordInput
.setVisibility(View
.GONE
);
498 if (mAction
== ACTION_CREATE
&&
499 AUTH_OPTIONAL
.equals(getString(R
.string
.auth_method_oauth2
))) {
500 mOAuth2Check
.setVisibility(View
.VISIBLE
);
502 mOAuth2Check
.setVisibility(View
.GONE
);
505 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
506 equals(mAuthTokenType
)) {
507 // OAuth 2 authorization
509 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
510 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
511 mUsernameInput
.setVisibility(View
.GONE
);
512 mPasswordInput
.setVisibility(View
.GONE
);
515 // basic HTTP authorization
516 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
517 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
518 mUsernameInput
.setVisibility(View
.VISIBLE
);
519 mPasswordInput
.setVisibility(View
.VISIBLE
);
527 * Saves relevant state before {@link #onPause()}
529 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag, intended to defer the
530 * processing of the redirection caught in {@link #onNewIntent(Intent)} until {@link #onResume()}
532 * See {@link #loadSavedInstanceState(Bundle)}
535 protected void onSaveInstanceState(Bundle outState
) {
536 //Log_OC.wtf(TAG, "onSaveInstanceState init" );
537 super.onSaveInstanceState(outState
);
540 outState
.putString(KEY_AUTH_TOKEN_TYPE
, mAuthTokenType
);
541 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mWaitingForOpId
);
543 /// Server PRE-fragment state
544 outState
.putInt(KEY_SERVER_STATUS_TEXT
, mServerStatusText
);
545 outState
.putInt(KEY_SERVER_STATUS_ICON
, mServerStatusIcon
);
546 outState
.putBoolean(KEY_SERVER_CHECKED
, mServerIsChecked
);
547 outState
.putBoolean(KEY_SERVER_VALID
, mServerIsValid
);
548 outState
.putBoolean(KEY_IS_SSL_CONN
, mServerInfo
.mIsSslConn
);
549 outState
.putString(KEY_HOST_URL_TEXT
, mServerInfo
.mBaseUrl
);
550 if (mServerInfo
.mVersion
!= null
) {
551 outState
.putString(KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion());
553 outState
.putString(KEY_SERVER_AUTH_METHOD
, mServerInfo
.mAuthMethod
.name());
555 /// Authentication PRE-fragment state
556 outState
.putBoolean(KEY_PASSWORD_EXPOSED
, isPasswordVisible());
557 outState
.putInt(KEY_AUTH_STATUS_ICON
, mAuthStatusIcon
);
558 outState
.putInt(KEY_AUTH_STATUS_TEXT
, mAuthStatusText
);
559 outState
.putString(KEY_AUTH_TOKEN
, mAuthToken
);
561 //Log_OC.wtf(TAG, "onSaveInstanceState end" );
566 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION request
569 * To make this possible, this activity needs to be qualified with android:launchMode = "singleTask" in the
570 * AndroidManifest.xml file.
573 protected void onNewIntent (Intent intent
) {
574 Log_OC
.d(TAG
, "onNewIntent()");
575 Uri data
= intent
.getData();
576 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
577 mNewCapturedUriFromOAuth2Redirection
= data
;
583 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION, and
584 * deferred in {@link #onNewIntent(Intent)}, is processed here.
587 protected void onResume() {
588 //Log_OC.wtf(TAG, "onResume init" );
591 // bound here to avoid spurious changes triggered by Android on device rotations
592 mHostUrlInput
.setOnFocusChangeListener(this);
593 mHostUrlInput
.addTextChangedListener(mHostUrlInputWatcher
);
595 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
596 getOAuth2AccessTokenFromCapturedRedirection();
599 if (mOperationsServiceBinder
!= null
) {
600 doOnResumeAndBound();
603 //Log_OC.wtf(TAG, "onResume end" );
608 protected void onPause() {
609 //Log_OC.wtf(TAG, "onPause init" );
610 if (mOperationsServiceBinder
!= null
) {
611 //Log_OC.wtf(TAG, "unregistering to listen for operation callbacks" );
612 mOperationsServiceBinder
.removeOperationListener(this);
615 mHostUrlInput
.removeTextChangedListener(mHostUrlInputWatcher
);
616 mHostUrlInput
.setOnFocusChangeListener(null
);
619 //Log_OC.wtf(TAG, "onPause end" );
623 protected void onDestroy() {
625 mHostUrlInputWatcher
= null
;
627 if (mOperationsServiceConnection
!= null
) {
628 unbindService(mOperationsServiceConnection
);
629 mOperationsServiceBinder
= null
;
636 * Parses the redirection with the response to the GET AUTHORIZATION request to the
637 * oAuth server and requests for the access token (GET ACCESS TOKEN)
639 private void getOAuth2AccessTokenFromCapturedRedirection() {
640 /// Parse data from OAuth redirection
641 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
642 mNewCapturedUriFromOAuth2Redirection
= null
;
644 /// Showing the dialog with instructions for the user.
645 IndeterminateProgressDialog dialog
=
646 IndeterminateProgressDialog
.newInstance(R
.string
.auth_getting_authorization
, true
);
647 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
649 /// GET ACCESS TOKEN to the oAuth server
650 Intent getServerInfoIntent
= new Intent();
651 getServerInfoIntent
.setAction(OperationsService
.ACTION_OAUTH2_GET_ACCESS_TOKEN
);
653 getServerInfoIntent
.putExtra(
654 OperationsService
.EXTRA_SERVER_URL
,
655 mOAuthTokenEndpointText
.getText().toString().trim());
657 getServerInfoIntent
.putExtra(
658 OperationsService
.EXTRA_OAUTH2_QUERY_PARAMETERS
,
661 if (mOperationsServiceBinder
!= null
) {
662 //Log_OC.wtf(TAG, "getting access token..." );
663 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(getServerInfoIntent
);
670 * Handles the change of focus on the text inputs for the server URL and the password
672 public void onFocusChange(View view
, boolean hasFocus
) {
673 if (view
.getId() == R
.id
.hostUrlInput
) {
675 onUrlInputFocusLost((TextView
) view
);
678 showRefreshButton(false
);
681 } else if (view
.getId() == R
.id
.account_password
) {
682 onPasswordFocusChanged((TextView
) view
, hasFocus
);
688 * Handles changes in focus on the text input for the server URL.
690 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
691 * other field. The operation to check the existence of the server in the entered URL is
694 * When hasFocus: user 'comes back' to write again the server URL.
696 * @param hostInput TextView with the URL input field receiving the change of focus.
698 private void onUrlInputFocusLost(TextView hostInput
) {
699 if (!mServerInfo
.mBaseUrl
.equals(
700 normalizeUrl(mHostUrlInput
.getText().toString(), mServerInfo
.mIsSslConn
))) {
701 // check server again only if the user changed something in the field
704 mOkButton
.setEnabled(mServerIsValid
);
705 showRefreshButton(!mServerIsValid
);
710 private void checkOcServer() {
711 String uri
= mHostUrlInput
.getText().toString().trim();
712 mServerIsValid
= false
;
713 mServerIsChecked
= false
;
714 mOkButton
.setEnabled(false
);
715 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
716 showRefreshButton(false
);
718 if (uri
.length() != 0) {
719 mServerStatusText
= R
.string
.auth_testing_connection
;
720 mServerStatusIcon
= R
.drawable
.progress_small
;
723 Intent getServerInfoIntent
= new Intent();
724 getServerInfoIntent
.setAction(OperationsService
.ACTION_GET_SERVER_INFO
);
725 getServerInfoIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, uri
);
726 getServerInfoIntent
.putExtra(OperationsService
.EXTRA_AUTH_TOKEN_TYPE
, mAuthTokenType
);
727 if (mOperationsServiceBinder
!= null
) {
728 //Log_OC.wtf(TAG, "checking server..." );
729 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(getServerInfoIntent
);
731 Log_OC
.wtf(TAG
, "Server check tried with OperationService unbound!" );
735 mServerStatusText
= 0;
736 mServerStatusIcon
= 0;
743 * Handles changes in focus on the text input for the password (basic authorization).
745 * When (hasFocus), the button to toggle password visibility is shown.
747 * When (!hasFocus), the button is made invisible and the password is hidden.
749 * @param passwordInput TextView with the password input field receiving the change of focus.
750 * @param hasFocus 'True' if focus is received, 'false' if is lost
752 private void onPasswordFocusChanged(TextView passwordInput
, boolean hasFocus
) {
754 showViewPasswordButton();
757 hidePasswordButton();
762 private void showViewPasswordButton() {
763 int drawable
= R
.drawable
.ic_view
;
764 if (isPasswordVisible()) {
765 drawable
= R
.drawable
.ic_hide
;
767 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable
, 0);
770 private boolean isPasswordVisible() {
771 return ((mPasswordInput
.getInputType() & InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) == InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
774 private void hidePasswordButton() {
775 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
778 private void showPassword() {
779 mPasswordInput
.setInputType(InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
780 showViewPasswordButton();
783 private void hidePassword() {
784 mPasswordInput
.setInputType(InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
);
785 showViewPasswordButton();
789 * Checks the credentials of the user in the root of the ownCloud server
790 * before creating a new local account.
792 * For basic authorization, a check of existence of the root folder is
795 * For OAuth, starts the flow to get an access token; the credentials test
796 * is postponed until it is available.
798 * IMPORTANT ENTRY POINT 4
800 * @param view OK button
802 public void onOkClick(View view
) {
803 // this check should be unnecessary
804 if (mServerInfo
.mVersion
== null
||
805 !mServerInfo
.mVersion
.isVersionValid() ||
806 mServerInfo
.mBaseUrl
== null
||
807 mServerInfo
.mBaseUrl
.length() == 0) {
808 mServerStatusIcon
= R
.drawable
.common_error
;
809 mServerStatusText
= R
.string
.auth_wtf_reenter_URL
;
811 mOkButton
.setEnabled(false
);
812 //Log_OC.wtf(TAG, "The user was allowed to click 'connect' to an unchecked server!!");
816 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
817 startOauthorization();
818 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
819 startSamlBasedFederatedSingleSignOnAuthorization();
821 checkBasicAuthorization();
827 * Tests the credentials entered by the user performing a check of existence on
828 * the root folder of the ownCloud server.
830 private void checkBasicAuthorization() {
831 /// get basic credentials entered by user
832 String username
= mUsernameInput
.getText().toString();
833 String password
= mPasswordInput
.getText().toString();
835 /// be gentle with the user
836 IndeterminateProgressDialog dialog
=
837 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
838 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
840 /// test credentials accessing the root folder
841 String remotePath
="";
842 boolean successIfAbsent
= false
;
843 boolean followRedirects
= true
;
844 startExistenceCheckRemoteOperation(
845 remotePath
, this, successIfAbsent
, username
, password
, followRedirects
);
849 private void startExistenceCheckRemoteOperation(
850 String remotePath
, Context context
, boolean successIfAbsent
,
851 String username
, String password
, boolean followRedirects
) {
852 Intent existenceCheckIntent
= new Intent();
853 existenceCheckIntent
.setAction(OperationsService
.ACTION_EXISTENCE_CHECK
);
854 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
855 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_REMOTE_PATH
, remotePath
);
856 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_SUCCESS_IF_ABSENT
, successIfAbsent
);
857 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_USERNAME
, username
);
858 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_PASSWORD
, password
);
859 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_AUTH_TOKEN
, mAuthToken
);
860 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_FOLLOW_REDIRECTS
, followRedirects
);
862 if (mOperationsServiceBinder
!= null
) {
863 //Log_OC.wtf(TAG, "starting existenceCheckRemoteOperation..." );
864 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(existenceCheckIntent
);
869 * Starts the OAuth 'grant type' flow to get an access token, with
870 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
872 private void startOauthorization() {
873 // be gentle with the user
874 mAuthStatusIcon
= R
.drawable
.progress_small
;
875 mAuthStatusText
= R
.string
.oauth_login_connection
;
878 // GET AUTHORIZATION request
879 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
880 Uri
.Builder uriBuilder
= uri
.buildUpon();
881 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
));
882 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
));
883 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
));
884 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
));
885 uri
= uriBuilder
.build();
886 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
887 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
893 * Starts the Web Single Sign On flow to get access to the root folder
896 private void startSamlBasedFederatedSingleSignOnAuthorization() {
897 // be gentle with the user
898 mAuthStatusIcon
= R
.drawable
.progress_small
;
899 mAuthStatusText
= R
.string
.auth_connecting_auth_server
;
901 IndeterminateProgressDialog dialog
=
902 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
903 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
905 /// test credentials accessing the root folder
906 String remotePath
="";
907 boolean successIfAbsent
= false
;
908 boolean followRedirections
= false
;
909 startExistenceCheckRemoteOperation(
910 remotePath
, this, successIfAbsent
, "", "", followRedirections
);
915 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
917 * Dispatches the operation flow to the right method.
920 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
922 if (operation
instanceof GetServerInfoOperation
) {
923 if (operation
.hashCode() == mWaitingForOpId
) {
924 onGetServerInfoFinish(result
);
925 } // else nothing ; only the last check operation is considered;
926 // multiple can be started if the user amends a URL quickly
928 } else if (operation
instanceof OAuth2GetAccessToken
) {
929 onGetOAuthAccessTokenFinish(result
);
931 } else if (operation
instanceof ExistenceCheckRemoteOperation
) {
932 //Log_OC.wtf(TAG, "received detection response through callback" );
933 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
934 onSamlBasedFederatedSingleSignOnAuthorizationStart(result
);
937 onAuthorizationCheckFinish(result
);
939 } else if (operation
instanceof GetRemoteUserNameOperation
) {
940 onGetUserNameFinish(result
);
945 private void onGetUserNameFinish(RemoteOperationResult result
) {
946 mWaitingForOpId
= Long
.MAX_VALUE
;
947 if (result
.isSuccess()) {
948 boolean success
= false
;
949 String username
= (String
) result
.getData().get(0);
951 if ( mAction
== ACTION_CREATE
) {
952 mUsernameInput
.setText(username
);
953 success
= createAccount();
956 if (!mUsernameInput
.getText().toString().equals(username
)) {
957 // fail - not a new account, but an existing one; disallow
958 result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_THE_SAME
);
959 updateAuthStatusIconAndText(result
);
961 Log_OC
.d(TAG
, result
.getLogMessage());
971 updateStatusIconFailUserName();
973 Log_OC
.e(TAG
, "Access to user name failed: " + result
.getLogMessage());
978 private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperationResult result
) {
979 mWaitingForOpId
= Long
.MAX_VALUE
;
980 dismissDialog(WAIT_DIALOG_TAG
);
982 if (result
.isIdPRedirection()) {
983 String url
= result
.getRedirectedLocation();
984 String targetUrl
= mServerInfo
.mBaseUrl
985 + AccountUtils
.getWebdavPath(mServerInfo
.mVersion
, mAuthTokenType
);
988 SamlWebViewDialog dialog
= SamlWebViewDialog
.newInstance(url
, targetUrl
);
989 dialog
.show(getSupportFragmentManager(), SAML_DIALOG_TAG
);
995 mAuthStatusIcon
= R
.drawable
.common_error
;
996 mAuthStatusText
= R
.string
.auth_unsupported_auth_method
;
1004 * Processes the result of the server check performed when the user finishes the enter of the
1007 * @param operation Server check performed.
1008 * @param result Result of the check.
1010 private void onGetServerInfoFinish(RemoteOperationResult result
) {
1011 /// update activity state
1012 mServerIsChecked
= true
;
1013 mWaitingForOpId
= Long
.MAX_VALUE
;
1015 // update server status, but don't show it yet
1016 updateServerStatusIconAndText(result
);
1018 if (result
.isSuccess()) {
1020 // 1. connection succeeded, and we know if it's SSL or not
1021 // 2. server is installed
1022 // 3. we got the server version
1023 // 4. we got the authentication method required by the server
1024 mServerInfo
= (GetServerInfoOperation
.ServerInfo
) (result
.getData().get(0));
1026 if (!authSupported(mServerInfo
.mAuthMethod
)) {
1028 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1029 mServerIsValid
= false
;
1032 mServerIsValid
= true
;
1036 mServerIsValid
= false
;
1040 showRefreshButton(!mServerIsValid
);
1042 mOkButton
.setEnabled(mServerIsValid
);
1044 /// very special case (TODO: move to a common place for all the remote operations)
1045 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1046 showUntrustedCertDialog(result
);
1051 private boolean authSupported(AuthenticationMethod authMethod
) {
1052 String basic
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1053 String oAuth
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1054 String saml
= AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
1056 return (( mAuthTokenType
.equals(basic
) &&
1057 authMethod
.equals(AuthenticationMethod
.BASIC_HTTP_AUTH
) ) ||
1058 ( mAuthTokenType
.equals(oAuth
) &&
1059 authMethod
.equals(AuthenticationMethod
.BEARER_TOKEN
)) ||
1060 ( mAuthTokenType
.equals(saml
) &&
1061 authMethod
.equals(AuthenticationMethod
.SAML_WEB_SSO
))
1066 // TODO remove, if possible
1067 private String
normalizeUrl(String url
, boolean sslWhenUnprefixed
) {
1068 if (url
!= null
&& url
.length() > 0) {
1070 if (!url
.toLowerCase().startsWith("http://") &&
1071 !url
.toLowerCase().startsWith("https://")) {
1072 if (sslWhenUnprefixed
) {
1073 url
= "https://" + url
;
1075 url
= "http://" + url
;
1079 url
= trimUrlWebdav(url
);
1081 if (url
.endsWith("/")) {
1082 url
= url
.substring(0, url
.length() - 1);
1086 return (url
!= null ? url
: "");
1090 // TODO remove, if possible
1091 private String
trimUrlWebdav(String url
){
1092 if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_4_0
)){
1093 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_4_0
.length());
1094 } else if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_2_0
)){
1095 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_2_0
.length());
1096 } else if (url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_1_2
)){
1097 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_1_2
.length());
1099 return (url
!= null ? url
: "");
1104 * Chooses the right icon and text to show to the user for the received operation result.
1106 * @param result Result of a remote operation performed in this activity
1108 private void updateServerStatusIconAndText(RemoteOperationResult result
) {
1109 mServerStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1111 switch (result
.getCode()) {
1113 mServerStatusIcon
= android
.R
.drawable
.ic_secure
;
1114 mServerStatusText
= R
.string
.auth_secure_connection
;
1119 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1120 mServerStatusText
= R
.string
.auth_connection_established
;
1121 mServerStatusIcon
= R
.drawable
.ic_ok
;
1123 mServerStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1124 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1128 case NO_NETWORK_CONNECTION
:
1129 mServerStatusIcon
= R
.drawable
.no_network
;
1130 mServerStatusText
= R
.string
.auth_no_net_conn_title
;
1133 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1134 mServerStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1136 case BAD_OC_VERSION
:
1137 mServerStatusText
= R
.string
.auth_bad_oc_version_title
;
1139 case WRONG_CONNECTION
:
1140 mServerStatusText
= R
.string
.auth_wrong_connection_title
;
1143 mServerStatusText
= R
.string
.auth_timeout_title
;
1145 case INCORRECT_ADDRESS
:
1146 mServerStatusText
= R
.string
.auth_incorrect_address_title
;
1149 mServerStatusText
= R
.string
.auth_ssl_general_error_title
;
1152 mServerStatusText
= R
.string
.auth_unauthorized
;
1154 case HOST_NOT_AVAILABLE
:
1155 mServerStatusText
= R
.string
.auth_unknown_host_title
;
1157 case INSTANCE_NOT_CONFIGURED
:
1158 mServerStatusText
= R
.string
.auth_not_configured_title
;
1160 case FILE_NOT_FOUND
:
1161 mServerStatusText
= R
.string
.auth_incorrect_path_title
;
1164 mServerStatusText
= R
.string
.auth_oauth_error
;
1166 case OAUTH2_ERROR_ACCESS_DENIED
:
1167 mServerStatusText
= R
.string
.auth_oauth_error_access_denied
;
1169 case UNHANDLED_HTTP_CODE
:
1171 mServerStatusText
= R
.string
.auth_unknown_error_title
;
1174 mServerStatusText
= 0;
1175 mServerStatusIcon
= 0;
1181 * Chooses the right icon and text to show to the user for the received operation result.
1183 * @param result Result of a remote operation performed in this activity
1185 private void updateAuthStatusIconAndText(RemoteOperationResult result
) {
1186 mAuthStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1188 switch (result
.getCode()) {
1190 mAuthStatusIcon
= android
.R
.drawable
.ic_secure
;
1191 mAuthStatusText
= R
.string
.auth_secure_connection
;
1196 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1197 mAuthStatusText
= R
.string
.auth_connection_established
;
1198 mAuthStatusIcon
= R
.drawable
.ic_ok
;
1200 mAuthStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1201 mAuthStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1205 case NO_NETWORK_CONNECTION
:
1206 mAuthStatusIcon
= R
.drawable
.no_network
;
1207 mAuthStatusText
= R
.string
.auth_no_net_conn_title
;
1210 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1211 mAuthStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1213 case BAD_OC_VERSION
:
1214 mAuthStatusText
= R
.string
.auth_bad_oc_version_title
;
1216 case WRONG_CONNECTION
:
1217 mAuthStatusText
= R
.string
.auth_wrong_connection_title
;
1220 mAuthStatusText
= R
.string
.auth_timeout_title
;
1222 case INCORRECT_ADDRESS
:
1223 mAuthStatusText
= R
.string
.auth_incorrect_address_title
;
1226 mAuthStatusText
= R
.string
.auth_ssl_general_error_title
;
1229 mAuthStatusText
= R
.string
.auth_unauthorized
;
1231 case HOST_NOT_AVAILABLE
:
1232 mAuthStatusText
= R
.string
.auth_unknown_host_title
;
1234 case INSTANCE_NOT_CONFIGURED
:
1235 mAuthStatusText
= R
.string
.auth_not_configured_title
;
1237 case FILE_NOT_FOUND
:
1238 mAuthStatusText
= R
.string
.auth_incorrect_path_title
;
1241 mAuthStatusText
= R
.string
.auth_oauth_error
;
1243 case OAUTH2_ERROR_ACCESS_DENIED
:
1244 mAuthStatusText
= R
.string
.auth_oauth_error_access_denied
;
1246 case ACCOUNT_NOT_NEW
:
1247 mAuthStatusText
= R
.string
.auth_account_not_new
;
1249 case ACCOUNT_NOT_THE_SAME
:
1250 mAuthStatusText
= R
.string
.auth_account_not_the_same
;
1252 case UNHANDLED_HTTP_CODE
:
1254 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
1257 mAuthStatusText
= 0;
1258 mAuthStatusIcon
= 0;
1263 private void updateStatusIconFailUserName(){
1264 mAuthStatusIcon
= R
.drawable
.common_error
;
1265 mAuthStatusText
= R
.string
.auth_fail_get_user_name
;
1268 private void updateServerStatusIconNoRegularAuth(){
1269 mServerStatusIcon
= R
.drawable
.common_error
;
1270 mServerStatusText
= R
.string
.auth_can_not_auth_against_server
;
1274 * Processes the result of the request for and access token send
1275 * to an OAuth authorization server.
1277 * @param result Result of the operation.
1279 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result
) {
1280 mWaitingForOpId
= Long
.MAX_VALUE
;
1281 dismissDialog(WAIT_DIALOG_TAG
);
1283 if (result
.isSuccess()) {
1284 /// be gentle with the user
1285 IndeterminateProgressDialog dialog
=
1286 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
1287 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
1289 /// time to test the retrieved access token on the ownCloud server
1290 @SuppressWarnings("unchecked")
1291 Map
<String
, String
> tokens
= (Map
<String
, String
>)(result
.getData().get(0));
1292 mAuthToken
= tokens
.get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
1293 //mAuthToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Constants.KEY_ACCESS_TOKEN);
1294 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mAuthToken
);
1296 String remotePath
="";
1297 boolean successIfAbsent
= false
;
1298 boolean followRedirects
= true
;
1299 startExistenceCheckRemoteOperation(
1300 remotePath
, this, successIfAbsent
, "", "", followRedirects
);
1303 updateAuthStatusIconAndText(result
);
1305 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1311 * Processes the result of the access check performed to try the user credentials.
1313 * Creates a new account through the AccountManager.
1315 * @param operation Access check performed.
1316 * @param result Result of the operation.
1318 private void onAuthorizationCheckFinish(RemoteOperationResult result
) {
1319 mWaitingForOpId
= Long
.MAX_VALUE
;
1320 dismissDialog(WAIT_DIALOG_TAG
);
1322 if (result
.isSuccess()) {
1323 Log_OC
.d(TAG
, "Successful access - time to save the account");
1325 boolean success
= false
;
1326 if (mAction
== ACTION_CREATE
) {
1327 success
= createAccount();
1338 } else if (result
.isServerFail() || result
.isException()) {
1339 /// server errors or exceptions in authorization take to requiring a new check of
1341 mServerIsChecked
= true
;
1342 mServerIsValid
= false
;
1343 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
1345 // update status icon and text
1346 updateServerStatusIconAndText(result
);
1348 mAuthStatusIcon
= 0;
1349 mAuthStatusText
= 0;
1352 // update input controls state
1353 showRefreshButton(true
);
1354 mOkButton
.setEnabled(false
);
1356 // very special case (TODO: move to a common place for all the remote operations) (dangerous here?)
1357 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1358 showUntrustedCertDialog(result
);
1361 } else { // authorization fail due to client side - probably wrong credentials
1362 updateAuthStatusIconAndText(result
);
1364 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1372 * Sets the proper response to get that the Account Authenticator that started this activity saves
1373 * a new authorization token for mAccount.
1375 private void updateToken() {
1376 Bundle response
= new Bundle();
1377 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1378 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
1380 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
1381 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1382 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1383 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1385 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
1387 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1388 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1389 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1392 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
1393 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
1395 setAccountAuthenticatorResult(response
);
1401 * Creates a new account through the Account Authenticator that started this activity.
1403 * This makes the account permanent.
1405 * TODO Decide how to name the OAuth accounts
1407 private boolean createAccount() {
1408 /// create and save new ownCloud account
1409 boolean isOAuth
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
);
1410 boolean isSaml
= AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
);
1412 Uri uri
= Uri
.parse(mServerInfo
.mBaseUrl
);
1413 String username
= mUsernameInput
.getText().toString().trim();
1415 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1417 String accountName
= com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.
1418 buildAccountName(uri
, username
);
1419 Account newAccount
= new Account(accountName
, MainApp
.getAccountType());
1420 if (AccountUtils
.exists(newAccount
, getApplicationContext())) {
1421 // fail - not a new account, but an existing one; disallow
1422 RemoteOperationResult result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_NEW
);
1423 updateAuthStatusIconAndText(result
);
1425 Log_OC
.d(TAG
, result
.getLogMessage());
1429 mAccount
= newAccount
;
1431 if (isOAuth
|| isSaml
) {
1432 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
); // with external authorizations, the password is never input in the app
1434 mAccountMgr
.addAccountExplicitly(mAccount
, mPasswordInput
.getText().toString(), null
);
1437 /// add the new account as default in preferences, if there is none already
1438 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1439 if (defaultAccount
== null
) {
1440 SharedPreferences
.Editor editor
= PreferenceManager
1441 .getDefaultSharedPreferences(this).edit();
1442 editor
.putString("select_oc_account", accountName
);
1446 /// prepare result to return to the Authenticator
1447 // TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done
1448 final Intent intent
= new Intent();
1449 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, MainApp
.getAccountType());
1450 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1452 intent.putExtra(AccountManager.KEY_AUTHTOKEN, MainApp.getAccountType()); */
1453 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1454 if (isOAuth
|| isSaml
) {
1455 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1457 /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
1458 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion());
1459 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_OC_BASE_URL
, mServerInfo
.mBaseUrl
);
1462 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
, "TRUE");
1463 } else if (isOAuth
) {
1464 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
, "TRUE");
1467 setAccountAuthenticatorResult(intent
.getExtras());
1468 setResult(RESULT_OK
, intent
);
1476 * Starts and activity to open the 'new account' page in the ownCloud web site
1478 * @param view 'Account register' button
1480 public void onRegisterClick(View view
) {
1481 Intent register
= new Intent(Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.welcome_link_url
)));
1482 setResult(RESULT_CANCELED
);
1483 startActivity(register
);
1488 * Updates the content and visibility state of the icon and text associated
1489 * to the last check on the ownCloud server.
1491 * @param serverStatusText Resource identifier of the text to show.
1492 * @param serverStatusIcon Resource identifier of the icon to show.
1494 private void showServerStatus() {
1495 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1496 mServerStatusView
.setVisibility(View
.INVISIBLE
);
1499 mServerStatusView
.setText(mServerStatusText
);
1500 mServerStatusView
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1501 mServerStatusView
.setVisibility(View
.VISIBLE
);
1508 * Updates the content and visibility state of the icon and text associated
1509 * to the interactions with the OAuth authorization server.
1511 private void showAuthStatus() {
1512 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1513 mAuthStatusView
.setVisibility(View
.INVISIBLE
);
1516 mAuthStatusView
.setText(mAuthStatusText
);
1517 mAuthStatusView
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1518 mAuthStatusView
.setVisibility(View
.VISIBLE
);
1523 private void showRefreshButton (boolean show
) {
1525 mRefreshButton
.setVisibility(View
.VISIBLE
);
1527 mRefreshButton
.setVisibility(View
.GONE
);
1532 * Called when the refresh button in the input field for ownCloud host is clicked.
1534 * Performs a new check on the URL in the input field.
1536 * @param view Refresh 'button'
1538 public void onRefreshClick(View view
) {
1544 * Called when the eye icon in the password field is clicked.
1546 * Toggles the visibility of the password in the field.
1548 public void onViewPasswordClick() {
1549 int selectionStart
= mPasswordInput
.getSelectionStart();
1550 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1551 if (isPasswordVisible()) {
1556 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1561 * Called when the checkbox for OAuth authorization is clicked.
1563 * Hides or shows the input fields for user & password.
1565 * @param view 'View password' 'button'
1567 public void onCheckClick(View view
) {
1568 CheckBox oAuth2Check
= (CheckBox
)view
;
1569 if (oAuth2Check
.isChecked()) {
1570 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1572 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1574 updateAuthenticationPreFragmentVisibility();
1579 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1581 * Used to trigger the authentication check when the user presses 'enter' after writing the password,
1582 * or to throw the server test when the only field on screen is the URL input field.
1585 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1586 if (actionId
== EditorInfo
.IME_ACTION_DONE
&& inputField
!= null
&& inputField
.equals(mPasswordInput
)) {
1587 if (mOkButton
.isEnabled()) {
1588 mOkButton
.performClick();
1591 } else if (actionId
== EditorInfo
.IME_ACTION_NEXT
&& inputField
!= null
&& inputField
.equals(mHostUrlInput
)) {
1592 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
1596 return false
; // always return false to grant that the software keyboard is hidden anyway
1600 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1602 private int fuzz
= 75;
1608 public boolean onTouch(View view
, MotionEvent event
) {
1609 Drawable rightDrawable
= null
;
1610 if (view
instanceof TextView
) {
1611 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1612 if (drawables
.length
> 2) {
1613 rightDrawable
= drawables
[2];
1616 if (rightDrawable
!= null
) {
1617 final int x
= (int) event
.getX();
1618 final int y
= (int) event
.getY();
1619 final Rect bounds
= rightDrawable
.getBounds();
1620 if (x
>= (view
.getRight() - bounds
.width() - fuzz
) && x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
)
1621 && y
>= (view
.getPaddingTop() - fuzz
) && y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1623 return onDrawableTouch(event
);
1629 public abstract boolean onDrawableTouch(final MotionEvent event
);
1633 private void getRemoteUserNameOperation(String sessionCookie
, boolean followRedirects
) {
1635 Intent getUserNameIntent
= new Intent();
1636 getUserNameIntent
.setAction(OperationsService
.ACTION_GET_USER_NAME
);
1637 getUserNameIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
1638 getUserNameIntent
.putExtra(OperationsService
.EXTRA_COOKIE
, sessionCookie
);
1639 getUserNameIntent
.putExtra(OperationsService
.EXTRA_FOLLOW_REDIRECTS
, followRedirects
);
1641 if (mOperationsServiceBinder
!= null
) {
1642 //Log_OC.wtf(TAG, "starting getRemoteUserNameOperation..." );
1643 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(getUserNameIntent
);
1649 public void onSsoFinished(String sessionCookie
) {
1650 if (sessionCookie
!= null
&& sessionCookie
.length() > 0) {
1651 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1652 mAuthToken
= sessionCookie
;
1653 getRemoteUserNameOperation(sessionCookie
, true
);
1654 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1655 if (fd
!= null
&& fd
instanceof SherlockDialogFragment
) {
1656 Dialog d
= ((SherlockDialogFragment
)fd
).getDialog();
1657 if (d
!= null
&& d
.isShowing()) {
1664 Log_OC
.d(TAG
, "SSO failed");
1670 public boolean onTouchEvent(MotionEvent event
) {
1671 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
) &&
1672 mHostUrlInput
.hasFocus() && event
.getAction() == MotionEvent
.ACTION_DOWN
) {
1675 return super.onTouchEvent(event
);
1680 * Show untrusted cert dialog
1682 public void showUntrustedCertDialog(X509Certificate x509Certificate
, SslError error
, SslErrorHandler handler
) {
1683 // Show a dialog with the certificate info
1684 SslUntrustedCertDialog dialog
= null
;
1685 if (x509Certificate
== null
) {
1686 dialog
= SslUntrustedCertDialog
.newInstanceForEmptySslError(error
, handler
);
1688 dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(x509Certificate
, error
, handler
);
1690 FragmentManager fm
= getSupportFragmentManager();
1691 FragmentTransaction ft
= fm
.beginTransaction();
1692 ft
.addToBackStack(null
);
1693 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1697 * Show untrusted cert dialog
1699 private void showUntrustedCertDialog(RemoteOperationResult result
) {
1700 // Show a dialog with the certificate info
1701 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1702 FragmentManager fm
= getSupportFragmentManager();
1703 FragmentTransaction ft
= fm
.beginTransaction();
1704 ft
.addToBackStack(null
);
1705 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1710 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1712 public void onSavedCertificate() {
1713 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1715 // if SAML dialog is not shown, the SslDialog was shown due to an SSL error in the server check
1721 * Called from SslValidatorDialog when a new server certificate could not be saved
1722 * when the user requested it.
1725 public void onFailedSavingCertificate() {
1726 dismissDialog(SAML_DIALOG_TAG
);
1727 Toast
.makeText(this, R
.string
.ssl_validator_not_saved
, Toast
.LENGTH_LONG
).show();
1731 public void onCancelCertificate() {
1732 dismissDialog(SAML_DIALOG_TAG
);
1736 private void doOnResumeAndBound() {
1737 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1738 mOperationsServiceBinder
.addOperationListener(AuthenticatorActivity
.this, mHandler
);
1739 if (mWaitingForOpId
<= Integer
.MAX_VALUE
) {
1740 mOperationsServiceBinder
.dispatchResultIfFinished((int)mWaitingForOpId
, this);
1743 if (mPendingAutoCheck
) {
1749 private void dismissDialog(String dialogTag
){
1750 Fragment frag
= getSupportFragmentManager().findFragmentByTag(dialogTag
);
1751 if (frag
!= null
&& frag
instanceof SherlockDialogFragment
) {
1752 SherlockDialogFragment dialog
= (SherlockDialogFragment
) frag
;
1759 * Implements callback methods for service binding.
1761 private class OperationsServiceConnection
implements ServiceConnection
{
1764 public void onServiceConnected(ComponentName component
, IBinder service
) {
1765 if (component
.equals(new ComponentName(AuthenticatorActivity
.this, OperationsService
.class))) {
1766 //Log_OC.wtf(TAG, "Operations service connected");
1767 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
1769 doOnResumeAndBound();
1778 public void onServiceDisconnected(ComponentName component
) {
1779 if (component
.equals(new ComponentName(AuthenticatorActivity
.this, OperationsService
.class))) {
1780 Log_OC
.e(TAG
, "Operations service crashed");
1781 mOperationsServiceBinder
= null
;