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
.lib
.common
.network
.CertificateCombinedException
;
68 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
69 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
70 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
71 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
72 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
73 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
74 import com
.owncloud
.android
.lib
.resources
.users
.GetRemoteUserNameOperation
;
75 import com
.owncloud
.android
.operations
.DetectAuthenticationMethodOperation
.AuthenticationMethod
;
76 import com
.owncloud
.android
.operations
.GetServerInfoOperation
;
77 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
78 import com
.owncloud
.android
.services
.OperationsService
;
79 import com
.owncloud
.android
.services
.OperationsService
.OperationsServiceBinder
;
80 import com
.owncloud
.android
.ui
.dialog
.IndeterminateProgressDialog
;
81 import com
.owncloud
.android
.ui
.dialog
.SamlWebViewDialog
;
82 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
83 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
84 import com
.owncloud
.android
.utils
.Log_OC
;
87 * This Activity is used to add an ownCloud account to the App
89 * @author Bartek Przybylski
90 * @author David A. Velasco
93 public class AuthenticatorActivity
extends AccountAuthenticatorActivity
94 implements OnRemoteOperationListener
, OnFocusChangeListener
, OnEditorActionListener
,
95 SsoWebViewClientListener
, OnSslUntrustedCertListener
{
97 private static final String TAG
= AuthenticatorActivity
.class.getSimpleName();
99 public static final String EXTRA_ACTION
= "ACTION";
100 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
102 private static final String KEY_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
104 private static final String KEY_HOST_URL_TEXT
= "HOST_URL_TEXT";
105 private static final String KEY_OC_VERSION
= "OC_VERSION";
106 private static final String KEY_SERVER_VALID
= "SERVER_VALID";
107 private static final String KEY_SERVER_CHECKED
= "SERVER_CHECKED";
108 private static final String KEY_SERVER_STATUS_TEXT
= "SERVER_STATUS_TEXT";
109 private static final String KEY_SERVER_STATUS_ICON
= "SERVER_STATUS_ICON";
110 private static final String KEY_IS_SSL_CONN
= "IS_SSL_CONN";
111 private static final String KEY_PASSWORD_EXPOSED
= "PASSWORD_VISIBLE";
112 private static final String KEY_AUTH_STATUS_TEXT
= "AUTH_STATUS_TEXT";
113 private static final String KEY_AUTH_STATUS_ICON
= "AUTH_STATUS_ICON";
114 private static final String KEY_SERVER_AUTH_METHOD
= "SERVER_AUTH_METHOD";
115 private static final String KEY_WAITING_FOR_OP_ID
= "WAITING_FOR_OP_ID";
116 private static final String KEY_AUTH_TOKEN
= "AUTH_TOKEN";
118 private static final String AUTH_ON
= "on";
119 private static final String AUTH_OPTIONAL
= "optional";
121 public static final byte ACTION_CREATE
= 0;
122 public static final byte ACTION_UPDATE_TOKEN
= 1; // requested by the user
123 public static final byte ACTION_UPDATE_EXPIRED_TOKEN
= 2; // detected by the app
125 private static final String UNTRUSTED_CERT_DIALOG_TAG
= "UNTRUSTED_CERT_DIALOG";
126 private static final String SAML_DIALOG_TAG
= "SAML_DIALOG";
127 private static final String WAIT_DIALOG_TAG
= "WAIT_DIALOG";
130 /// parameters from EXTRAs in starter Intent
131 private byte mAction
;
132 private Account mAccount
;
133 private String mAuthTokenType
;
136 /// activity-level references / state
137 private final Handler mHandler
= new Handler();
138 private ServiceConnection mOperationsServiceConnection
= null
;
139 private OperationsServiceBinder mOperationsServiceBinder
= null
;
140 private AccountManager mAccountMgr
;
141 private Uri mNewCapturedUriFromOAuth2Redirection
;
144 /// Server PRE-Fragment elements
145 private EditText mHostUrlInput
;
146 private View mRefreshButton
;
147 private TextView mServerStatusView
;
149 private TextWatcher mHostUrlInputWatcher
;
150 private int mServerStatusText
= 0, mServerStatusIcon
= 0;
152 private boolean mServerIsChecked
= false
;
153 private boolean mServerIsValid
= false
;
154 private boolean mPendingAutoCheck
= false
;
156 private GetServerInfoOperation
.ServerInfo mServerInfo
=
157 new GetServerInfoOperation
.ServerInfo();
160 /// Authentication PRE-Fragment elements
161 private CheckBox mOAuth2Check
;
162 private TextView mOAuthAuthEndpointText
;
163 private TextView mOAuthTokenEndpointText
;
164 private EditText mUsernameInput
;
165 private EditText mPasswordInput
;
166 private View mOkButton
;
167 private TextView mAuthStatusView
;
169 private int mAuthStatusText
= 0, mAuthStatusIcon
= 0;
171 private String mAuthToken
= "";
174 /// Identifier of operation in progress which result shouldn't be lost
175 private long mWaitingForOpId
= Long
.MAX_VALUE
;
181 * IMPORTANT ENTRY POINT 1: activity is shown to the user
184 protected void onCreate(Bundle savedInstanceState
) {
185 //Log_OC.wtf(TAG, "onCreate init");
186 super.onCreate(savedInstanceState
);
187 getWindow().requestFeature(Window
.FEATURE_NO_TITLE
);
189 // bind to Operations Service
190 mOperationsServiceConnection
= new OperationsServiceConnection();
191 if (!bindService(new Intent(this, OperationsService
.class),
192 mOperationsServiceConnection
,
193 Context
.BIND_AUTO_CREATE
)) {
195 R
.string
.error_cant_bind_to_operations_service
,
201 /// init activity state
202 mAccountMgr
= AccountManager
.get(this);
203 mNewCapturedUriFromOAuth2Redirection
= null
;
206 mAction
= getIntent().getByteExtra(EXTRA_ACTION
, ACTION_CREATE
);
207 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
208 if (savedInstanceState
== null
) {
211 mAuthTokenType
= savedInstanceState
.getString(KEY_AUTH_TOKEN_TYPE
);
212 mWaitingForOpId
= savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
);
215 /// load user interface
216 setContentView(R
.layout
.account_setup
);
218 /// initialize general UI elements
219 initOverallUi(savedInstanceState
);
221 mOkButton
= findViewById(R
.id
.buttonOK
);
223 /// initialize block to be moved to single Fragment to check server and get info about it
224 initServerPreFragment(savedInstanceState
);
226 /// initialize block to be moved to single Fragment to retrieve and validate credentials
227 initAuthorizationPreFragment(savedInstanceState
);
229 //Log_OC.wtf(TAG, "onCreate end");
232 private void initAuthTokenType() {
234 getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
235 if (mAuthTokenType
== null
) {
236 if (mAccount
!= null
) {
237 boolean oAuthRequired
=
238 (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
) != null
);
239 boolean samlWebSsoRequired
=
240 (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
) != null
);
241 mAuthTokenType
= chooseAuthTokenType(oAuthRequired
, samlWebSsoRequired
);
244 boolean oAuthSupported
= AUTH_ON
.equals(getString(R
.string
.auth_method_oauth2
));
245 boolean samlWebSsoSupported
= AUTH_ON
.equals(getString(R
.string
.auth_method_saml_web_sso
));
246 mAuthTokenType
= chooseAuthTokenType(oAuthSupported
, samlWebSsoSupported
);
251 private String
chooseAuthTokenType(boolean oauth
, boolean saml
) {
253 return AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
255 return AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
257 return AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
263 * Configures elements in the user interface under direct control of the Activity.
265 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
267 private void initOverallUi(Bundle savedInstanceState
) {
269 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
270 boolean isWelcomeLinkVisible
= getResources().getBoolean(R
.bool
.show_welcome_link
);
272 String instructionsMessageText
= null
;
273 if (mAction
== ACTION_UPDATE_EXPIRED_TOKEN
) {
274 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
275 .equals(mAuthTokenType
)) {
276 instructionsMessageText
= getString(R
.string
.auth_expired_oauth_token_toast
);
278 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType())
279 .equals(mAuthTokenType
)) {
280 instructionsMessageText
= getString(R
.string
.auth_expired_saml_sso_token_toast
);
283 instructionsMessageText
= getString(R
.string
.auth_expired_basic_auth_toast
);
287 /// step 2 - set properties of UI elements (text, visibility, enabled...)
288 Button welcomeLink
= (Button
) findViewById(R
.id
.welcome_link
);
289 welcomeLink
.setVisibility(isWelcomeLinkVisible ? View
.VISIBLE
: View
.GONE
);
291 String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
293 TextView instructionsView
= (TextView
) findViewById(R
.id
.instructions_message
);
294 if (instructionsMessageText
!= null
) {
295 instructionsView
.setVisibility(View
.VISIBLE
);
296 instructionsView
.setText(instructionsMessageText
);
298 instructionsView
.setVisibility(View
.GONE
);
305 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
307 private void initServerPreFragment(Bundle savedInstanceState
) {
309 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
310 boolean isUrlInputAllowed
= getResources().getBoolean(R
.bool
.show_server_url_input
);
311 if (savedInstanceState
== null
) {
312 if (mAccount
!= null
) {
313 mServerInfo
.mBaseUrl
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_BASE_URL
);
314 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://"); // TODO do this in a setter for mBaseUrl
315 String ocVersion
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_VERSION
);
316 if (ocVersion
!= null
) {
317 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
320 mServerInfo
.mBaseUrl
= getString(R
.string
.server_url
).trim();
321 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
324 mServerStatusText
= savedInstanceState
.getInt(KEY_SERVER_STATUS_TEXT
);
325 mServerStatusIcon
= savedInstanceState
.getInt(KEY_SERVER_STATUS_ICON
);
327 mServerIsValid
= savedInstanceState
.getBoolean(KEY_SERVER_VALID
);
328 mServerIsChecked
= savedInstanceState
.getBoolean(KEY_SERVER_CHECKED
);
331 mServerInfo
.mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
332 mServerInfo
.mBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
333 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
334 if (ocVersion
!= null
) {
335 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
337 mServerInfo
.mAuthMethod
= AuthenticationMethod
.valueOf(
338 savedInstanceState
.getString(KEY_SERVER_AUTH_METHOD
));
342 /// step 2 - set properties of UI elements (text, visibility, enabled...)
343 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
344 mHostUrlInput
.setText(mServerInfo
.mBaseUrl
);
345 if (mAction
!= ACTION_CREATE
) {
346 /// lock things that should not change
347 mHostUrlInput
.setEnabled(false
);
348 mHostUrlInput
.setFocusable(false
);
350 if (isUrlInputAllowed
) {
351 mRefreshButton
= findViewById(R
.id
.embeddedRefreshButton
);
353 findViewById(R
.id
.hostUrlFrame
).setVisibility(View
.GONE
);
354 mRefreshButton
= findViewById(R
.id
.centeredRefreshButton
);
356 showRefreshButton(mServerIsChecked
&& !mServerIsValid
&&
357 mWaitingForOpId
> Integer
.MAX_VALUE
);
358 mServerStatusView
= (TextView
) findViewById(R
.id
.server_status_text
);
361 /// step 3 - bind some listeners and options
362 mHostUrlInput
.setImeOptions(EditorInfo
.IME_ACTION_NEXT
);
363 mHostUrlInput
.setOnEditorActionListener(this);
365 /// step 4 - create listeners that will be bound at onResume
366 mHostUrlInputWatcher
= new TextWatcher() {
369 public void afterTextChanged(Editable s
) {
370 if (mOkButton
.isEnabled() &&
371 !mServerInfo
.mBaseUrl
.equals(
372 normalizeUrl(s
.toString(), mServerInfo
.mIsSslConn
))) {
373 mOkButton
.setEnabled(false
);
378 public void beforeTextChanged(CharSequence s
, int start
, int count
, int after
) {
382 public void onTextChanged(CharSequence s
, int start
, int before
, int count
) {
383 if (mAuthStatusIcon
!= 0) {
384 Log_OC
.d(TAG
, "onTextChanged: hiding authentication status");
393 // TODO find out if this is really necessary, or if it can done in a different way
394 findViewById(R
.id
.scroll
).setOnTouchListener(new OnTouchListener() {
396 public boolean onTouch(View view
, MotionEvent event
) {
397 if (event
.getAction() == MotionEvent
.ACTION_DOWN
) {
398 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
) &&
399 mHostUrlInput
.hasFocus()) {
408 /// step 4 - mark automatic check to be started when OperationsService is ready
409 mPendingAutoCheck
= (savedInstanceState
== null
&&
410 (mAction
!= ACTION_CREATE
|| !isUrlInputAllowed
));
416 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
418 private void initAuthorizationPreFragment(Bundle savedInstanceState
) {
420 /// step 0 - get UI elements in layout
421 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
422 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
423 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
424 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
425 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
426 mAuthStatusView
= (TextView
) findViewById(R
.id
.auth_status_text
);
428 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
429 String presetUserName
= null
;
430 boolean isPasswordExposed
= false
;
431 if (savedInstanceState
== null
) {
432 if (mAccount
!= null
) {
433 presetUserName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
437 isPasswordExposed
= savedInstanceState
.getBoolean(KEY_PASSWORD_EXPOSED
, false
);
438 mAuthStatusText
= savedInstanceState
.getInt(KEY_AUTH_STATUS_TEXT
);
439 mAuthStatusIcon
= savedInstanceState
.getInt(KEY_AUTH_STATUS_ICON
);
440 mAuthToken
= savedInstanceState
.getString(KEY_AUTH_TOKEN
);
443 /// step 2 - set properties of UI elements (text, visibility, enabled...)
444 mOAuth2Check
.setChecked(
445 AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
446 .equals(mAuthTokenType
));
447 if (presetUserName
!= null
) {
448 mUsernameInput
.setText(presetUserName
);
450 if (mAction
!= ACTION_CREATE
) {
451 mUsernameInput
.setEnabled(false
);
452 mUsernameInput
.setFocusable(false
);
454 mPasswordInput
.setText(""); // clean password to avoid social hacking
455 if (isPasswordExposed
) {
458 updateAuthenticationPreFragmentVisibility();
460 mOkButton
.setEnabled(mServerIsValid
);
463 /// step 3 - bind listeners
464 // bindings for password input field
465 mPasswordInput
.setOnFocusChangeListener(this);
466 mPasswordInput
.setImeOptions(EditorInfo
.IME_ACTION_DONE
);
467 mPasswordInput
.setOnEditorActionListener(this);
468 mPasswordInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
470 public boolean onDrawableTouch(final MotionEvent event
) {
471 if (event
.getAction() == MotionEvent
.ACTION_UP
) {
472 AuthenticatorActivity
.this.onViewPasswordClick();
482 * Changes the visibility of input elements depending on
483 * the current authorization method.
485 private void updateAuthenticationPreFragmentVisibility () {
486 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
487 equals(mAuthTokenType
)) {
488 // SAML-based web Single Sign On
489 mOAuth2Check
.setVisibility(View
.GONE
);
490 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
491 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
492 mUsernameInput
.setVisibility(View
.GONE
);
493 mPasswordInput
.setVisibility(View
.GONE
);
496 if (mAction
== ACTION_CREATE
&&
497 AUTH_OPTIONAL
.equals(getString(R
.string
.auth_method_oauth2
))) {
498 mOAuth2Check
.setVisibility(View
.VISIBLE
);
500 mOAuth2Check
.setVisibility(View
.GONE
);
503 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
504 equals(mAuthTokenType
)) {
505 // OAuth 2 authorization
507 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
508 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
509 mUsernameInput
.setVisibility(View
.GONE
);
510 mPasswordInput
.setVisibility(View
.GONE
);
513 // basic HTTP authorization
514 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
515 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
516 mUsernameInput
.setVisibility(View
.VISIBLE
);
517 mPasswordInput
.setVisibility(View
.VISIBLE
);
525 * Saves relevant state before {@link #onPause()}
527 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag, intended to defer the
528 * processing of the redirection caught in {@link #onNewIntent(Intent)} until {@link #onResume()}
530 * See {@link #loadSavedInstanceState(Bundle)}
533 protected void onSaveInstanceState(Bundle outState
) {
534 //Log_OC.wtf(TAG, "onSaveInstanceState init" );
535 super.onSaveInstanceState(outState
);
538 outState
.putString(KEY_AUTH_TOKEN_TYPE
, mAuthTokenType
);
539 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mWaitingForOpId
);
541 /// Server PRE-fragment state
542 outState
.putInt(KEY_SERVER_STATUS_TEXT
, mServerStatusText
);
543 outState
.putInt(KEY_SERVER_STATUS_ICON
, mServerStatusIcon
);
544 outState
.putBoolean(KEY_SERVER_CHECKED
, mServerIsChecked
);
545 outState
.putBoolean(KEY_SERVER_VALID
, mServerIsValid
);
546 outState
.putBoolean(KEY_IS_SSL_CONN
, mServerInfo
.mIsSslConn
);
547 outState
.putString(KEY_HOST_URL_TEXT
, mServerInfo
.mBaseUrl
);
548 if (mServerInfo
.mVersion
!= null
) {
549 outState
.putString(KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion());
551 outState
.putString(KEY_SERVER_AUTH_METHOD
, mServerInfo
.mAuthMethod
.name());
553 /// Authentication PRE-fragment state
554 outState
.putBoolean(KEY_PASSWORD_EXPOSED
, isPasswordVisible());
555 outState
.putInt(KEY_AUTH_STATUS_ICON
, mAuthStatusIcon
);
556 outState
.putInt(KEY_AUTH_STATUS_TEXT
, mAuthStatusText
);
557 outState
.putString(KEY_AUTH_TOKEN
, mAuthToken
);
559 //Log_OC.wtf(TAG, "onSaveInstanceState end" );
564 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION request
567 * To make this possible, this activity needs to be qualified with android:launchMode = "singleTask" in the
568 * AndroidManifest.xml file.
571 protected void onNewIntent (Intent intent
) {
572 Log_OC
.d(TAG
, "onNewIntent()");
573 Uri data
= intent
.getData();
574 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
575 mNewCapturedUriFromOAuth2Redirection
= data
;
581 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION, and
582 * deferred in {@link #onNewIntent(Intent)}, is processed here.
585 protected void onResume() {
586 //Log_OC.wtf(TAG, "onResume init" );
589 // bound here to avoid spurious changes triggered by Android on device rotations
590 mHostUrlInput
.setOnFocusChangeListener(this);
591 mHostUrlInput
.addTextChangedListener(mHostUrlInputWatcher
);
593 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
594 getOAuth2AccessTokenFromCapturedRedirection();
597 if (mOperationsServiceBinder
!= null
) {
598 doOnResumeAndBound();
601 //Log_OC.wtf(TAG, "onResume end" );
606 protected void onPause() {
607 //Log_OC.wtf(TAG, "onPause init" );
608 if (mOperationsServiceBinder
!= null
) {
609 //Log_OC.wtf(TAG, "unregistering to listen for operation callbacks" );
610 mOperationsServiceBinder
.removeOperationListener(this);
613 mHostUrlInput
.removeTextChangedListener(mHostUrlInputWatcher
);
614 mHostUrlInput
.setOnFocusChangeListener(null
);
617 //Log_OC.wtf(TAG, "onPause end" );
621 protected void onDestroy() {
623 mHostUrlInputWatcher
= null
;
625 if (mOperationsServiceConnection
!= null
) {
626 unbindService(mOperationsServiceConnection
);
627 mOperationsServiceBinder
= null
;
634 * Parses the redirection with the response to the GET AUTHORIZATION request to the
635 * oAuth server and requests for the access token (GET ACCESS TOKEN)
637 private void getOAuth2AccessTokenFromCapturedRedirection() {
638 /// Parse data from OAuth redirection
639 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
640 mNewCapturedUriFromOAuth2Redirection
= null
;
642 /// Showing the dialog with instructions for the user.
643 IndeterminateProgressDialog dialog
=
644 IndeterminateProgressDialog
.newInstance(R
.string
.auth_getting_authorization
, true
);
645 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
647 /// GET ACCESS TOKEN to the oAuth server
648 Intent getServerInfoIntent
= new Intent();
649 getServerInfoIntent
.setAction(OperationsService
.ACTION_OAUTH2_GET_ACCESS_TOKEN
);
651 getServerInfoIntent
.putExtra(
652 OperationsService
.EXTRA_SERVER_URL
,
653 mOAuthTokenEndpointText
.getText().toString().trim());
655 getServerInfoIntent
.putExtra(
656 OperationsService
.EXTRA_OAUTH2_QUERY_PARAMETERS
,
659 if (mOperationsServiceBinder
!= null
) {
660 //Log_OC.wtf(TAG, "getting access token..." );
661 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(getServerInfoIntent
);
668 * Handles the change of focus on the text inputs for the server URL and the password
670 public void onFocusChange(View view
, boolean hasFocus
) {
671 if (view
.getId() == R
.id
.hostUrlInput
) {
673 onUrlInputFocusLost((TextView
) view
);
676 showRefreshButton(false
);
679 } else if (view
.getId() == R
.id
.account_password
) {
680 onPasswordFocusChanged((TextView
) view
, hasFocus
);
686 * Handles changes in focus on the text input for the server URL.
688 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
689 * other field. The operation to check the existence of the server in the entered URL is
692 * When hasFocus: user 'comes back' to write again the server URL.
694 * @param hostInput TextView with the URL input field receiving the change of focus.
696 private void onUrlInputFocusLost(TextView hostInput
) {
697 if (!mServerInfo
.mBaseUrl
.equals(
698 normalizeUrl(mHostUrlInput
.getText().toString(), mServerInfo
.mIsSslConn
))) {
699 // check server again only if the user changed something in the field
702 mOkButton
.setEnabled(mServerIsValid
);
703 showRefreshButton(!mServerIsValid
);
708 private void checkOcServer() {
709 String uri
= mHostUrlInput
.getText().toString().trim();
710 mServerIsValid
= false
;
711 mServerIsChecked
= false
;
712 mOkButton
.setEnabled(false
);
713 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
714 showRefreshButton(false
);
716 if (uri
.length() != 0) {
717 mServerStatusText
= R
.string
.auth_testing_connection
;
718 mServerStatusIcon
= R
.drawable
.progress_small
;
721 Intent getServerInfoIntent
= new Intent();
722 getServerInfoIntent
.setAction(OperationsService
.ACTION_GET_SERVER_INFO
);
723 getServerInfoIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, uri
);
724 if (mOperationsServiceBinder
!= null
) {
725 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(getServerInfoIntent
);
727 Log_OC
.wtf(TAG
, "Server check tried with OperationService unbound!" );
731 mServerStatusText
= 0;
732 mServerStatusIcon
= 0;
739 * Handles changes in focus on the text input for the password (basic authorization).
741 * When (hasFocus), the button to toggle password visibility is shown.
743 * When (!hasFocus), the button is made invisible and the password is hidden.
745 * @param passwordInput TextView with the password input field receiving the change of focus.
746 * @param hasFocus 'True' if focus is received, 'false' if is lost
748 private void onPasswordFocusChanged(TextView passwordInput
, boolean hasFocus
) {
750 showViewPasswordButton();
753 hidePasswordButton();
758 private void showViewPasswordButton() {
759 int drawable
= R
.drawable
.ic_view
;
760 if (isPasswordVisible()) {
761 drawable
= R
.drawable
.ic_hide
;
763 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable
, 0);
766 private boolean isPasswordVisible() {
767 return ((mPasswordInput
.getInputType() & InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) == InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
770 private void hidePasswordButton() {
771 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
774 private void showPassword() {
775 mPasswordInput
.setInputType(InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
776 showViewPasswordButton();
779 private void hidePassword() {
780 mPasswordInput
.setInputType(InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
);
781 showViewPasswordButton();
785 * Checks the credentials of the user in the root of the ownCloud server
786 * before creating a new local account.
788 * For basic authorization, a check of existence of the root folder is
791 * For OAuth, starts the flow to get an access token; the credentials test
792 * is postponed until it is available.
794 * IMPORTANT ENTRY POINT 4
796 * @param view OK button
798 public void onOkClick(View view
) {
799 // this check should be unnecessary
800 if (mServerInfo
.mVersion
== null
||
801 !mServerInfo
.mVersion
.isVersionValid() ||
802 mServerInfo
.mBaseUrl
== null
||
803 mServerInfo
.mBaseUrl
.length() == 0) {
804 mServerStatusIcon
= R
.drawable
.common_error
;
805 mServerStatusText
= R
.string
.auth_wtf_reenter_URL
;
807 mOkButton
.setEnabled(false
);
808 //Log_OC.wtf(TAG, "The user was allowed to click 'connect' to an unchecked server!!");
812 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
813 startOauthorization();
814 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
815 startSamlBasedFederatedSingleSignOnAuthorization();
817 checkBasicAuthorization();
823 * Tests the credentials entered by the user performing a check of existence on
824 * the root folder of the ownCloud server.
826 private void checkBasicAuthorization() {
827 /// get basic credentials entered by user
828 String username
= mUsernameInput
.getText().toString();
829 String password
= mPasswordInput
.getText().toString();
831 /// be gentle with the user
832 IndeterminateProgressDialog dialog
=
833 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
834 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
836 /// validate credentials accessing the root folder
837 accessRootFolderRemoteOperation(username
, password
);
841 private void accessRootFolderRemoteOperation(String username
, String password
) {
842 Intent existenceCheckIntent
= new Intent();
843 existenceCheckIntent
.setAction(OperationsService
.ACTION_EXISTENCE_CHECK
);
844 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
845 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_REMOTE_PATH
, "/");
846 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_USERNAME
, username
);
847 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_PASSWORD
, password
);
848 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_AUTH_TOKEN
, mAuthToken
);
850 if (mOperationsServiceBinder
!= null
) {
851 //Log_OC.wtf(TAG, "starting existenceCheckRemoteOperation..." );
852 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(existenceCheckIntent
);
857 * Starts the OAuth 'grant type' flow to get an access token, with
858 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
860 private void startOauthorization() {
861 // be gentle with the user
862 mAuthStatusIcon
= R
.drawable
.progress_small
;
863 mAuthStatusText
= R
.string
.oauth_login_connection
;
866 // GET AUTHORIZATION request
867 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
868 Uri
.Builder uriBuilder
= uri
.buildUpon();
869 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
));
870 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
));
871 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
));
872 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
));
873 uri
= uriBuilder
.build();
874 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
875 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
881 * Starts the Web Single Sign On flow to get access to the root folder
884 private void startSamlBasedFederatedSingleSignOnAuthorization() {
885 // be gentle with the user
886 mAuthStatusIcon
= R
.drawable
.progress_small
;
887 mAuthStatusText
= R
.string
.auth_connecting_auth_server
;
889 IndeterminateProgressDialog dialog
=
890 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
891 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
893 /// validate credentials accessing the root folder
894 accessRootFolderRemoteOperation("", "");
899 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
901 * Dispatches the operation flow to the right method.
904 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
906 if (operation
instanceof GetServerInfoOperation
) {
907 if (operation
.hashCode() == mWaitingForOpId
) {
908 onGetServerInfoFinish(result
);
909 } // else nothing ; only the last check operation is considered;
910 // multiple can be started if the user amends a URL quickly
912 } else if (operation
instanceof OAuth2GetAccessToken
) {
913 onGetOAuthAccessTokenFinish(result
);
915 } else if (operation
instanceof ExistenceCheckRemoteOperation
) {
916 //Log_OC.wtf(TAG, "received detection response through callback" );
917 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
918 onSamlBasedFederatedSingleSignOnAuthorizationStart(result
);
921 onAuthorizationCheckFinish(result
);
923 } else if (operation
instanceof GetRemoteUserNameOperation
) {
924 onGetUserNameFinish(result
);
929 private void onGetUserNameFinish(RemoteOperationResult result
) {
930 mWaitingForOpId
= Long
.MAX_VALUE
;
931 if (result
.isSuccess()) {
932 boolean success
= false
;
933 String username
= (String
) result
.getData().get(0);
935 if ( mAction
== ACTION_CREATE
) {
936 mUsernameInput
.setText(username
);
937 success
= createAccount();
940 if (!mUsernameInput
.getText().toString().equals(username
)) {
941 // fail - not a new account, but an existing one; disallow
942 result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_THE_SAME
);
944 OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(
946 Uri.parse(mServerInfo.mBaseUrl),
947 OwnCloudCredentialsFactory.newSamlSsoCredentials(mAuthToken))
951 updateAuthStatusIconAndText(result
);
953 Log_OC
.d(TAG
, result
.getLogMessage());
963 updateStatusIconFailUserName();
965 Log_OC
.e(TAG
, "Access to user name failed: " + result
.getLogMessage());
970 private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperationResult result
) {
971 mWaitingForOpId
= Long
.MAX_VALUE
;
972 dismissDialog(WAIT_DIALOG_TAG
);
974 if (result
.isIdPRedirection()) {
975 String url
= result
.getRedirectedLocation();
976 String targetUrl
= mServerInfo
.mBaseUrl
977 + AccountUtils
.getWebdavPath(mServerInfo
.mVersion
, mAuthTokenType
);
980 SamlWebViewDialog dialog
= SamlWebViewDialog
.newInstance(url
, targetUrl
);
981 dialog
.show(getSupportFragmentManager(), SAML_DIALOG_TAG
);
987 mAuthStatusIcon
= R
.drawable
.common_error
;
988 mAuthStatusText
= R
.string
.auth_unsupported_auth_method
;
996 * Processes the result of the server check performed when the user finishes the enter of the
999 * @param operation Server check performed.
1000 * @param result Result of the check.
1002 private void onGetServerInfoFinish(RemoteOperationResult result
) {
1003 /// update activity state
1004 mServerIsChecked
= true
;
1005 mWaitingForOpId
= Long
.MAX_VALUE
;
1007 // update server status, but don't show it yet
1008 updateServerStatusIconAndText(result
);
1010 if (result
.isSuccess()) {
1012 // 1. connection succeeded, and we know if it's SSL or not
1013 // 2. server is installed
1014 // 3. we got the server version
1015 // 4. we got the authentication method required by the server
1016 mServerInfo
= (GetServerInfoOperation
.ServerInfo
) (result
.getData().get(0));
1018 if (!authSupported(mServerInfo
.mAuthMethod
)) {
1020 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1021 mServerIsValid
= false
;
1024 mServerIsValid
= true
;
1028 mServerIsValid
= false
;
1032 showRefreshButton(!mServerIsValid
);
1034 mOkButton
.setEnabled(mServerIsValid
);
1036 /// very special case (TODO: move to a common place for all the remote operations)
1037 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1038 showUntrustedCertDialog(result
);
1043 private boolean authSupported(AuthenticationMethod authMethod
) {
1044 String basic
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1045 String oAuth
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1046 String saml
= AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
1048 return (( mAuthTokenType
.equals(basic
) &&
1049 authMethod
.equals(AuthenticationMethod
.BASIC_HTTP_AUTH
) ) ||
1050 ( mAuthTokenType
.equals(oAuth
) &&
1051 authMethod
.equals(AuthenticationMethod
.BEARER_TOKEN
)) ||
1052 ( mAuthTokenType
.equals(saml
) &&
1053 authMethod
.equals(AuthenticationMethod
.SAML_WEB_SSO
))
1058 // TODO remove, if possible
1059 private String
normalizeUrl(String url
, boolean sslWhenUnprefixed
) {
1060 if (url
!= null
&& url
.length() > 0) {
1062 if (!url
.toLowerCase().startsWith("http://") &&
1063 !url
.toLowerCase().startsWith("https://")) {
1064 if (sslWhenUnprefixed
) {
1065 url
= "https://" + url
;
1067 url
= "http://" + url
;
1071 url
= trimUrlWebdav(url
);
1073 if (url
.endsWith("/")) {
1074 url
= url
.substring(0, url
.length() - 1);
1078 return (url
!= null ? url
: "");
1082 // TODO remove, if possible
1083 private String
trimUrlWebdav(String url
){
1084 if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_4_0
)){
1085 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_4_0
.length());
1086 } else if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_2_0
)){
1087 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_2_0
.length());
1088 } else if (url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_1_2
)){
1089 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_1_2
.length());
1091 return (url
!= null ? url
: "");
1096 * Chooses the right icon and text to show to the user for the received operation result.
1098 * @param result Result of a remote operation performed in this activity
1100 private void updateServerStatusIconAndText(RemoteOperationResult result
) {
1101 mServerStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1103 switch (result
.getCode()) {
1105 mServerStatusIcon
= android
.R
.drawable
.ic_secure
;
1106 mServerStatusText
= R
.string
.auth_secure_connection
;
1111 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1112 mServerStatusText
= R
.string
.auth_connection_established
;
1113 mServerStatusIcon
= R
.drawable
.ic_ok
;
1115 mServerStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1116 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1120 case NO_NETWORK_CONNECTION
:
1121 mServerStatusIcon
= R
.drawable
.no_network
;
1122 mServerStatusText
= R
.string
.auth_no_net_conn_title
;
1125 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1126 mServerStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1128 case BAD_OC_VERSION
:
1129 mServerStatusText
= R
.string
.auth_bad_oc_version_title
;
1131 case WRONG_CONNECTION
:
1132 mServerStatusText
= R
.string
.auth_wrong_connection_title
;
1135 mServerStatusText
= R
.string
.auth_timeout_title
;
1137 case INCORRECT_ADDRESS
:
1138 mServerStatusText
= R
.string
.auth_incorrect_address_title
;
1141 mServerStatusText
= R
.string
.auth_ssl_general_error_title
;
1144 mServerStatusText
= R
.string
.auth_unauthorized
;
1146 case HOST_NOT_AVAILABLE
:
1147 mServerStatusText
= R
.string
.auth_unknown_host_title
;
1149 case INSTANCE_NOT_CONFIGURED
:
1150 mServerStatusText
= R
.string
.auth_not_configured_title
;
1152 case FILE_NOT_FOUND
:
1153 mServerStatusText
= R
.string
.auth_incorrect_path_title
;
1156 mServerStatusText
= R
.string
.auth_oauth_error
;
1158 case OAUTH2_ERROR_ACCESS_DENIED
:
1159 mServerStatusText
= R
.string
.auth_oauth_error_access_denied
;
1161 case UNHANDLED_HTTP_CODE
:
1163 mServerStatusText
= R
.string
.auth_unknown_error_title
;
1165 case OK_REDIRECT_TO_NON_SECURE_CONNECTION
:
1166 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1167 mServerStatusText
= R
.string
.auth_redirect_non_secure_connection_title
;
1170 mServerStatusText
= 0;
1171 mServerStatusIcon
= 0;
1177 * Chooses the right icon and text to show to the user for the received operation result.
1179 * @param result Result of a remote operation performed in this activity
1181 private void updateAuthStatusIconAndText(RemoteOperationResult result
) {
1182 mAuthStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1184 switch (result
.getCode()) {
1186 mAuthStatusIcon
= android
.R
.drawable
.ic_secure
;
1187 mAuthStatusText
= R
.string
.auth_secure_connection
;
1192 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1193 mAuthStatusText
= R
.string
.auth_connection_established
;
1194 mAuthStatusIcon
= R
.drawable
.ic_ok
;
1196 mAuthStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1197 mAuthStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1201 case NO_NETWORK_CONNECTION
:
1202 mAuthStatusIcon
= R
.drawable
.no_network
;
1203 mAuthStatusText
= R
.string
.auth_no_net_conn_title
;
1206 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1207 mAuthStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1209 case BAD_OC_VERSION
:
1210 mAuthStatusText
= R
.string
.auth_bad_oc_version_title
;
1212 case WRONG_CONNECTION
:
1213 mAuthStatusText
= R
.string
.auth_wrong_connection_title
;
1216 mAuthStatusText
= R
.string
.auth_timeout_title
;
1218 case INCORRECT_ADDRESS
:
1219 mAuthStatusText
= R
.string
.auth_incorrect_address_title
;
1222 mAuthStatusText
= R
.string
.auth_ssl_general_error_title
;
1225 mAuthStatusText
= R
.string
.auth_unauthorized
;
1227 case HOST_NOT_AVAILABLE
:
1228 mAuthStatusText
= R
.string
.auth_unknown_host_title
;
1230 case INSTANCE_NOT_CONFIGURED
:
1231 mAuthStatusText
= R
.string
.auth_not_configured_title
;
1233 case FILE_NOT_FOUND
:
1234 mAuthStatusText
= R
.string
.auth_incorrect_path_title
;
1237 mAuthStatusText
= R
.string
.auth_oauth_error
;
1239 case OAUTH2_ERROR_ACCESS_DENIED
:
1240 mAuthStatusText
= R
.string
.auth_oauth_error_access_denied
;
1242 case ACCOUNT_NOT_NEW
:
1243 mAuthStatusText
= R
.string
.auth_account_not_new
;
1245 case ACCOUNT_NOT_THE_SAME
:
1246 mAuthStatusText
= R
.string
.auth_account_not_the_same
;
1248 case UNHANDLED_HTTP_CODE
:
1250 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
1253 mAuthStatusText
= 0;
1254 mAuthStatusIcon
= 0;
1259 private void updateStatusIconFailUserName(){
1260 mAuthStatusIcon
= R
.drawable
.common_error
;
1261 mAuthStatusText
= R
.string
.auth_fail_get_user_name
;
1264 private void updateServerStatusIconNoRegularAuth(){
1265 mServerStatusIcon
= R
.drawable
.common_error
;
1266 mServerStatusText
= R
.string
.auth_can_not_auth_against_server
;
1270 * Processes the result of the request for and access token send
1271 * to an OAuth authorization server.
1273 * @param result Result of the operation.
1275 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result
) {
1276 mWaitingForOpId
= Long
.MAX_VALUE
;
1277 dismissDialog(WAIT_DIALOG_TAG
);
1279 if (result
.isSuccess()) {
1280 /// be gentle with the user
1281 IndeterminateProgressDialog dialog
=
1282 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
1283 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
1285 /// time to test the retrieved access token on the ownCloud server
1286 @SuppressWarnings("unchecked")
1287 Map
<String
, String
> tokens
= (Map
<String
, String
>)(result
.getData().get(0));
1288 mAuthToken
= tokens
.get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
1289 //mAuthToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Constants.KEY_ACCESS_TOKEN);
1290 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mAuthToken
);
1292 accessRootFolderRemoteOperation("", "");
1295 updateAuthStatusIconAndText(result
);
1297 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1303 * Processes the result of the access check performed to try the user credentials.
1305 * Creates a new account through the AccountManager.
1307 * @param operation Access check performed.
1308 * @param result Result of the operation.
1310 private void onAuthorizationCheckFinish(RemoteOperationResult result
) {
1311 mWaitingForOpId
= Long
.MAX_VALUE
;
1312 dismissDialog(WAIT_DIALOG_TAG
);
1314 if (result
.isSuccess()) {
1315 Log_OC
.d(TAG
, "Successful access - time to save the account");
1317 boolean success
= false
;
1318 if (mAction
== ACTION_CREATE
) {
1319 success
= createAccount();
1330 } else if (result
.isServerFail() || result
.isException()) {
1331 /// server errors or exceptions in authorization take to requiring a new check of
1333 mServerIsChecked
= true
;
1334 mServerIsValid
= false
;
1335 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
1337 // update status icon and text
1338 updateServerStatusIconAndText(result
);
1340 mAuthStatusIcon
= 0;
1341 mAuthStatusText
= 0;
1344 // update input controls state
1345 showRefreshButton(true
);
1346 mOkButton
.setEnabled(false
);
1348 // very special case (TODO: move to a common place for all the remote operations) (dangerous here?)
1349 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1350 showUntrustedCertDialog(result
);
1353 } else { // authorization fail due to client side - probably wrong credentials
1354 updateAuthStatusIconAndText(result
);
1356 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1364 * Sets the proper response to get that the Account Authenticator that started this activity saves
1365 * a new authorization token for mAccount.
1367 private void updateToken() {
1368 Bundle response
= new Bundle();
1369 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1370 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
1372 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
1373 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1374 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1375 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1377 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
1379 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1380 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1381 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1384 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
1385 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
1387 setAccountAuthenticatorResult(response
);
1393 * Creates a new account through the Account Authenticator that started this activity.
1395 * This makes the account permanent.
1397 * TODO Decide how to name the OAuth accounts
1399 private boolean createAccount() {
1400 /// create and save new ownCloud account
1401 boolean isOAuth
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
);
1402 boolean isSaml
= AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
);
1404 Uri uri
= Uri
.parse(mServerInfo
.mBaseUrl
);
1405 String username
= mUsernameInput
.getText().toString().trim();
1407 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1409 String accountName
= com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.
1410 buildAccountName(uri
, username
);
1411 Account newAccount
= new Account(accountName
, MainApp
.getAccountType());
1412 if (AccountUtils
.exists(newAccount
, getApplicationContext())) {
1413 // fail - not a new account, but an existing one; disallow
1414 RemoteOperationResult result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_NEW
);
1415 updateAuthStatusIconAndText(result
);
1417 Log_OC
.d(TAG
, result
.getLogMessage());
1421 mAccount
= newAccount
;
1423 if (isOAuth
|| isSaml
) {
1424 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
); // with external authorizations, the password is never input in the app
1426 mAccountMgr
.addAccountExplicitly(mAccount
, mPasswordInput
.getText().toString(), null
);
1429 /// add the new account as default in preferences, if there is none already
1430 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1431 if (defaultAccount
== null
) {
1432 SharedPreferences
.Editor editor
= PreferenceManager
1433 .getDefaultSharedPreferences(this).edit();
1434 editor
.putString("select_oc_account", accountName
);
1438 /// prepare result to return to the Authenticator
1439 // TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done
1440 final Intent intent
= new Intent();
1441 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, MainApp
.getAccountType());
1442 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1444 intent.putExtra(AccountManager.KEY_AUTHTOKEN, MainApp.getAccountType()); */
1445 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1446 if (isOAuth
|| isSaml
) {
1447 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1449 /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
1450 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion());
1451 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_OC_BASE_URL
, mServerInfo
.mBaseUrl
);
1454 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
, "TRUE");
1455 } else if (isOAuth
) {
1456 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
, "TRUE");
1459 setAccountAuthenticatorResult(intent
.getExtras());
1460 setResult(RESULT_OK
, intent
);
1468 * Starts and activity to open the 'new account' page in the ownCloud web site
1470 * @param view 'Account register' button
1472 public void onRegisterClick(View view
) {
1473 Intent register
= new Intent(Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.welcome_link_url
)));
1474 setResult(RESULT_CANCELED
);
1475 startActivity(register
);
1480 * Updates the content and visibility state of the icon and text associated
1481 * to the last check on the ownCloud server.
1483 * @param serverStatusText Resource identifier of the text to show.
1484 * @param serverStatusIcon Resource identifier of the icon to show.
1486 private void showServerStatus() {
1487 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1488 mServerStatusView
.setVisibility(View
.INVISIBLE
);
1491 mServerStatusView
.setText(mServerStatusText
);
1492 mServerStatusView
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1493 mServerStatusView
.setVisibility(View
.VISIBLE
);
1500 * Updates the content and visibility state of the icon and text associated
1501 * to the interactions with the OAuth authorization server.
1503 private void showAuthStatus() {
1504 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1505 mAuthStatusView
.setVisibility(View
.INVISIBLE
);
1508 mAuthStatusView
.setText(mAuthStatusText
);
1509 mAuthStatusView
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1510 mAuthStatusView
.setVisibility(View
.VISIBLE
);
1515 private void showRefreshButton (boolean show
) {
1517 mRefreshButton
.setVisibility(View
.VISIBLE
);
1519 mRefreshButton
.setVisibility(View
.GONE
);
1524 * Called when the refresh button in the input field for ownCloud host is clicked.
1526 * Performs a new check on the URL in the input field.
1528 * @param view Refresh 'button'
1530 public void onRefreshClick(View view
) {
1536 * Called when the eye icon in the password field is clicked.
1538 * Toggles the visibility of the password in the field.
1540 public void onViewPasswordClick() {
1541 int selectionStart
= mPasswordInput
.getSelectionStart();
1542 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1543 if (isPasswordVisible()) {
1548 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1553 * Called when the checkbox for OAuth authorization is clicked.
1555 * Hides or shows the input fields for user & password.
1557 * @param view 'View password' 'button'
1559 public void onCheckClick(View view
) {
1560 CheckBox oAuth2Check
= (CheckBox
)view
;
1561 if (oAuth2Check
.isChecked()) {
1562 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1564 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1566 updateAuthenticationPreFragmentVisibility();
1571 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1573 * Used to trigger the authentication check when the user presses 'enter' after writing the password,
1574 * or to throw the server test when the only field on screen is the URL input field.
1577 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1578 if (actionId
== EditorInfo
.IME_ACTION_DONE
&& inputField
!= null
&& inputField
.equals(mPasswordInput
)) {
1579 if (mOkButton
.isEnabled()) {
1580 mOkButton
.performClick();
1583 } else if (actionId
== EditorInfo
.IME_ACTION_NEXT
&& inputField
!= null
&& inputField
.equals(mHostUrlInput
)) {
1584 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
1588 return false
; // always return false to grant that the software keyboard is hidden anyway
1592 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1594 private int fuzz
= 75;
1600 public boolean onTouch(View view
, MotionEvent event
) {
1601 Drawable rightDrawable
= null
;
1602 if (view
instanceof TextView
) {
1603 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1604 if (drawables
.length
> 2) {
1605 rightDrawable
= drawables
[2];
1608 if (rightDrawable
!= null
) {
1609 final int x
= (int) event
.getX();
1610 final int y
= (int) event
.getY();
1611 final Rect bounds
= rightDrawable
.getBounds();
1612 if (x
>= (view
.getRight() - bounds
.width() - fuzz
) && x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
)
1613 && y
>= (view
.getPaddingTop() - fuzz
) && y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1615 return onDrawableTouch(event
);
1621 public abstract boolean onDrawableTouch(final MotionEvent event
);
1625 private void getRemoteUserNameOperation(String sessionCookie
, boolean followRedirects
) {
1627 Intent getUserNameIntent
= new Intent();
1628 getUserNameIntent
.setAction(OperationsService
.ACTION_GET_USER_NAME
);
1629 getUserNameIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
1630 getUserNameIntent
.putExtra(OperationsService
.EXTRA_COOKIE
, sessionCookie
);
1632 if (mOperationsServiceBinder
!= null
) {
1633 //Log_OC.wtf(TAG, "starting getRemoteUserNameOperation..." );
1634 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(getUserNameIntent
);
1640 public void onSsoFinished(String sessionCookie
) {
1641 if (sessionCookie
!= null
&& sessionCookie
.length() > 0) {
1642 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1643 mAuthToken
= sessionCookie
;
1644 getRemoteUserNameOperation(sessionCookie
, true
);
1645 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1646 if (fd
!= null
&& fd
instanceof SherlockDialogFragment
) {
1647 Dialog d
= ((SherlockDialogFragment
)fd
).getDialog();
1648 if (d
!= null
&& d
.isShowing()) {
1655 Log_OC
.d(TAG
, "SSO failed");
1661 public boolean onTouchEvent(MotionEvent event
) {
1662 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
) &&
1663 mHostUrlInput
.hasFocus() && event
.getAction() == MotionEvent
.ACTION_DOWN
) {
1666 return super.onTouchEvent(event
);
1671 * Show untrusted cert dialog
1673 public void showUntrustedCertDialog(X509Certificate x509Certificate
, SslError error
, SslErrorHandler handler
) {
1674 // Show a dialog with the certificate info
1675 SslUntrustedCertDialog dialog
= null
;
1676 if (x509Certificate
== null
) {
1677 dialog
= SslUntrustedCertDialog
.newInstanceForEmptySslError(error
, handler
);
1679 dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(x509Certificate
, error
, handler
);
1681 FragmentManager fm
= getSupportFragmentManager();
1682 FragmentTransaction ft
= fm
.beginTransaction();
1683 ft
.addToBackStack(null
);
1684 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1688 * Show untrusted cert dialog
1690 private void showUntrustedCertDialog(RemoteOperationResult result
) {
1691 // Show a dialog with the certificate info
1692 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1693 FragmentManager fm
= getSupportFragmentManager();
1694 FragmentTransaction ft
= fm
.beginTransaction();
1695 ft
.addToBackStack(null
);
1696 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1701 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1703 public void onSavedCertificate() {
1704 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1706 // if SAML dialog is not shown, the SslDialog was shown due to an SSL error in the server check
1712 * Called from SslValidatorDialog when a new server certificate could not be saved
1713 * when the user requested it.
1716 public void onFailedSavingCertificate() {
1717 dismissDialog(SAML_DIALOG_TAG
);
1718 Toast
.makeText(this, R
.string
.ssl_validator_not_saved
, Toast
.LENGTH_LONG
).show();
1722 public void onCancelCertificate() {
1723 dismissDialog(SAML_DIALOG_TAG
);
1727 private void doOnResumeAndBound() {
1728 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1729 mOperationsServiceBinder
.addOperationListener(AuthenticatorActivity
.this, mHandler
);
1730 if (mWaitingForOpId
<= Integer
.MAX_VALUE
) {
1731 mOperationsServiceBinder
.dispatchResultIfFinished((int)mWaitingForOpId
, this);
1734 if (mPendingAutoCheck
) {
1740 private void dismissDialog(String dialogTag
){
1741 Fragment frag
= getSupportFragmentManager().findFragmentByTag(dialogTag
);
1742 if (frag
!= null
&& frag
instanceof SherlockDialogFragment
) {
1743 SherlockDialogFragment dialog
= (SherlockDialogFragment
) frag
;
1750 * Implements callback methods for service binding.
1752 private class OperationsServiceConnection
implements ServiceConnection
{
1755 public void onServiceConnected(ComponentName component
, IBinder service
) {
1756 if (component
.equals(new ComponentName(AuthenticatorActivity
.this, OperationsService
.class))) {
1757 //Log_OC.wtf(TAG, "Operations service connected");
1758 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
1760 doOnResumeAndBound();
1769 public void onServiceDisconnected(ComponentName component
) {
1770 if (component
.equals(new ComponentName(AuthenticatorActivity
.this, OperationsService
.class))) {
1771 Log_OC
.e(TAG
, "Operations service crashed");
1772 mOperationsServiceBinder
= null
;