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
.OwnCloudAccount
;
66 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
67 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentialsFactory
;
68 import com
.owncloud
.android
.lib
.common
.accounts
.AccountTypeUtils
;
69 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.Constants
;
70 import com
.owncloud
.android
.operations
.DetectAuthenticationMethodOperation
.AuthenticationMethod
;
71 import com
.owncloud
.android
.operations
.GetServerInfoOperation
;
72 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
74 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
75 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
76 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
79 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
80 import com
.owncloud
.android
.lib
.resources
.users
.GetRemoteUserNameOperation
;
82 import com
.owncloud
.android
.services
.OperationsService
;
83 import com
.owncloud
.android
.services
.OperationsService
.OperationsServiceBinder
;
84 import com
.owncloud
.android
.ui
.dialog
.IndeterminateProgressDialog
;
85 import com
.owncloud
.android
.ui
.dialog
.SamlWebViewDialog
;
86 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
87 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
88 import com
.owncloud
.android
.utils
.Log_OC
;
89 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
92 * This Activity is used to add an ownCloud account to the App
94 * @author Bartek Przybylski
95 * @author David A. Velasco
98 public class AuthenticatorActivity
extends AccountAuthenticatorActivity
99 implements OnRemoteOperationListener
, OnFocusChangeListener
, OnEditorActionListener
,
100 SsoWebViewClientListener
, OnSslUntrustedCertListener
{
102 private static final String TAG
= AuthenticatorActivity
.class.getSimpleName();
104 public static final String EXTRA_ACTION
= "ACTION";
105 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
107 private static final String KEY_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
109 private static final String KEY_HOST_URL_TEXT
= "HOST_URL_TEXT";
110 private static final String KEY_OC_VERSION
= "OC_VERSION";
111 private static final String KEY_SERVER_VALID
= "SERVER_VALID";
112 private static final String KEY_SERVER_CHECKED
= "SERVER_CHECKED";
113 private static final String KEY_SERVER_STATUS_TEXT
= "SERVER_STATUS_TEXT";
114 private static final String KEY_SERVER_STATUS_ICON
= "SERVER_STATUS_ICON";
115 private static final String KEY_IS_SSL_CONN
= "IS_SSL_CONN";
116 private static final String KEY_PASSWORD_EXPOSED
= "PASSWORD_VISIBLE";
117 private static final String KEY_AUTH_STATUS_TEXT
= "AUTH_STATUS_TEXT";
118 private static final String KEY_AUTH_STATUS_ICON
= "AUTH_STATUS_ICON";
119 private static final String KEY_SERVER_AUTH_METHOD
= "SERVER_AUTH_METHOD";
120 private static final String KEY_WAITING_FOR_OP_ID
= "WAITING_FOR_OP_ID";
121 private static final String KEY_AUTH_TOKEN
= "AUTH_TOKEN";
123 private static final String AUTH_ON
= "on";
124 private static final String AUTH_OPTIONAL
= "optional";
126 public static final byte ACTION_CREATE
= 0;
127 public static final byte ACTION_UPDATE_TOKEN
= 1; // requested by the user
128 public static final byte ACTION_UPDATE_EXPIRED_TOKEN
= 2; // detected by the app
130 private static final String UNTRUSTED_CERT_DIALOG_TAG
= "UNTRUSTED_CERT_DIALOG";
131 private static final String SAML_DIALOG_TAG
= "SAML_DIALOG";
132 private static final String WAIT_DIALOG_TAG
= "WAIT_DIALOG";
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
= "";
179 /// Identifier of operation in progress which result shouldn't be lost
180 private long mWaitingForOpId
= Long
.MAX_VALUE
;
186 * IMPORTANT ENTRY POINT 1: activity is shown to the user
189 protected void onCreate(Bundle savedInstanceState
) {
190 //Log_OC.wtf(TAG, "onCreate init");
191 super.onCreate(savedInstanceState
);
192 getWindow().requestFeature(Window
.FEATURE_NO_TITLE
);
194 // bind to Operations Service
195 mOperationsServiceConnection
= new OperationsServiceConnection();
196 if (!bindService(new Intent(this, OperationsService
.class),
197 mOperationsServiceConnection
,
198 Context
.BIND_AUTO_CREATE
)) {
200 R
.string
.error_cant_bind_to_operations_service
,
206 /// init activity state
207 mAccountMgr
= AccountManager
.get(this);
208 mNewCapturedUriFromOAuth2Redirection
= null
;
211 mAction
= getIntent().getByteExtra(EXTRA_ACTION
, ACTION_CREATE
);
212 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
213 if (savedInstanceState
== null
) {
216 mAuthTokenType
= savedInstanceState
.getString(KEY_AUTH_TOKEN_TYPE
);
217 mWaitingForOpId
= savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
);
220 /// load user interface
221 setContentView(R
.layout
.account_setup
);
223 /// initialize general UI elements
224 initOverallUi(savedInstanceState
);
226 mOkButton
= findViewById(R
.id
.buttonOK
);
228 /// initialize block to be moved to single Fragment to check server and get info about it
229 initServerPreFragment(savedInstanceState
);
231 /// initialize block to be moved to single Fragment to retrieve and validate credentials
232 initAuthorizationPreFragment(savedInstanceState
);
234 //Log_OC.wtf(TAG, "onCreate end");
237 private void initAuthTokenType() {
239 getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
240 if (mAuthTokenType
== null
) {
241 if (mAccount
!= null
) {
242 boolean oAuthRequired
=
243 (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
) != null
);
244 boolean samlWebSsoRequired
=
245 (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
) != null
);
246 mAuthTokenType
= chooseAuthTokenType(oAuthRequired
, samlWebSsoRequired
);
249 boolean oAuthSupported
= AUTH_ON
.equals(getString(R
.string
.auth_method_oauth2
));
250 boolean samlWebSsoSupported
= AUTH_ON
.equals(getString(R
.string
.auth_method_saml_web_sso
));
251 mAuthTokenType
= chooseAuthTokenType(oAuthSupported
, samlWebSsoSupported
);
256 private String
chooseAuthTokenType(boolean oauth
, boolean saml
) {
258 return AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
260 return AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
262 return AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
268 * Configures elements in the user interface under direct control of the Activity.
270 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
272 private void initOverallUi(Bundle savedInstanceState
) {
274 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
275 boolean isWelcomeLinkVisible
= getResources().getBoolean(R
.bool
.show_welcome_link
);
277 String instructionsMessageText
= null
;
278 if (mAction
== ACTION_UPDATE_EXPIRED_TOKEN
) {
279 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
280 .equals(mAuthTokenType
)) {
281 instructionsMessageText
= getString(R
.string
.auth_expired_oauth_token_toast
);
283 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType())
284 .equals(mAuthTokenType
)) {
285 instructionsMessageText
= getString(R
.string
.auth_expired_saml_sso_token_toast
);
288 instructionsMessageText
= getString(R
.string
.auth_expired_basic_auth_toast
);
292 /// step 2 - set properties of UI elements (text, visibility, enabled...)
293 Button welcomeLink
= (Button
) findViewById(R
.id
.welcome_link
);
294 welcomeLink
.setVisibility(isWelcomeLinkVisible ? View
.VISIBLE
: View
.GONE
);
296 String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
298 TextView instructionsView
= (TextView
) findViewById(R
.id
.instructions_message
);
299 if (instructionsMessageText
!= null
) {
300 instructionsView
.setVisibility(View
.VISIBLE
);
301 instructionsView
.setText(instructionsMessageText
);
303 instructionsView
.setVisibility(View
.GONE
);
310 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
312 private void initServerPreFragment(Bundle savedInstanceState
) {
314 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
315 boolean isUrlInputAllowed
= getResources().getBoolean(R
.bool
.show_server_url_input
);
316 if (savedInstanceState
== null
) {
317 if (mAccount
!= null
) {
318 mServerInfo
.mBaseUrl
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_BASE_URL
);
319 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://"); // TODO do this in a setter for mBaseUrl
320 String ocVersion
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_VERSION
);
321 if (ocVersion
!= null
) {
322 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
325 mServerInfo
.mBaseUrl
= getString(R
.string
.server_url
).trim();
326 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
329 mServerStatusText
= savedInstanceState
.getInt(KEY_SERVER_STATUS_TEXT
);
330 mServerStatusIcon
= savedInstanceState
.getInt(KEY_SERVER_STATUS_ICON
);
332 mServerIsValid
= savedInstanceState
.getBoolean(KEY_SERVER_VALID
);
333 mServerIsChecked
= savedInstanceState
.getBoolean(KEY_SERVER_CHECKED
);
336 mServerInfo
.mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
337 mServerInfo
.mBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
338 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
339 if (ocVersion
!= null
) {
340 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
342 mServerInfo
.mAuthMethod
= AuthenticationMethod
.valueOf(
343 savedInstanceState
.getString(KEY_SERVER_AUTH_METHOD
));
347 /// step 2 - set properties of UI elements (text, visibility, enabled...)
348 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
349 mHostUrlInput
.setText(mServerInfo
.mBaseUrl
);
350 if (mAction
!= ACTION_CREATE
) {
351 /// lock things that should not change
352 mHostUrlInput
.setEnabled(false
);
353 mHostUrlInput
.setFocusable(false
);
355 if (isUrlInputAllowed
) {
356 mRefreshButton
= findViewById(R
.id
.embeddedRefreshButton
);
358 findViewById(R
.id
.hostUrlFrame
).setVisibility(View
.GONE
);
359 mRefreshButton
= findViewById(R
.id
.centeredRefreshButton
);
361 showRefreshButton(mServerIsChecked
&& !mServerIsValid
&&
362 mWaitingForOpId
> Integer
.MAX_VALUE
);
363 mServerStatusView
= (TextView
) findViewById(R
.id
.server_status_text
);
366 /// step 3 - bind some listeners and options
367 mHostUrlInput
.setImeOptions(EditorInfo
.IME_ACTION_NEXT
);
368 mHostUrlInput
.setOnEditorActionListener(this);
370 /// step 4 - create listeners that will be bound at onResume
371 mHostUrlInputWatcher
= new TextWatcher() {
374 public void afterTextChanged(Editable s
) {
375 if (mOkButton
.isEnabled() &&
376 !mServerInfo
.mBaseUrl
.equals(
377 normalizeUrl(s
.toString(), mServerInfo
.mIsSslConn
))) {
378 mOkButton
.setEnabled(false
);
383 public void beforeTextChanged(CharSequence s
, int start
, int count
, int after
) {
387 public void onTextChanged(CharSequence s
, int start
, int before
, int count
) {
388 if (mAuthStatusIcon
!= 0) {
389 Log_OC
.d(TAG
, "onTextChanged: hiding authentication status");
398 // TODO find out if this is really necessary, or if it can done in a different way
399 findViewById(R
.id
.scroll
).setOnTouchListener(new OnTouchListener() {
401 public boolean onTouch(View view
, MotionEvent event
) {
402 if (event
.getAction() == MotionEvent
.ACTION_DOWN
) {
403 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
) &&
404 mHostUrlInput
.hasFocus()) {
413 /// step 4 - mark automatic check to be started when OperationsService is ready
414 mPendingAutoCheck
= (savedInstanceState
== null
&&
415 (mAction
!= ACTION_CREATE
|| !isUrlInputAllowed
));
421 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
423 private void initAuthorizationPreFragment(Bundle savedInstanceState
) {
425 /// step 0 - get UI elements in layout
426 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
427 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
428 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
429 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
430 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
431 mAuthStatusView
= (TextView
) findViewById(R
.id
.auth_status_text
);
433 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
434 String presetUserName
= null
;
435 boolean isPasswordExposed
= false
;
436 if (savedInstanceState
== null
) {
437 if (mAccount
!= null
) {
438 presetUserName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
442 isPasswordExposed
= savedInstanceState
.getBoolean(KEY_PASSWORD_EXPOSED
, false
);
443 mAuthStatusText
= savedInstanceState
.getInt(KEY_AUTH_STATUS_TEXT
);
444 mAuthStatusIcon
= savedInstanceState
.getInt(KEY_AUTH_STATUS_ICON
);
445 mAuthToken
= savedInstanceState
.getString(KEY_AUTH_TOKEN
);
448 /// step 2 - set properties of UI elements (text, visibility, enabled...)
449 mOAuth2Check
.setChecked(
450 AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
451 .equals(mAuthTokenType
));
452 if (presetUserName
!= null
) {
453 mUsernameInput
.setText(presetUserName
);
455 if (mAction
!= ACTION_CREATE
) {
456 mUsernameInput
.setEnabled(false
);
457 mUsernameInput
.setFocusable(false
);
459 mPasswordInput
.setText(""); // clean password to avoid social hacking
460 if (isPasswordExposed
) {
463 updateAuthenticationPreFragmentVisibility();
465 mOkButton
.setEnabled(mServerIsValid
);
468 /// step 3 - bind listeners
469 // bindings for password input field
470 mPasswordInput
.setOnFocusChangeListener(this);
471 mPasswordInput
.setImeOptions(EditorInfo
.IME_ACTION_DONE
);
472 mPasswordInput
.setOnEditorActionListener(this);
473 mPasswordInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
475 public boolean onDrawableTouch(final MotionEvent event
) {
476 if (event
.getAction() == MotionEvent
.ACTION_UP
) {
477 AuthenticatorActivity
.this.onViewPasswordClick();
487 * Changes the visibility of input elements depending on
488 * the current authorization method.
490 private void updateAuthenticationPreFragmentVisibility () {
491 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
492 equals(mAuthTokenType
)) {
493 // SAML-based web Single Sign On
494 mOAuth2Check
.setVisibility(View
.GONE
);
495 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
496 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
497 mUsernameInput
.setVisibility(View
.GONE
);
498 mPasswordInput
.setVisibility(View
.GONE
);
501 if (mAction
== ACTION_CREATE
&&
502 AUTH_OPTIONAL
.equals(getString(R
.string
.auth_method_oauth2
))) {
503 mOAuth2Check
.setVisibility(View
.VISIBLE
);
505 mOAuth2Check
.setVisibility(View
.GONE
);
508 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
509 equals(mAuthTokenType
)) {
510 // OAuth 2 authorization
512 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
513 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
514 mUsernameInput
.setVisibility(View
.GONE
);
515 mPasswordInput
.setVisibility(View
.GONE
);
518 // basic HTTP authorization
519 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
520 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
521 mUsernameInput
.setVisibility(View
.VISIBLE
);
522 mPasswordInput
.setVisibility(View
.VISIBLE
);
530 * Saves relevant state before {@link #onPause()}
532 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag, intended to defer the
533 * processing of the redirection caught in {@link #onNewIntent(Intent)} until {@link #onResume()}
535 * See {@link #loadSavedInstanceState(Bundle)}
538 protected void onSaveInstanceState(Bundle outState
) {
539 //Log_OC.wtf(TAG, "onSaveInstanceState init" );
540 super.onSaveInstanceState(outState
);
543 outState
.putString(KEY_AUTH_TOKEN_TYPE
, mAuthTokenType
);
544 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mWaitingForOpId
);
546 /// Server PRE-fragment state
547 outState
.putInt(KEY_SERVER_STATUS_TEXT
, mServerStatusText
);
548 outState
.putInt(KEY_SERVER_STATUS_ICON
, mServerStatusIcon
);
549 outState
.putBoolean(KEY_SERVER_CHECKED
, mServerIsChecked
);
550 outState
.putBoolean(KEY_SERVER_VALID
, mServerIsValid
);
551 outState
.putBoolean(KEY_IS_SSL_CONN
, mServerInfo
.mIsSslConn
);
552 outState
.putString(KEY_HOST_URL_TEXT
, mServerInfo
.mBaseUrl
);
553 if (mServerInfo
.mVersion
!= null
) {
554 outState
.putString(KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion());
556 outState
.putString(KEY_SERVER_AUTH_METHOD
, mServerInfo
.mAuthMethod
.name());
558 /// Authentication PRE-fragment state
559 outState
.putBoolean(KEY_PASSWORD_EXPOSED
, isPasswordVisible());
560 outState
.putInt(KEY_AUTH_STATUS_ICON
, mAuthStatusIcon
);
561 outState
.putInt(KEY_AUTH_STATUS_TEXT
, mAuthStatusText
);
562 outState
.putString(KEY_AUTH_TOKEN
, mAuthToken
);
564 //Log_OC.wtf(TAG, "onSaveInstanceState end" );
569 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION request
572 * To make this possible, this activity needs to be qualified with android:launchMode = "singleTask" in the
573 * AndroidManifest.xml file.
576 protected void onNewIntent (Intent intent
) {
577 Log_OC
.d(TAG
, "onNewIntent()");
578 Uri data
= intent
.getData();
579 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
580 mNewCapturedUriFromOAuth2Redirection
= data
;
586 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION, and
587 * deferred in {@link #onNewIntent(Intent)}, is processed here.
590 protected void onResume() {
591 //Log_OC.wtf(TAG, "onResume init" );
594 // bound here to avoid spurious changes triggered by Android on device rotations
595 mHostUrlInput
.setOnFocusChangeListener(this);
596 mHostUrlInput
.addTextChangedListener(mHostUrlInputWatcher
);
598 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
599 getOAuth2AccessTokenFromCapturedRedirection();
602 if (mOperationsServiceBinder
!= null
) {
603 doOnResumeAndBound();
606 //Log_OC.wtf(TAG, "onResume end" );
611 protected void onPause() {
612 //Log_OC.wtf(TAG, "onPause init" );
613 if (mOperationsServiceBinder
!= null
) {
614 //Log_OC.wtf(TAG, "unregistering to listen for operation callbacks" );
615 mOperationsServiceBinder
.removeOperationListener(this);
618 mHostUrlInput
.removeTextChangedListener(mHostUrlInputWatcher
);
619 mHostUrlInput
.setOnFocusChangeListener(null
);
622 //Log_OC.wtf(TAG, "onPause end" );
626 protected void onDestroy() {
628 mHostUrlInputWatcher
= null
;
630 if (mOperationsServiceConnection
!= null
) {
631 unbindService(mOperationsServiceConnection
);
632 mOperationsServiceBinder
= null
;
639 * Parses the redirection with the response to the GET AUTHORIZATION request to the
640 * oAuth server and requests for the access token (GET ACCESS TOKEN)
642 private void getOAuth2AccessTokenFromCapturedRedirection() {
643 /// Parse data from OAuth redirection
644 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
645 mNewCapturedUriFromOAuth2Redirection
= null
;
647 /// Showing the dialog with instructions for the user.
648 IndeterminateProgressDialog dialog
=
649 IndeterminateProgressDialog
.newInstance(R
.string
.auth_getting_authorization
, true
);
650 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
652 /// GET ACCESS TOKEN to the oAuth server
653 Intent getServerInfoIntent
= new Intent();
654 getServerInfoIntent
.setAction(OperationsService
.ACTION_OAUTH2_GET_ACCESS_TOKEN
);
656 getServerInfoIntent
.putExtra(
657 OperationsService
.EXTRA_SERVER_URL
,
658 mOAuthTokenEndpointText
.getText().toString().trim());
660 getServerInfoIntent
.putExtra(
661 OperationsService
.EXTRA_OAUTH2_QUERY_PARAMETERS
,
664 if (mOperationsServiceBinder
!= null
) {
665 //Log_OC.wtf(TAG, "getting access token..." );
666 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(getServerInfoIntent
);
673 * Handles the change of focus on the text inputs for the server URL and the password
675 public void onFocusChange(View view
, boolean hasFocus
) {
676 if (view
.getId() == R
.id
.hostUrlInput
) {
678 onUrlInputFocusLost((TextView
) view
);
681 showRefreshButton(false
);
684 } else if (view
.getId() == R
.id
.account_password
) {
685 onPasswordFocusChanged((TextView
) view
, hasFocus
);
691 * Handles changes in focus on the text input for the server URL.
693 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
694 * other field. The operation to check the existence of the server in the entered URL is
697 * When hasFocus: user 'comes back' to write again the server URL.
699 * @param hostInput TextView with the URL input field receiving the change of focus.
701 private void onUrlInputFocusLost(TextView hostInput
) {
702 if (!mServerInfo
.mBaseUrl
.equals(
703 normalizeUrl(mHostUrlInput
.getText().toString(), mServerInfo
.mIsSslConn
))) {
704 // check server again only if the user changed something in the field
707 mOkButton
.setEnabled(mServerIsValid
);
708 showRefreshButton(!mServerIsValid
);
713 private void checkOcServer() {
714 String uri
= mHostUrlInput
.getText().toString().trim();
715 mServerIsValid
= false
;
716 mServerIsChecked
= false
;
717 mOkButton
.setEnabled(false
);
718 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
719 showRefreshButton(false
);
721 if (uri
.length() != 0) {
722 mServerStatusText
= R
.string
.auth_testing_connection
;
723 mServerStatusIcon
= R
.drawable
.progress_small
;
726 Intent getServerInfoIntent
= new Intent();
727 getServerInfoIntent
.setAction(OperationsService
.ACTION_GET_SERVER_INFO
);
728 getServerInfoIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, uri
);
729 if (mOperationsServiceBinder
!= null
) {
730 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(getServerInfoIntent
);
732 Log_OC
.wtf(TAG
, "Server check tried with OperationService unbound!" );
736 mServerStatusText
= 0;
737 mServerStatusIcon
= 0;
744 * Handles changes in focus on the text input for the password (basic authorization).
746 * When (hasFocus), the button to toggle password visibility is shown.
748 * When (!hasFocus), the button is made invisible and the password is hidden.
750 * @param passwordInput TextView with the password input field receiving the change of focus.
751 * @param hasFocus 'True' if focus is received, 'false' if is lost
753 private void onPasswordFocusChanged(TextView passwordInput
, boolean hasFocus
) {
755 showViewPasswordButton();
758 hidePasswordButton();
763 private void showViewPasswordButton() {
764 int drawable
= R
.drawable
.ic_view
;
765 if (isPasswordVisible()) {
766 drawable
= R
.drawable
.ic_hide
;
768 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable
, 0);
771 private boolean isPasswordVisible() {
772 return ((mPasswordInput
.getInputType() & InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) == InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
775 private void hidePasswordButton() {
776 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
779 private void showPassword() {
780 mPasswordInput
.setInputType(InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
781 showViewPasswordButton();
784 private void hidePassword() {
785 mPasswordInput
.setInputType(InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
);
786 showViewPasswordButton();
790 * Checks the credentials of the user in the root of the ownCloud server
791 * before creating a new local account.
793 * For basic authorization, a check of existence of the root folder is
796 * For OAuth, starts the flow to get an access token; the credentials test
797 * is postponed until it is available.
799 * IMPORTANT ENTRY POINT 4
801 * @param view OK button
803 public void onOkClick(View view
) {
804 // this check should be unnecessary
805 if (mServerInfo
.mVersion
== null
||
806 !mServerInfo
.mVersion
.isVersionValid() ||
807 mServerInfo
.mBaseUrl
== null
||
808 mServerInfo
.mBaseUrl
.length() == 0) {
809 mServerStatusIcon
= R
.drawable
.common_error
;
810 mServerStatusText
= R
.string
.auth_wtf_reenter_URL
;
812 mOkButton
.setEnabled(false
);
813 //Log_OC.wtf(TAG, "The user was allowed to click 'connect' to an unchecked server!!");
817 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
818 startOauthorization();
819 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
820 startSamlBasedFederatedSingleSignOnAuthorization();
822 checkBasicAuthorization();
828 * Tests the credentials entered by the user performing a check of existence on
829 * the root folder of the ownCloud server.
831 private void checkBasicAuthorization() {
832 /// get basic credentials entered by user
833 String username
= mUsernameInput
.getText().toString();
834 String password
= mPasswordInput
.getText().toString();
836 /// be gentle with the user
837 IndeterminateProgressDialog dialog
=
838 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
839 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
841 /// validate credentials accessing the root folder
842 accessRootFolderRemoteOperation(username
, password
);
846 private void accessRootFolderRemoteOperation(String username
, String password
) {
847 Intent existenceCheckIntent
= new Intent();
848 existenceCheckIntent
.setAction(OperationsService
.ACTION_EXISTENCE_CHECK
);
849 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
850 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_REMOTE_PATH
, "/");
851 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_USERNAME
, username
);
852 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_PASSWORD
, password
);
853 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_AUTH_TOKEN
, mAuthToken
);
855 if (mOperationsServiceBinder
!= null
) {
856 //Log_OC.wtf(TAG, "starting existenceCheckRemoteOperation..." );
857 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(existenceCheckIntent
);
862 * Starts the OAuth 'grant type' flow to get an access token, with
863 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
865 private void startOauthorization() {
866 // be gentle with the user
867 mAuthStatusIcon
= R
.drawable
.progress_small
;
868 mAuthStatusText
= R
.string
.oauth_login_connection
;
871 // GET AUTHORIZATION request
872 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
873 Uri
.Builder uriBuilder
= uri
.buildUpon();
874 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
));
875 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
));
876 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
));
877 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
));
878 uri
= uriBuilder
.build();
879 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
880 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
886 * Starts the Web Single Sign On flow to get access to the root folder
889 private void startSamlBasedFederatedSingleSignOnAuthorization() {
890 // be gentle with the user
891 mAuthStatusIcon
= R
.drawable
.progress_small
;
892 mAuthStatusText
= R
.string
.auth_connecting_auth_server
;
894 IndeterminateProgressDialog dialog
=
895 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
896 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
898 /// validate credentials accessing the root folder
899 accessRootFolderRemoteOperation("", "");
904 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
906 * Dispatches the operation flow to the right method.
909 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
911 if (operation
instanceof GetServerInfoOperation
) {
912 if (operation
.hashCode() == mWaitingForOpId
) {
913 onGetServerInfoFinish(result
);
914 } // else nothing ; only the last check operation is considered;
915 // multiple can be started if the user amends a URL quickly
917 } else if (operation
instanceof OAuth2GetAccessToken
) {
918 onGetOAuthAccessTokenFinish(result
);
920 } else if (operation
instanceof ExistenceCheckRemoteOperation
) {
921 //Log_OC.wtf(TAG, "received detection response through callback" );
922 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
923 onSamlBasedFederatedSingleSignOnAuthorizationStart(result
);
926 onAuthorizationCheckFinish(result
);
928 } else if (operation
instanceof GetRemoteUserNameOperation
) {
929 onGetUserNameFinish(result
);
934 private void onGetUserNameFinish(RemoteOperationResult result
) {
935 mWaitingForOpId
= Long
.MAX_VALUE
;
936 if (result
.isSuccess()) {
937 boolean success
= false
;
938 String username
= (String
) result
.getData().get(0);
940 if ( mAction
== ACTION_CREATE
) {
941 mUsernameInput
.setText(username
);
942 success
= createAccount();
945 if (!mUsernameInput
.getText().toString().equals(username
)) {
946 // fail - not a new account, but an existing one; disallow
947 result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_THE_SAME
);
949 OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(
951 Uri.parse(mServerInfo.mBaseUrl),
952 OwnCloudCredentialsFactory.newSamlSsoCredentials(mAuthToken))
956 updateAuthStatusIconAndText(result
);
958 Log_OC
.d(TAG
, result
.getLogMessage());
968 updateStatusIconFailUserName();
970 Log_OC
.e(TAG
, "Access to user name failed: " + result
.getLogMessage());
975 private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperationResult result
) {
976 mWaitingForOpId
= Long
.MAX_VALUE
;
977 dismissDialog(WAIT_DIALOG_TAG
);
979 if (result
.isIdPRedirection()) {
980 String url
= result
.getRedirectedLocation();
981 String targetUrl
= mServerInfo
.mBaseUrl
982 + AccountUtils
.getWebdavPath(mServerInfo
.mVersion
, mAuthTokenType
);
985 SamlWebViewDialog dialog
= SamlWebViewDialog
.newInstance(url
, targetUrl
);
986 dialog
.show(getSupportFragmentManager(), SAML_DIALOG_TAG
);
992 mAuthStatusIcon
= R
.drawable
.common_error
;
993 mAuthStatusText
= R
.string
.auth_unsupported_auth_method
;
1001 * Processes the result of the server check performed when the user finishes the enter of the
1004 * @param operation Server check performed.
1005 * @param result Result of the check.
1007 private void onGetServerInfoFinish(RemoteOperationResult result
) {
1008 /// update activity state
1009 mServerIsChecked
= true
;
1010 mWaitingForOpId
= Long
.MAX_VALUE
;
1012 // update server status, but don't show it yet
1013 updateServerStatusIconAndText(result
);
1015 if (result
.isSuccess()) {
1017 // 1. connection succeeded, and we know if it's SSL or not
1018 // 2. server is installed
1019 // 3. we got the server version
1020 // 4. we got the authentication method required by the server
1021 mServerInfo
= (GetServerInfoOperation
.ServerInfo
) (result
.getData().get(0));
1023 if (!authSupported(mServerInfo
.mAuthMethod
)) {
1025 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1026 mServerIsValid
= false
;
1029 mServerIsValid
= true
;
1033 mServerIsValid
= false
;
1037 showRefreshButton(!mServerIsValid
);
1039 mOkButton
.setEnabled(mServerIsValid
);
1041 /// very special case (TODO: move to a common place for all the remote operations)
1042 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1043 showUntrustedCertDialog(result
);
1048 private boolean authSupported(AuthenticationMethod authMethod
) {
1049 String basic
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1050 String oAuth
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1051 String saml
= AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
1053 return (( mAuthTokenType
.equals(basic
) &&
1054 authMethod
.equals(AuthenticationMethod
.BASIC_HTTP_AUTH
) ) ||
1055 ( mAuthTokenType
.equals(oAuth
) &&
1056 authMethod
.equals(AuthenticationMethod
.BEARER_TOKEN
)) ||
1057 ( mAuthTokenType
.equals(saml
) &&
1058 authMethod
.equals(AuthenticationMethod
.SAML_WEB_SSO
))
1063 // TODO remove, if possible
1064 private String
normalizeUrl(String url
, boolean sslWhenUnprefixed
) {
1065 if (url
!= null
&& url
.length() > 0) {
1067 if (!url
.toLowerCase().startsWith("http://") &&
1068 !url
.toLowerCase().startsWith("https://")) {
1069 if (sslWhenUnprefixed
) {
1070 url
= "https://" + url
;
1072 url
= "http://" + url
;
1076 url
= trimUrlWebdav(url
);
1078 if (url
.endsWith("/")) {
1079 url
= url
.substring(0, url
.length() - 1);
1083 return (url
!= null ? url
: "");
1087 // TODO remove, if possible
1088 private String
trimUrlWebdav(String url
){
1089 if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_4_0
)){
1090 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_4_0
.length());
1091 } else if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_2_0
)){
1092 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_2_0
.length());
1093 } else if (url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_1_2
)){
1094 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_1_2
.length());
1096 return (url
!= null ? url
: "");
1101 * Chooses the right icon and text to show to the user for the received operation result.
1103 * @param result Result of a remote operation performed in this activity
1105 private void updateServerStatusIconAndText(RemoteOperationResult result
) {
1106 mServerStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1108 switch (result
.getCode()) {
1110 mServerStatusIcon
= android
.R
.drawable
.ic_secure
;
1111 mServerStatusText
= R
.string
.auth_secure_connection
;
1116 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1117 mServerStatusText
= R
.string
.auth_connection_established
;
1118 mServerStatusIcon
= R
.drawable
.ic_ok
;
1120 mServerStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1121 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1125 case NO_NETWORK_CONNECTION
:
1126 mServerStatusIcon
= R
.drawable
.no_network
;
1127 mServerStatusText
= R
.string
.auth_no_net_conn_title
;
1130 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1131 mServerStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1133 case BAD_OC_VERSION
:
1134 mServerStatusText
= R
.string
.auth_bad_oc_version_title
;
1136 case WRONG_CONNECTION
:
1137 mServerStatusText
= R
.string
.auth_wrong_connection_title
;
1140 mServerStatusText
= R
.string
.auth_timeout_title
;
1142 case INCORRECT_ADDRESS
:
1143 mServerStatusText
= R
.string
.auth_incorrect_address_title
;
1146 mServerStatusText
= R
.string
.auth_ssl_general_error_title
;
1149 mServerStatusText
= R
.string
.auth_unauthorized
;
1151 case HOST_NOT_AVAILABLE
:
1152 mServerStatusText
= R
.string
.auth_unknown_host_title
;
1154 case INSTANCE_NOT_CONFIGURED
:
1155 mServerStatusText
= R
.string
.auth_not_configured_title
;
1157 case FILE_NOT_FOUND
:
1158 mServerStatusText
= R
.string
.auth_incorrect_path_title
;
1161 mServerStatusText
= R
.string
.auth_oauth_error
;
1163 case OAUTH2_ERROR_ACCESS_DENIED
:
1164 mServerStatusText
= R
.string
.auth_oauth_error_access_denied
;
1166 case UNHANDLED_HTTP_CODE
:
1168 mServerStatusText
= R
.string
.auth_unknown_error_title
;
1171 mServerStatusText
= 0;
1172 mServerStatusIcon
= 0;
1178 * Chooses the right icon and text to show to the user for the received operation result.
1180 * @param result Result of a remote operation performed in this activity
1182 private void updateAuthStatusIconAndText(RemoteOperationResult result
) {
1183 mAuthStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1185 switch (result
.getCode()) {
1187 mAuthStatusIcon
= android
.R
.drawable
.ic_secure
;
1188 mAuthStatusText
= R
.string
.auth_secure_connection
;
1193 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1194 mAuthStatusText
= R
.string
.auth_connection_established
;
1195 mAuthStatusIcon
= R
.drawable
.ic_ok
;
1197 mAuthStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1198 mAuthStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1202 case NO_NETWORK_CONNECTION
:
1203 mAuthStatusIcon
= R
.drawable
.no_network
;
1204 mAuthStatusText
= R
.string
.auth_no_net_conn_title
;
1207 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1208 mAuthStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1210 case BAD_OC_VERSION
:
1211 mAuthStatusText
= R
.string
.auth_bad_oc_version_title
;
1213 case WRONG_CONNECTION
:
1214 mAuthStatusText
= R
.string
.auth_wrong_connection_title
;
1217 mAuthStatusText
= R
.string
.auth_timeout_title
;
1219 case INCORRECT_ADDRESS
:
1220 mAuthStatusText
= R
.string
.auth_incorrect_address_title
;
1223 mAuthStatusText
= R
.string
.auth_ssl_general_error_title
;
1226 mAuthStatusText
= R
.string
.auth_unauthorized
;
1228 case HOST_NOT_AVAILABLE
:
1229 mAuthStatusText
= R
.string
.auth_unknown_host_title
;
1231 case INSTANCE_NOT_CONFIGURED
:
1232 mAuthStatusText
= R
.string
.auth_not_configured_title
;
1234 case FILE_NOT_FOUND
:
1235 mAuthStatusText
= R
.string
.auth_incorrect_path_title
;
1238 mAuthStatusText
= R
.string
.auth_oauth_error
;
1240 case OAUTH2_ERROR_ACCESS_DENIED
:
1241 mAuthStatusText
= R
.string
.auth_oauth_error_access_denied
;
1243 case ACCOUNT_NOT_NEW
:
1244 mAuthStatusText
= R
.string
.auth_account_not_new
;
1246 case ACCOUNT_NOT_THE_SAME
:
1247 mAuthStatusText
= R
.string
.auth_account_not_the_same
;
1249 case UNHANDLED_HTTP_CODE
:
1251 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
1254 mAuthStatusText
= 0;
1255 mAuthStatusIcon
= 0;
1260 private void updateStatusIconFailUserName(){
1261 mAuthStatusIcon
= R
.drawable
.common_error
;
1262 mAuthStatusText
= R
.string
.auth_fail_get_user_name
;
1265 private void updateServerStatusIconNoRegularAuth(){
1266 mServerStatusIcon
= R
.drawable
.common_error
;
1267 mServerStatusText
= R
.string
.auth_can_not_auth_against_server
;
1271 * Processes the result of the request for and access token send
1272 * to an OAuth authorization server.
1274 * @param result Result of the operation.
1276 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result
) {
1277 mWaitingForOpId
= Long
.MAX_VALUE
;
1278 dismissDialog(WAIT_DIALOG_TAG
);
1280 if (result
.isSuccess()) {
1281 /// be gentle with the user
1282 IndeterminateProgressDialog dialog
=
1283 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
1284 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
1286 /// time to test the retrieved access token on the ownCloud server
1287 @SuppressWarnings("unchecked")
1288 Map
<String
, String
> tokens
= (Map
<String
, String
>)(result
.getData().get(0));
1289 mAuthToken
= tokens
.get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
1290 //mAuthToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Constants.KEY_ACCESS_TOKEN);
1291 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mAuthToken
);
1293 accessRootFolderRemoteOperation("", "");
1296 updateAuthStatusIconAndText(result
);
1298 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1304 * Processes the result of the access check performed to try the user credentials.
1306 * Creates a new account through the AccountManager.
1308 * @param operation Access check performed.
1309 * @param result Result of the operation.
1311 private void onAuthorizationCheckFinish(RemoteOperationResult result
) {
1312 mWaitingForOpId
= Long
.MAX_VALUE
;
1313 dismissDialog(WAIT_DIALOG_TAG
);
1315 if (result
.isSuccess()) {
1316 Log_OC
.d(TAG
, "Successful access - time to save the account");
1318 boolean success
= false
;
1319 if (mAction
== ACTION_CREATE
) {
1320 success
= createAccount();
1331 } else if (result
.isServerFail() || result
.isException()) {
1332 /// server errors or exceptions in authorization take to requiring a new check of
1334 mServerIsChecked
= true
;
1335 mServerIsValid
= false
;
1336 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
1338 // update status icon and text
1339 updateServerStatusIconAndText(result
);
1341 mAuthStatusIcon
= 0;
1342 mAuthStatusText
= 0;
1345 // update input controls state
1346 showRefreshButton(true
);
1347 mOkButton
.setEnabled(false
);
1349 // very special case (TODO: move to a common place for all the remote operations) (dangerous here?)
1350 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1351 showUntrustedCertDialog(result
);
1354 } else { // authorization fail due to client side - probably wrong credentials
1355 updateAuthStatusIconAndText(result
);
1357 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1365 * Sets the proper response to get that the Account Authenticator that started this activity saves
1366 * a new authorization token for mAccount.
1368 private void updateToken() {
1369 Bundle response
= new Bundle();
1370 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1371 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
1373 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
1374 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1375 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1376 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1378 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
1380 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1381 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1382 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1385 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
1386 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
1388 setAccountAuthenticatorResult(response
);
1394 * Creates a new account through the Account Authenticator that started this activity.
1396 * This makes the account permanent.
1398 * TODO Decide how to name the OAuth accounts
1400 private boolean createAccount() {
1401 /// create and save new ownCloud account
1402 boolean isOAuth
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
);
1403 boolean isSaml
= AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
);
1405 Uri uri
= Uri
.parse(mServerInfo
.mBaseUrl
);
1406 String username
= mUsernameInput
.getText().toString().trim();
1408 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1410 String accountName
= com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.
1411 buildAccountName(uri
, username
);
1412 Account newAccount
= new Account(accountName
, MainApp
.getAccountType());
1413 if (AccountUtils
.exists(newAccount
, getApplicationContext())) {
1414 // fail - not a new account, but an existing one; disallow
1415 RemoteOperationResult result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_NEW
);
1416 updateAuthStatusIconAndText(result
);
1418 Log_OC
.d(TAG
, result
.getLogMessage());
1422 mAccount
= newAccount
;
1424 if (isOAuth
|| isSaml
) {
1425 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
); // with external authorizations, the password is never input in the app
1427 mAccountMgr
.addAccountExplicitly(mAccount
, mPasswordInput
.getText().toString(), null
);
1430 /// add the new account as default in preferences, if there is none already
1431 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1432 if (defaultAccount
== null
) {
1433 SharedPreferences
.Editor editor
= PreferenceManager
1434 .getDefaultSharedPreferences(this).edit();
1435 editor
.putString("select_oc_account", accountName
);
1439 /// prepare result to return to the Authenticator
1440 // TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done
1441 final Intent intent
= new Intent();
1442 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, MainApp
.getAccountType());
1443 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1445 intent.putExtra(AccountManager.KEY_AUTHTOKEN, MainApp.getAccountType()); */
1446 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1447 if (isOAuth
|| isSaml
) {
1448 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1450 /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
1451 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion());
1452 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_OC_BASE_URL
, mServerInfo
.mBaseUrl
);
1455 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
, "TRUE");
1456 } else if (isOAuth
) {
1457 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
, "TRUE");
1460 setAccountAuthenticatorResult(intent
.getExtras());
1461 setResult(RESULT_OK
, intent
);
1469 * Starts and activity to open the 'new account' page in the ownCloud web site
1471 * @param view 'Account register' button
1473 public void onRegisterClick(View view
) {
1474 Intent register
= new Intent(Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.welcome_link_url
)));
1475 setResult(RESULT_CANCELED
);
1476 startActivity(register
);
1481 * Updates the content and visibility state of the icon and text associated
1482 * to the last check on the ownCloud server.
1484 * @param serverStatusText Resource identifier of the text to show.
1485 * @param serverStatusIcon Resource identifier of the icon to show.
1487 private void showServerStatus() {
1488 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1489 mServerStatusView
.setVisibility(View
.INVISIBLE
);
1492 mServerStatusView
.setText(mServerStatusText
);
1493 mServerStatusView
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1494 mServerStatusView
.setVisibility(View
.VISIBLE
);
1501 * Updates the content and visibility state of the icon and text associated
1502 * to the interactions with the OAuth authorization server.
1504 private void showAuthStatus() {
1505 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1506 mAuthStatusView
.setVisibility(View
.INVISIBLE
);
1509 mAuthStatusView
.setText(mAuthStatusText
);
1510 mAuthStatusView
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1511 mAuthStatusView
.setVisibility(View
.VISIBLE
);
1516 private void showRefreshButton (boolean show
) {
1518 mRefreshButton
.setVisibility(View
.VISIBLE
);
1520 mRefreshButton
.setVisibility(View
.GONE
);
1525 * Called when the refresh button in the input field for ownCloud host is clicked.
1527 * Performs a new check on the URL in the input field.
1529 * @param view Refresh 'button'
1531 public void onRefreshClick(View view
) {
1537 * Called when the eye icon in the password field is clicked.
1539 * Toggles the visibility of the password in the field.
1541 public void onViewPasswordClick() {
1542 int selectionStart
= mPasswordInput
.getSelectionStart();
1543 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1544 if (isPasswordVisible()) {
1549 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1554 * Called when the checkbox for OAuth authorization is clicked.
1556 * Hides or shows the input fields for user & password.
1558 * @param view 'View password' 'button'
1560 public void onCheckClick(View view
) {
1561 CheckBox oAuth2Check
= (CheckBox
)view
;
1562 if (oAuth2Check
.isChecked()) {
1563 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1565 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1567 updateAuthenticationPreFragmentVisibility();
1572 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1574 * Used to trigger the authentication check when the user presses 'enter' after writing the password,
1575 * or to throw the server test when the only field on screen is the URL input field.
1578 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1579 if (actionId
== EditorInfo
.IME_ACTION_DONE
&& inputField
!= null
&& inputField
.equals(mPasswordInput
)) {
1580 if (mOkButton
.isEnabled()) {
1581 mOkButton
.performClick();
1584 } else if (actionId
== EditorInfo
.IME_ACTION_NEXT
&& inputField
!= null
&& inputField
.equals(mHostUrlInput
)) {
1585 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
1589 return false
; // always return false to grant that the software keyboard is hidden anyway
1593 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1595 private int fuzz
= 75;
1601 public boolean onTouch(View view
, MotionEvent event
) {
1602 Drawable rightDrawable
= null
;
1603 if (view
instanceof TextView
) {
1604 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1605 if (drawables
.length
> 2) {
1606 rightDrawable
= drawables
[2];
1609 if (rightDrawable
!= null
) {
1610 final int x
= (int) event
.getX();
1611 final int y
= (int) event
.getY();
1612 final Rect bounds
= rightDrawable
.getBounds();
1613 if (x
>= (view
.getRight() - bounds
.width() - fuzz
) && x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
)
1614 && y
>= (view
.getPaddingTop() - fuzz
) && y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1616 return onDrawableTouch(event
);
1622 public abstract boolean onDrawableTouch(final MotionEvent event
);
1626 private void getRemoteUserNameOperation(String sessionCookie
, boolean followRedirects
) {
1628 Intent getUserNameIntent
= new Intent();
1629 getUserNameIntent
.setAction(OperationsService
.ACTION_GET_USER_NAME
);
1630 getUserNameIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
1631 getUserNameIntent
.putExtra(OperationsService
.EXTRA_COOKIE
, sessionCookie
);
1633 if (mOperationsServiceBinder
!= null
) {
1634 //Log_OC.wtf(TAG, "starting getRemoteUserNameOperation..." );
1635 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(getUserNameIntent
);
1641 public void onSsoFinished(String sessionCookie
) {
1642 if (sessionCookie
!= null
&& sessionCookie
.length() > 0) {
1643 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1644 mAuthToken
= sessionCookie
;
1645 getRemoteUserNameOperation(sessionCookie
, true
);
1646 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1647 if (fd
!= null
&& fd
instanceof SherlockDialogFragment
) {
1648 Dialog d
= ((SherlockDialogFragment
)fd
).getDialog();
1649 if (d
!= null
&& d
.isShowing()) {
1656 Log_OC
.d(TAG
, "SSO failed");
1662 public boolean onTouchEvent(MotionEvent event
) {
1663 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
) &&
1664 mHostUrlInput
.hasFocus() && event
.getAction() == MotionEvent
.ACTION_DOWN
) {
1667 return super.onTouchEvent(event
);
1672 * Show untrusted cert dialog
1674 public void showUntrustedCertDialog(X509Certificate x509Certificate
, SslError error
, SslErrorHandler handler
) {
1675 // Show a dialog with the certificate info
1676 SslUntrustedCertDialog dialog
= null
;
1677 if (x509Certificate
== null
) {
1678 dialog
= SslUntrustedCertDialog
.newInstanceForEmptySslError(error
, handler
);
1680 dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(x509Certificate
, error
, handler
);
1682 FragmentManager fm
= getSupportFragmentManager();
1683 FragmentTransaction ft
= fm
.beginTransaction();
1684 ft
.addToBackStack(null
);
1685 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1689 * Show untrusted cert dialog
1691 private void showUntrustedCertDialog(RemoteOperationResult result
) {
1692 // Show a dialog with the certificate info
1693 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1694 FragmentManager fm
= getSupportFragmentManager();
1695 FragmentTransaction ft
= fm
.beginTransaction();
1696 ft
.addToBackStack(null
);
1697 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1702 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1704 public void onSavedCertificate() {
1705 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1707 // if SAML dialog is not shown, the SslDialog was shown due to an SSL error in the server check
1713 * Called from SslValidatorDialog when a new server certificate could not be saved
1714 * when the user requested it.
1717 public void onFailedSavingCertificate() {
1718 dismissDialog(SAML_DIALOG_TAG
);
1719 Toast
.makeText(this, R
.string
.ssl_validator_not_saved
, Toast
.LENGTH_LONG
).show();
1723 public void onCancelCertificate() {
1724 dismissDialog(SAML_DIALOG_TAG
);
1728 private void doOnResumeAndBound() {
1729 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1730 mOperationsServiceBinder
.addOperationListener(AuthenticatorActivity
.this, mHandler
);
1731 if (mWaitingForOpId
<= Integer
.MAX_VALUE
) {
1732 mOperationsServiceBinder
.dispatchResultIfFinished((int)mWaitingForOpId
, this);
1735 if (mPendingAutoCheck
) {
1741 private void dismissDialog(String dialogTag
){
1742 Fragment frag
= getSupportFragmentManager().findFragmentByTag(dialogTag
);
1743 if (frag
!= null
&& frag
instanceof SherlockDialogFragment
) {
1744 SherlockDialogFragment dialog
= (SherlockDialogFragment
) frag
;
1751 * Implements callback methods for service binding.
1753 private class OperationsServiceConnection
implements ServiceConnection
{
1756 public void onServiceConnected(ComponentName component
, IBinder service
) {
1757 if (component
.equals(new ComponentName(AuthenticatorActivity
.this, OperationsService
.class))) {
1758 //Log_OC.wtf(TAG, "Operations service connected");
1759 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
1761 doOnResumeAndBound();
1770 public void onServiceDisconnected(ComponentName component
) {
1771 if (component
.equals(new ComponentName(AuthenticatorActivity
.this, OperationsService
.class))) {
1772 Log_OC
.e(TAG
, "Operations service crashed");
1773 mOperationsServiceBinder
= null
;