1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.authentication
;
21 import java
.security
.cert
.X509Certificate
;
24 import android
.accounts
.Account
;
25 import android
.accounts
.AccountManager
;
26 import android
.app
.Dialog
;
27 import android
.content
.ComponentName
;
28 import android
.content
.Context
;
29 import android
.content
.Intent
;
30 import android
.content
.ServiceConnection
;
31 import android
.content
.SharedPreferences
;
32 import android
.graphics
.Rect
;
33 import android
.graphics
.drawable
.Drawable
;
34 import android
.net
.Uri
;
35 import android
.net
.http
.SslError
;
36 import android
.os
.Bundle
;
37 import android
.os
.Handler
;
38 import android
.os
.IBinder
;
39 import android
.preference
.PreferenceManager
;
40 import android
.support
.v4
.app
.Fragment
;
41 import android
.support
.v4
.app
.FragmentManager
;
42 import android
.support
.v4
.app
.FragmentTransaction
;
43 import android
.text
.Editable
;
44 import android
.text
.InputType
;
45 import android
.text
.TextWatcher
;
46 import android
.view
.KeyEvent
;
47 import android
.view
.MotionEvent
;
48 import android
.view
.View
;
49 import android
.view
.View
.OnFocusChangeListener
;
50 import android
.view
.View
.OnTouchListener
;
51 import android
.view
.Window
;
52 import android
.view
.inputmethod
.EditorInfo
;
53 import android
.webkit
.HttpAuthHandler
;
54 import android
.webkit
.SslErrorHandler
;
55 import android
.webkit
.WebView
;
56 import android
.widget
.Button
;
57 import android
.widget
.CheckBox
;
58 import android
.widget
.EditText
;
59 import android
.widget
.TextView
;
60 import android
.widget
.TextView
.OnEditorActionListener
;
61 import android
.widget
.Toast
;
63 import com
.actionbarsherlock
.app
.SherlockDialogFragment
;
64 import com
.owncloud
.android
.MainApp
;
65 import com
.owncloud
.android
.R
;
66 import com
.owncloud
.android
.authentication
.SsoWebViewClient
.SsoWebViewClientListener
;
67 import com
.owncloud
.android
.lib
.common
.accounts
.AccountTypeUtils
;
68 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.Constants
;
69 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
70 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
71 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
72 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
73 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
74 import com
.owncloud
.android
.lib
.resources
.files
.ExistenceCheckRemoteOperation
;
75 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
76 import com
.owncloud
.android
.lib
.resources
.users
.GetRemoteUserNameOperation
;
77 import com
.owncloud
.android
.operations
.DetectAuthenticationMethodOperation
.AuthenticationMethod
;
78 import com
.owncloud
.android
.operations
.GetServerInfoOperation
;
79 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
80 import com
.owncloud
.android
.services
.OperationsService
;
81 import com
.owncloud
.android
.services
.OperationsService
.OperationsServiceBinder
;
82 import com
.owncloud
.android
.ui
.dialog
.CredentialsDialogFragment
;
83 import com
.owncloud
.android
.ui
.dialog
.IndeterminateProgressDialog
;
84 import com
.owncloud
.android
.ui
.dialog
.SamlWebViewDialog
;
85 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
86 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
87 import com
.owncloud
.android
.utils
.DisplayUtils
;
88 import com
.owncloud
.android
.utils
.Log_OC
;
91 * This Activity is used to add an ownCloud account to the App
93 * @author Bartek Przybylski
94 * @author David A. Velasco
97 public class AuthenticatorActivity
extends AccountAuthenticatorActivity
98 implements OnRemoteOperationListener
, OnFocusChangeListener
, OnEditorActionListener
,
99 SsoWebViewClientListener
, OnSslUntrustedCertListener
{
101 private static final String TAG
= AuthenticatorActivity
.class.getSimpleName();
103 public static final String EXTRA_ACTION
= "ACTION";
104 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
106 private static final String KEY_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
108 private static final String KEY_HOST_URL_TEXT
= "HOST_URL_TEXT";
109 private static final String KEY_OC_VERSION
= "OC_VERSION";
110 private static final String KEY_SERVER_VALID
= "SERVER_VALID";
111 private static final String KEY_SERVER_CHECKED
= "SERVER_CHECKED";
112 private static final String KEY_SERVER_STATUS_TEXT
= "SERVER_STATUS_TEXT";
113 private static final String KEY_SERVER_STATUS_ICON
= "SERVER_STATUS_ICON";
114 private static final String KEY_IS_SSL_CONN
= "IS_SSL_CONN";
115 private static final String KEY_PASSWORD_EXPOSED
= "PASSWORD_VISIBLE";
116 private static final String KEY_AUTH_STATUS_TEXT
= "AUTH_STATUS_TEXT";
117 private static final String KEY_AUTH_STATUS_ICON
= "AUTH_STATUS_ICON";
118 private static final String KEY_SERVER_AUTH_METHOD
= "SERVER_AUTH_METHOD";
119 private static final String KEY_WAITING_FOR_OP_ID
= "WAITING_FOR_OP_ID";
120 private static final String KEY_AUTH_TOKEN
= "AUTH_TOKEN";
122 private static final String AUTH_ON
= "on";
123 private static final String AUTH_OPTIONAL
= "optional";
125 public static final byte ACTION_CREATE
= 0;
126 public static final byte ACTION_UPDATE_TOKEN
= 1; // requested by the user
127 public static final byte ACTION_UPDATE_EXPIRED_TOKEN
= 2; // detected by the app
129 private static final String UNTRUSTED_CERT_DIALOG_TAG
= "UNTRUSTED_CERT_DIALOG";
130 private static final String SAML_DIALOG_TAG
= "SAML_DIALOG";
131 private static final String WAIT_DIALOG_TAG
= "WAIT_DIALOG";
132 private static final String CREDENTIALS_DIALOG_TAG
= "CREDENTIALS_DIALOG";
133 private static final String KEY_AUTH_IS_FIRST_ATTEMPT_TAG
= "KEY_AUTH_IS_FIRST_ATTEMPT";
136 /// parameters from EXTRAs in starter Intent
137 private byte mAction
;
138 private Account mAccount
;
139 private String mAuthTokenType
;
142 /// activity-level references / state
143 private final Handler mHandler
= new Handler();
144 private ServiceConnection mOperationsServiceConnection
= null
;
145 private OperationsServiceBinder mOperationsServiceBinder
= null
;
146 private AccountManager mAccountMgr
;
147 private Uri mNewCapturedUriFromOAuth2Redirection
;
150 /// Server PRE-Fragment elements
151 private EditText mHostUrlInput
;
152 private View mRefreshButton
;
153 private TextView mServerStatusView
;
155 private TextWatcher mHostUrlInputWatcher
;
156 private int mServerStatusText
= 0, mServerStatusIcon
= 0;
158 private boolean mServerIsChecked
= false
;
159 private boolean mServerIsValid
= false
;
160 private boolean mPendingAutoCheck
= false
;
162 private GetServerInfoOperation
.ServerInfo mServerInfo
=
163 new GetServerInfoOperation
.ServerInfo();
166 /// Authentication PRE-Fragment elements
167 private CheckBox mOAuth2Check
;
168 private TextView mOAuthAuthEndpointText
;
169 private TextView mOAuthTokenEndpointText
;
170 private EditText mUsernameInput
;
171 private EditText mPasswordInput
;
172 private View mOkButton
;
173 private TextView mAuthStatusView
;
175 private int mAuthStatusText
= 0, mAuthStatusIcon
= 0;
177 private String mAuthToken
= "";
179 private boolean mIsFirstAuthAttempt
;
182 /// Identifier of operation in progress which result shouldn't be lost
183 private long mWaitingForOpId
= Long
.MAX_VALUE
;
189 * IMPORTANT ENTRY POINT 1: activity is shown to the user
192 protected void onCreate(Bundle savedInstanceState
) {
193 //Log_OC.wtf(TAG, "onCreate init");
194 super.onCreate(savedInstanceState
);
195 getWindow().requestFeature(Window
.FEATURE_NO_TITLE
);
197 mIsFirstAuthAttempt
= true
;
199 // bind to Operations Service
200 mOperationsServiceConnection
= new OperationsServiceConnection();
201 if (!bindService(new Intent(this, OperationsService
.class),
202 mOperationsServiceConnection
,
203 Context
.BIND_AUTO_CREATE
)) {
205 R
.string
.error_cant_bind_to_operations_service
,
211 /// init activity state
212 mAccountMgr
= AccountManager
.get(this);
213 mNewCapturedUriFromOAuth2Redirection
= null
;
216 mAction
= getIntent().getByteExtra(EXTRA_ACTION
, ACTION_CREATE
);
217 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
218 if (savedInstanceState
== null
) {
221 mAuthTokenType
= savedInstanceState
.getString(KEY_AUTH_TOKEN_TYPE
);
222 mWaitingForOpId
= savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
);
223 mIsFirstAuthAttempt
= savedInstanceState
.getBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
);
226 /// load user interface
227 setContentView(R
.layout
.account_setup
);
229 /// initialize general UI elements
230 initOverallUi(savedInstanceState
);
232 mOkButton
= findViewById(R
.id
.buttonOK
);
234 /// initialize block to be moved to single Fragment to check server and get info about it
235 initServerPreFragment(savedInstanceState
);
237 /// initialize block to be moved to single Fragment to retrieve and validate credentials
238 initAuthorizationPreFragment(savedInstanceState
);
240 //Log_OC.wtf(TAG, "onCreate end");
243 private void initAuthTokenType() {
245 getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
246 if (mAuthTokenType
== null
) {
247 if (mAccount
!= null
) {
248 boolean oAuthRequired
=
249 (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
) != null
);
250 boolean samlWebSsoRequired
=
251 (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
) != null
);
252 mAuthTokenType
= chooseAuthTokenType(oAuthRequired
, samlWebSsoRequired
);
255 boolean oAuthSupported
= AUTH_ON
.equals(getString(R
.string
.auth_method_oauth2
));
256 boolean samlWebSsoSupported
= AUTH_ON
.equals(getString(R
.string
.auth_method_saml_web_sso
));
257 mAuthTokenType
= chooseAuthTokenType(oAuthSupported
, samlWebSsoSupported
);
262 private String
chooseAuthTokenType(boolean oauth
, boolean saml
) {
264 return AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
266 return AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
268 return AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
274 * Configures elements in the user interface under direct control of the Activity.
276 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
278 private void initOverallUi(Bundle savedInstanceState
) {
280 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
281 boolean isWelcomeLinkVisible
= getResources().getBoolean(R
.bool
.show_welcome_link
);
283 String instructionsMessageText
= null
;
284 if (mAction
== ACTION_UPDATE_EXPIRED_TOKEN
) {
285 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
286 .equals(mAuthTokenType
)) {
287 instructionsMessageText
= getString(R
.string
.auth_expired_oauth_token_toast
);
289 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType())
290 .equals(mAuthTokenType
)) {
291 instructionsMessageText
= getString(R
.string
.auth_expired_saml_sso_token_toast
);
294 instructionsMessageText
= getString(R
.string
.auth_expired_basic_auth_toast
);
298 /// step 2 - set properties of UI elements (text, visibility, enabled...)
299 Button welcomeLink
= (Button
) findViewById(R
.id
.welcome_link
);
300 welcomeLink
.setVisibility(isWelcomeLinkVisible ? View
.VISIBLE
: View
.GONE
);
302 String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
304 TextView instructionsView
= (TextView
) findViewById(R
.id
.instructions_message
);
305 if (instructionsMessageText
!= null
) {
306 instructionsView
.setVisibility(View
.VISIBLE
);
307 instructionsView
.setText(instructionsMessageText
);
309 instructionsView
.setVisibility(View
.GONE
);
316 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
318 private void initServerPreFragment(Bundle savedInstanceState
) {
320 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
321 boolean isUrlInputAllowed
= getResources().getBoolean(R
.bool
.show_server_url_input
);
322 if (savedInstanceState
== null
) {
323 if (mAccount
!= null
) {
324 mServerInfo
.mBaseUrl
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_BASE_URL
);
325 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://"); // TODO do this in a setter for mBaseUrl
326 String ocVersion
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_VERSION
);
327 if (ocVersion
!= null
) {
328 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
331 mServerInfo
.mBaseUrl
= getString(R
.string
.server_url
).trim();
332 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
335 mServerStatusText
= savedInstanceState
.getInt(KEY_SERVER_STATUS_TEXT
);
336 mServerStatusIcon
= savedInstanceState
.getInt(KEY_SERVER_STATUS_ICON
);
338 mServerIsValid
= savedInstanceState
.getBoolean(KEY_SERVER_VALID
);
339 mServerIsChecked
= savedInstanceState
.getBoolean(KEY_SERVER_CHECKED
);
342 mServerInfo
.mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
343 mServerInfo
.mBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
344 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
345 if (ocVersion
!= null
) {
346 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
348 mServerInfo
.mAuthMethod
= AuthenticationMethod
.valueOf(
349 savedInstanceState
.getString(KEY_SERVER_AUTH_METHOD
));
353 /// step 2 - set properties of UI elements (text, visibility, enabled...)
354 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
355 // Convert IDN to Unicode
356 mHostUrlInput
.setText(DisplayUtils
.convertIdn(mServerInfo
.mBaseUrl
, false
));
357 if (mAction
!= ACTION_CREATE
) {
358 /// lock things that should not change
359 mHostUrlInput
.setEnabled(false
);
360 mHostUrlInput
.setFocusable(false
);
362 if (isUrlInputAllowed
) {
363 mRefreshButton
= findViewById(R
.id
.embeddedRefreshButton
);
365 findViewById(R
.id
.hostUrlFrame
).setVisibility(View
.GONE
);
366 mRefreshButton
= findViewById(R
.id
.centeredRefreshButton
);
368 showRefreshButton(mServerIsChecked
&& !mServerIsValid
&&
369 mWaitingForOpId
> Integer
.MAX_VALUE
);
370 mServerStatusView
= (TextView
) findViewById(R
.id
.server_status_text
);
373 /// step 3 - bind some listeners and options
374 mHostUrlInput
.setImeOptions(EditorInfo
.IME_ACTION_NEXT
);
375 mHostUrlInput
.setOnEditorActionListener(this);
377 /// step 4 - create listeners that will be bound at onResume
378 mHostUrlInputWatcher
= new TextWatcher() {
381 public void afterTextChanged(Editable s
) {
382 if (mOkButton
.isEnabled() &&
383 !mServerInfo
.mBaseUrl
.equals(
384 normalizeUrl(s
.toString(), mServerInfo
.mIsSslConn
))) {
385 mOkButton
.setEnabled(false
);
390 public void beforeTextChanged(CharSequence s
, int start
, int count
, int after
) {
394 public void onTextChanged(CharSequence s
, int start
, int before
, int count
) {
395 if (mAuthStatusIcon
!= 0) {
396 Log_OC
.d(TAG
, "onTextChanged: hiding authentication status");
405 // TODO find out if this is really necessary, or if it can done in a different way
406 findViewById(R
.id
.scroll
).setOnTouchListener(new OnTouchListener() {
408 public boolean onTouch(View view
, MotionEvent event
) {
409 if (event
.getAction() == MotionEvent
.ACTION_DOWN
) {
410 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
) &&
411 mHostUrlInput
.hasFocus()) {
420 /// step 4 - mark automatic check to be started when OperationsService is ready
421 mPendingAutoCheck
= (savedInstanceState
== null
&&
422 (mAction
!= ACTION_CREATE
|| !isUrlInputAllowed
));
428 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
430 private void initAuthorizationPreFragment(Bundle savedInstanceState
) {
432 /// step 0 - get UI elements in layout
433 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
434 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
435 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
436 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
437 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
438 mAuthStatusView
= (TextView
) findViewById(R
.id
.auth_status_text
);
440 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
441 String presetUserName
= null
;
442 boolean isPasswordExposed
= false
;
443 if (savedInstanceState
== null
) {
444 if (mAccount
!= null
) {
445 presetUserName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
449 isPasswordExposed
= savedInstanceState
.getBoolean(KEY_PASSWORD_EXPOSED
, false
);
450 mAuthStatusText
= savedInstanceState
.getInt(KEY_AUTH_STATUS_TEXT
);
451 mAuthStatusIcon
= savedInstanceState
.getInt(KEY_AUTH_STATUS_ICON
);
452 mAuthToken
= savedInstanceState
.getString(KEY_AUTH_TOKEN
);
455 /// step 2 - set properties of UI elements (text, visibility, enabled...)
456 mOAuth2Check
.setChecked(
457 AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
458 .equals(mAuthTokenType
));
459 if (presetUserName
!= null
) {
460 mUsernameInput
.setText(presetUserName
);
462 if (mAction
!= ACTION_CREATE
) {
463 mUsernameInput
.setEnabled(false
);
464 mUsernameInput
.setFocusable(false
);
466 mPasswordInput
.setText(""); // clean password to avoid social hacking
467 if (isPasswordExposed
) {
470 updateAuthenticationPreFragmentVisibility();
472 mOkButton
.setEnabled(mServerIsValid
);
475 /// step 3 - bind listeners
476 // bindings for password input field
477 mPasswordInput
.setOnFocusChangeListener(this);
478 mPasswordInput
.setImeOptions(EditorInfo
.IME_ACTION_DONE
);
479 mPasswordInput
.setOnEditorActionListener(this);
480 mPasswordInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
482 public boolean onDrawableTouch(final MotionEvent event
) {
483 if (event
.getAction() == MotionEvent
.ACTION_UP
) {
484 AuthenticatorActivity
.this.onViewPasswordClick();
494 * Changes the visibility of input elements depending on
495 * the current authorization method.
497 private void updateAuthenticationPreFragmentVisibility () {
498 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
499 equals(mAuthTokenType
)) {
500 // SAML-based web Single Sign On
501 mOAuth2Check
.setVisibility(View
.GONE
);
502 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
503 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
504 mUsernameInput
.setVisibility(View
.GONE
);
505 mPasswordInput
.setVisibility(View
.GONE
);
508 if (mAction
== ACTION_CREATE
&&
509 AUTH_OPTIONAL
.equals(getString(R
.string
.auth_method_oauth2
))) {
510 mOAuth2Check
.setVisibility(View
.VISIBLE
);
512 mOAuth2Check
.setVisibility(View
.GONE
);
515 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
516 equals(mAuthTokenType
)) {
517 // OAuth 2 authorization
519 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
520 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
521 mUsernameInput
.setVisibility(View
.GONE
);
522 mPasswordInput
.setVisibility(View
.GONE
);
525 // basic HTTP authorization
526 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
527 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
528 mUsernameInput
.setVisibility(View
.VISIBLE
);
529 mPasswordInput
.setVisibility(View
.VISIBLE
);
537 * Saves relevant state before {@link #onPause()}
539 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag, intended to defer the
540 * processing of the redirection caught in {@link #onNewIntent(Intent)} until {@link #onResume()}
542 * See {@link #loadSavedInstanceState(Bundle)}
545 protected void onSaveInstanceState(Bundle outState
) {
546 //Log_OC.wtf(TAG, "onSaveInstanceState init" );
547 super.onSaveInstanceState(outState
);
550 outState
.putString(KEY_AUTH_TOKEN_TYPE
, mAuthTokenType
);
551 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mWaitingForOpId
);
553 /// Server PRE-fragment state
554 outState
.putInt(KEY_SERVER_STATUS_TEXT
, mServerStatusText
);
555 outState
.putInt(KEY_SERVER_STATUS_ICON
, mServerStatusIcon
);
556 outState
.putBoolean(KEY_SERVER_CHECKED
, mServerIsChecked
);
557 outState
.putBoolean(KEY_SERVER_VALID
, mServerIsValid
);
558 outState
.putBoolean(KEY_IS_SSL_CONN
, mServerInfo
.mIsSslConn
);
559 outState
.putString(KEY_HOST_URL_TEXT
, mServerInfo
.mBaseUrl
);
560 if (mServerInfo
.mVersion
!= null
) {
561 outState
.putString(KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion());
563 outState
.putString(KEY_SERVER_AUTH_METHOD
, mServerInfo
.mAuthMethod
.name());
565 /// Authentication PRE-fragment state
566 outState
.putBoolean(KEY_PASSWORD_EXPOSED
, isPasswordVisible());
567 outState
.putInt(KEY_AUTH_STATUS_ICON
, mAuthStatusIcon
);
568 outState
.putInt(KEY_AUTH_STATUS_TEXT
, mAuthStatusText
);
569 outState
.putString(KEY_AUTH_TOKEN
, mAuthToken
);
572 outState
.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
, mIsFirstAuthAttempt
);
574 //Log_OC.wtf(TAG, "onSaveInstanceState end" );
579 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION request
582 * To make this possible, this activity needs to be qualified with android:launchMode = "singleTask" in the
583 * AndroidManifest.xml file.
586 protected void onNewIntent (Intent intent
) {
587 Log_OC
.d(TAG
, "onNewIntent()");
588 Uri data
= intent
.getData();
589 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
590 mNewCapturedUriFromOAuth2Redirection
= data
;
596 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION, and
597 * deferred in {@link #onNewIntent(Intent)}, is processed here.
600 protected void onResume() {
601 //Log_OC.wtf(TAG, "onResume init" );
604 // bound here to avoid spurious changes triggered by Android on device rotations
605 mHostUrlInput
.setOnFocusChangeListener(this);
606 mHostUrlInput
.addTextChangedListener(mHostUrlInputWatcher
);
608 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
609 getOAuth2AccessTokenFromCapturedRedirection();
612 if (mOperationsServiceBinder
!= null
) {
613 doOnResumeAndBound();
616 //Log_OC.wtf(TAG, "onResume end" );
621 protected void onPause() {
622 //Log_OC.wtf(TAG, "onPause init" );
623 if (mOperationsServiceBinder
!= null
) {
624 //Log_OC.wtf(TAG, "unregistering to listen for operation callbacks" );
625 mOperationsServiceBinder
.removeOperationListener(this);
628 mHostUrlInput
.removeTextChangedListener(mHostUrlInputWatcher
);
629 mHostUrlInput
.setOnFocusChangeListener(null
);
632 //Log_OC.wtf(TAG, "onPause end" );
636 protected void onDestroy() {
638 mHostUrlInputWatcher
= null
;
640 if (mOperationsServiceConnection
!= null
) {
641 unbindService(mOperationsServiceConnection
);
642 mOperationsServiceBinder
= null
;
649 * Parses the redirection with the response to the GET AUTHORIZATION request to the
650 * oAuth server and requests for the access token (GET ACCESS TOKEN)
652 private void getOAuth2AccessTokenFromCapturedRedirection() {
653 /// Parse data from OAuth redirection
654 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
655 mNewCapturedUriFromOAuth2Redirection
= null
;
657 /// Showing the dialog with instructions for the user.
658 IndeterminateProgressDialog dialog
=
659 IndeterminateProgressDialog
.newInstance(R
.string
.auth_getting_authorization
, true
);
660 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
662 /// GET ACCESS TOKEN to the oAuth server
663 Intent getServerInfoIntent
= new Intent();
664 getServerInfoIntent
.setAction(OperationsService
.ACTION_OAUTH2_GET_ACCESS_TOKEN
);
666 getServerInfoIntent
.putExtra(
667 OperationsService
.EXTRA_SERVER_URL
,
668 mOAuthTokenEndpointText
.getText().toString().trim());
670 getServerInfoIntent
.putExtra(
671 OperationsService
.EXTRA_OAUTH2_QUERY_PARAMETERS
,
674 if (mOperationsServiceBinder
!= null
) {
675 //Log_OC.wtf(TAG, "getting access token..." );
676 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(getServerInfoIntent
);
683 * Handles the change of focus on the text inputs for the server URL and the password
685 public void onFocusChange(View view
, boolean hasFocus
) {
686 if (view
.getId() == R
.id
.hostUrlInput
) {
688 onUrlInputFocusLost((TextView
) view
);
691 showRefreshButton(false
);
694 } else if (view
.getId() == R
.id
.account_password
) {
695 onPasswordFocusChanged((TextView
) view
, hasFocus
);
701 * Handles changes in focus on the text input for the server URL.
703 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
704 * other field. The operation to check the existence of the server in the entered URL is
707 * When hasFocus: user 'comes back' to write again the server URL.
709 * @param hostInput TextView with the URL input field receiving the change of focus.
711 private void onUrlInputFocusLost(TextView hostInput
) {
712 if (!mServerInfo
.mBaseUrl
.equals(
713 normalizeUrl(mHostUrlInput
.getText().toString(), mServerInfo
.mIsSslConn
))) {
714 // check server again only if the user changed something in the field
717 mOkButton
.setEnabled(mServerIsValid
);
718 showRefreshButton(!mServerIsValid
);
723 private void checkOcServer() {
724 String uri
= mHostUrlInput
.getText().toString().trim();
725 mServerIsValid
= false
;
726 mServerIsChecked
= false
;
727 mOkButton
.setEnabled(false
);
728 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
729 showRefreshButton(false
);
731 if (uri
.length() != 0) {
732 // Handle internationalized domain names
733 uri
= DisplayUtils
.convertIdn(uri
, true
);
734 mServerStatusText
= R
.string
.auth_testing_connection
;
735 mServerStatusIcon
= R
.drawable
.progress_small
;
738 Intent getServerInfoIntent
= new Intent();
739 getServerInfoIntent
.setAction(OperationsService
.ACTION_GET_SERVER_INFO
);
740 getServerInfoIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, uri
);
741 if (mOperationsServiceBinder
!= null
) {
742 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(getServerInfoIntent
);
744 Log_OC
.wtf(TAG
, "Server check tried with OperationService unbound!" );
748 mServerStatusText
= 0;
749 mServerStatusIcon
= 0;
756 * Handles changes in focus on the text input for the password (basic authorization).
758 * When (hasFocus), the button to toggle password visibility is shown.
760 * When (!hasFocus), the button is made invisible and the password is hidden.
762 * @param passwordInput TextView with the password input field receiving the change of focus.
763 * @param hasFocus 'True' if focus is received, 'false' if is lost
765 private void onPasswordFocusChanged(TextView passwordInput
, boolean hasFocus
) {
767 showViewPasswordButton();
770 hidePasswordButton();
775 private void showViewPasswordButton() {
776 int drawable
= R
.drawable
.ic_view
;
777 if (isPasswordVisible()) {
778 drawable
= R
.drawable
.ic_hide
;
780 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable
, 0);
783 private boolean isPasswordVisible() {
784 return ((mPasswordInput
.getInputType() & InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) == InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
787 private void hidePasswordButton() {
788 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
791 private void showPassword() {
792 mPasswordInput
.setInputType(InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
793 showViewPasswordButton();
796 private void hidePassword() {
797 mPasswordInput
.setInputType(InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
);
798 showViewPasswordButton();
802 * Checks the credentials of the user in the root of the ownCloud server
803 * before creating a new local account.
805 * For basic authorization, a check of existence of the root folder is
808 * For OAuth, starts the flow to get an access token; the credentials test
809 * is postponed until it is available.
811 * IMPORTANT ENTRY POINT 4
813 * @param view OK button
815 public void onOkClick(View view
) {
816 // this check should be unnecessary
817 if (mServerInfo
.mVersion
== null
||
818 !mServerInfo
.mVersion
.isVersionValid() ||
819 mServerInfo
.mBaseUrl
== null
||
820 mServerInfo
.mBaseUrl
.length() == 0) {
821 mServerStatusIcon
= R
.drawable
.common_error
;
822 mServerStatusText
= R
.string
.auth_wtf_reenter_URL
;
824 mOkButton
.setEnabled(false
);
825 //Log_OC.wtf(TAG, "The user was allowed to click 'connect' to an unchecked server!!");
829 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
830 startOauthorization();
831 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
832 startSamlBasedFederatedSingleSignOnAuthorization();
834 checkBasicAuthorization();
840 * Tests the credentials entered by the user performing a check of existence on
841 * the root folder of the ownCloud server.
843 private void checkBasicAuthorization() {
844 /// get basic credentials entered by user
845 String username
= mUsernameInput
.getText().toString();
846 String password
= mPasswordInput
.getText().toString();
848 /// be gentle with the user
849 IndeterminateProgressDialog dialog
=
850 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
851 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
853 /// validate credentials accessing the root folder
854 accessRootFolderRemoteOperation(username
, password
);
858 private void accessRootFolderRemoteOperation(String username
, String password
) {
859 Intent existenceCheckIntent
= new Intent();
860 existenceCheckIntent
.setAction(OperationsService
.ACTION_EXISTENCE_CHECK
);
861 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
862 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_REMOTE_PATH
, "/");
863 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_USERNAME
, username
);
864 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_PASSWORD
, password
);
865 existenceCheckIntent
.putExtra(OperationsService
.EXTRA_AUTH_TOKEN
, mAuthToken
);
867 if (mOperationsServiceBinder
!= null
) {
868 //Log_OC.wtf(TAG, "starting existenceCheckRemoteOperation..." );
869 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(existenceCheckIntent
);
874 * Starts the OAuth 'grant type' flow to get an access token, with
875 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
877 private void startOauthorization() {
878 // be gentle with the user
879 mAuthStatusIcon
= R
.drawable
.progress_small
;
880 mAuthStatusText
= R
.string
.oauth_login_connection
;
883 // GET AUTHORIZATION request
884 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
885 Uri
.Builder uriBuilder
= uri
.buildUpon();
886 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
));
887 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
));
888 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
));
889 uriBuilder
.appendQueryParameter(OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
));
890 uri
= uriBuilder
.build();
891 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
892 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
898 * Starts the Web Single Sign On flow to get access to the root folder
901 private void startSamlBasedFederatedSingleSignOnAuthorization() {
902 // be gentle with the user
903 mAuthStatusIcon
= R
.drawable
.progress_small
;
904 mAuthStatusText
= R
.string
.auth_connecting_auth_server
;
906 IndeterminateProgressDialog dialog
=
907 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
908 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
910 /// validate credentials accessing the root folder
911 accessRootFolderRemoteOperation("", "");
916 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
918 * Dispatches the operation flow to the right method.
921 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
923 if (operation
instanceof GetServerInfoOperation
) {
924 if (operation
.hashCode() == mWaitingForOpId
) {
925 onGetServerInfoFinish(result
);
926 } // else nothing ; only the last check operation is considered;
927 // multiple can be started if the user amends a URL quickly
929 } else if (operation
instanceof OAuth2GetAccessToken
) {
930 onGetOAuthAccessTokenFinish(result
);
932 } else if (operation
instanceof ExistenceCheckRemoteOperation
) {
933 //Log_OC.wtf(TAG, "received detection response through callback" );
934 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
935 onSamlBasedFederatedSingleSignOnAuthorizationStart(result
);
938 onAuthorizationCheckFinish(result
);
940 } else if (operation
instanceof GetRemoteUserNameOperation
) {
941 onGetUserNameFinish(result
);
946 private void onGetUserNameFinish(RemoteOperationResult result
) {
947 mWaitingForOpId
= Long
.MAX_VALUE
;
948 if (result
.isSuccess()) {
949 boolean success
= false
;
950 String username
= (String
) result
.getData().get(0);
952 if ( mAction
== ACTION_CREATE
) {
953 mUsernameInput
.setText(username
);
954 success
= createAccount();
957 if (!mUsernameInput
.getText().toString().equals(username
)) {
958 // fail - not a new account, but an existing one; disallow
959 result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_THE_SAME
);
961 OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(
963 Uri.parse(mServerInfo.mBaseUrl),
964 OwnCloudCredentialsFactory.newSamlSsoCredentials(mAuthToken))
968 updateAuthStatusIconAndText(result
);
970 Log_OC
.d(TAG
, result
.getLogMessage());
980 updateStatusIconFailUserName();
982 Log_OC
.e(TAG
, "Access to user name failed: " + result
.getLogMessage());
987 private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperationResult result
) {
988 mWaitingForOpId
= Long
.MAX_VALUE
;
989 dismissDialog(WAIT_DIALOG_TAG
);
991 if (result
.isIdPRedirection()) {
992 String url
= result
.getRedirectedLocation();
993 String targetUrl
= mServerInfo
.mBaseUrl
994 + AccountUtils
.getWebdavPath(mServerInfo
.mVersion
, mAuthTokenType
);
997 SamlWebViewDialog dialog
= SamlWebViewDialog
.newInstance(url
, targetUrl
);
998 dialog
.show(getSupportFragmentManager(), SAML_DIALOG_TAG
);
1000 mAuthStatusIcon
= 0;
1001 mAuthStatusText
= 0;
1004 mAuthStatusIcon
= R
.drawable
.common_error
;
1005 mAuthStatusText
= R
.string
.auth_unsupported_auth_method
;
1013 * Processes the result of the server check performed when the user finishes the enter of the
1016 * @param operation Server check performed.
1017 * @param result Result of the check.
1019 private void onGetServerInfoFinish(RemoteOperationResult result
) {
1020 /// update activity state
1021 mServerIsChecked
= true
;
1022 mWaitingForOpId
= Long
.MAX_VALUE
;
1024 // update server status, but don't show it yet
1025 updateServerStatusIconAndText(result
);
1027 if (result
.isSuccess()) {
1029 // 1. connection succeeded, and we know if it's SSL or not
1030 // 2. server is installed
1031 // 3. we got the server version
1032 // 4. we got the authentication method required by the server
1033 mServerInfo
= (GetServerInfoOperation
.ServerInfo
) (result
.getData().get(0));
1035 if (!authSupported(mServerInfo
.mAuthMethod
)) {
1037 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1038 mServerIsValid
= false
;
1041 mServerIsValid
= true
;
1045 mServerIsValid
= false
;
1049 showRefreshButton(!mServerIsValid
);
1051 mOkButton
.setEnabled(mServerIsValid
);
1053 /// very special case (TODO: move to a common place for all the remote operations)
1054 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1055 showUntrustedCertDialog(result
);
1060 private boolean authSupported(AuthenticationMethod authMethod
) {
1061 String basic
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1062 String oAuth
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1063 String saml
= AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
1065 return (( mAuthTokenType
.equals(basic
) &&
1066 authMethod
.equals(AuthenticationMethod
.BASIC_HTTP_AUTH
) ) ||
1067 ( mAuthTokenType
.equals(oAuth
) &&
1068 authMethod
.equals(AuthenticationMethod
.BEARER_TOKEN
)) ||
1069 ( mAuthTokenType
.equals(saml
) &&
1070 authMethod
.equals(AuthenticationMethod
.SAML_WEB_SSO
))
1075 // TODO remove, if possible
1076 private String
normalizeUrl(String url
, boolean sslWhenUnprefixed
) {
1077 if (url
!= null
&& url
.length() > 0) {
1079 if (!url
.toLowerCase().startsWith("http://") &&
1080 !url
.toLowerCase().startsWith("https://")) {
1081 if (sslWhenUnprefixed
) {
1082 url
= "https://" + url
;
1084 url
= "http://" + url
;
1088 url
= trimUrlWebdav(url
);
1090 if (url
.endsWith("/")) {
1091 url
= url
.substring(0, url
.length() - 1);
1095 return (url
!= null ? url
: "");
1099 // TODO remove, if possible
1100 private String
trimUrlWebdav(String url
){
1101 if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_4_0
)){
1102 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_4_0
.length());
1103 } else if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_2_0
)){
1104 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_2_0
.length());
1105 } else if (url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_1_2
)){
1106 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_1_2
.length());
1108 return (url
!= null ? url
: "");
1113 * Chooses the right icon and text to show to the user for the received operation result.
1115 * @param result Result of a remote operation performed in this activity
1117 private void updateServerStatusIconAndText(RemoteOperationResult result
) {
1118 mServerStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1120 switch (result
.getCode()) {
1122 mServerStatusIcon
= android
.R
.drawable
.ic_secure
;
1123 mServerStatusText
= R
.string
.auth_secure_connection
;
1128 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1129 mServerStatusText
= R
.string
.auth_connection_established
;
1130 mServerStatusIcon
= R
.drawable
.ic_ok
;
1132 mServerStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1133 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1137 case NO_NETWORK_CONNECTION
:
1138 mServerStatusIcon
= R
.drawable
.no_network
;
1139 mServerStatusText
= R
.string
.auth_no_net_conn_title
;
1142 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1143 mServerStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1145 case BAD_OC_VERSION
:
1146 mServerStatusText
= R
.string
.auth_bad_oc_version_title
;
1148 case WRONG_CONNECTION
:
1149 mServerStatusText
= R
.string
.auth_wrong_connection_title
;
1152 mServerStatusText
= R
.string
.auth_timeout_title
;
1154 case INCORRECT_ADDRESS
:
1155 mServerStatusText
= R
.string
.auth_incorrect_address_title
;
1158 mServerStatusText
= R
.string
.auth_ssl_general_error_title
;
1161 mServerStatusText
= R
.string
.auth_unauthorized
;
1163 case HOST_NOT_AVAILABLE
:
1164 mServerStatusText
= R
.string
.auth_unknown_host_title
;
1166 case INSTANCE_NOT_CONFIGURED
:
1167 mServerStatusText
= R
.string
.auth_not_configured_title
;
1169 case FILE_NOT_FOUND
:
1170 mServerStatusText
= R
.string
.auth_incorrect_path_title
;
1173 mServerStatusText
= R
.string
.auth_oauth_error
;
1175 case OAUTH2_ERROR_ACCESS_DENIED
:
1176 mServerStatusText
= R
.string
.auth_oauth_error_access_denied
;
1178 case UNHANDLED_HTTP_CODE
:
1180 mServerStatusText
= R
.string
.auth_unknown_error_title
;
1182 case OK_REDIRECT_TO_NON_SECURE_CONNECTION
:
1183 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1184 mServerStatusText
= R
.string
.auth_redirect_non_secure_connection_title
;
1187 mServerStatusText
= 0;
1188 mServerStatusIcon
= 0;
1194 * Chooses the right icon and text to show to the user for the received operation result.
1196 * @param result Result of a remote operation performed in this activity
1198 private void updateAuthStatusIconAndText(RemoteOperationResult result
) {
1199 mAuthStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1201 switch (result
.getCode()) {
1203 mAuthStatusIcon
= android
.R
.drawable
.ic_secure
;
1204 mAuthStatusText
= R
.string
.auth_secure_connection
;
1209 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1210 mAuthStatusText
= R
.string
.auth_connection_established
;
1211 mAuthStatusIcon
= R
.drawable
.ic_ok
;
1213 mAuthStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1214 mAuthStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1218 case NO_NETWORK_CONNECTION
:
1219 mAuthStatusIcon
= R
.drawable
.no_network
;
1220 mAuthStatusText
= R
.string
.auth_no_net_conn_title
;
1223 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1224 mAuthStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1226 case BAD_OC_VERSION
:
1227 mAuthStatusText
= R
.string
.auth_bad_oc_version_title
;
1229 case WRONG_CONNECTION
:
1230 mAuthStatusText
= R
.string
.auth_wrong_connection_title
;
1233 mAuthStatusText
= R
.string
.auth_timeout_title
;
1235 case INCORRECT_ADDRESS
:
1236 mAuthStatusText
= R
.string
.auth_incorrect_address_title
;
1239 mAuthStatusText
= R
.string
.auth_ssl_general_error_title
;
1242 mAuthStatusText
= R
.string
.auth_unauthorized
;
1244 case HOST_NOT_AVAILABLE
:
1245 mAuthStatusText
= R
.string
.auth_unknown_host_title
;
1247 case INSTANCE_NOT_CONFIGURED
:
1248 mAuthStatusText
= R
.string
.auth_not_configured_title
;
1250 case FILE_NOT_FOUND
:
1251 mAuthStatusText
= R
.string
.auth_incorrect_path_title
;
1254 mAuthStatusText
= R
.string
.auth_oauth_error
;
1256 case OAUTH2_ERROR_ACCESS_DENIED
:
1257 mAuthStatusText
= R
.string
.auth_oauth_error_access_denied
;
1259 case ACCOUNT_NOT_NEW
:
1260 mAuthStatusText
= R
.string
.auth_account_not_new
;
1262 case ACCOUNT_NOT_THE_SAME
:
1263 mAuthStatusText
= R
.string
.auth_account_not_the_same
;
1265 case UNHANDLED_HTTP_CODE
:
1267 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
1270 mAuthStatusText
= 0;
1271 mAuthStatusIcon
= 0;
1276 private void updateStatusIconFailUserName(){
1277 mAuthStatusIcon
= R
.drawable
.common_error
;
1278 mAuthStatusText
= R
.string
.auth_fail_get_user_name
;
1281 private void updateServerStatusIconNoRegularAuth(){
1282 mServerStatusIcon
= R
.drawable
.common_error
;
1283 mServerStatusText
= R
.string
.auth_can_not_auth_against_server
;
1287 * Processes the result of the request for and access token send
1288 * to an OAuth authorization server.
1290 * @param result Result of the operation.
1292 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result
) {
1293 mWaitingForOpId
= Long
.MAX_VALUE
;
1294 dismissDialog(WAIT_DIALOG_TAG
);
1296 if (result
.isSuccess()) {
1297 /// be gentle with the user
1298 IndeterminateProgressDialog dialog
=
1299 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
1300 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
1302 /// time to test the retrieved access token on the ownCloud server
1303 @SuppressWarnings("unchecked")
1304 Map
<String
, String
> tokens
= (Map
<String
, String
>)(result
.getData().get(0));
1305 mAuthToken
= tokens
.get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
1306 //mAuthToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Constants.KEY_ACCESS_TOKEN);
1307 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mAuthToken
);
1309 accessRootFolderRemoteOperation("", "");
1312 updateAuthStatusIconAndText(result
);
1314 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1320 * Processes the result of the access check performed to try the user credentials.
1322 * Creates a new account through the AccountManager.
1324 * @param operation Access check performed.
1325 * @param result Result of the operation.
1327 private void onAuthorizationCheckFinish(RemoteOperationResult result
) {
1328 mWaitingForOpId
= Long
.MAX_VALUE
;
1329 dismissDialog(WAIT_DIALOG_TAG
);
1331 if (result
.isSuccess()) {
1332 Log_OC
.d(TAG
, "Successful access - time to save the account");
1334 boolean success
= false
;
1335 if (mAction
== ACTION_CREATE
) {
1336 success
= createAccount();
1347 } else if (result
.isServerFail() || result
.isException()) {
1348 /// server errors or exceptions in authorization take to requiring a new check of
1350 mServerIsChecked
= true
;
1351 mServerIsValid
= false
;
1352 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
1354 // update status icon and text
1355 updateServerStatusIconAndText(result
);
1357 mAuthStatusIcon
= 0;
1358 mAuthStatusText
= 0;
1361 // update input controls state
1362 showRefreshButton(true
);
1363 mOkButton
.setEnabled(false
);
1365 // very special case (TODO: move to a common place for all the remote operations) (dangerous here?)
1366 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1367 showUntrustedCertDialog(result
);
1370 } else { // authorization fail due to client side - probably wrong credentials
1371 updateAuthStatusIconAndText(result
);
1373 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1381 * Sets the proper response to get that the Account Authenticator that started this activity saves
1382 * a new authorization token for mAccount.
1384 private void updateToken() {
1385 Bundle response
= new Bundle();
1386 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1387 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
1389 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
1390 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1391 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1392 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1394 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
1396 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1397 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1398 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1401 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
1402 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
1404 setAccountAuthenticatorResult(response
);
1410 * Creates a new account through the Account Authenticator that started this activity.
1412 * This makes the account permanent.
1414 * TODO Decide how to name the OAuth accounts
1416 private boolean createAccount() {
1417 /// create and save new ownCloud account
1418 boolean isOAuth
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
);
1419 boolean isSaml
= AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
);
1421 Uri uri
= Uri
.parse(mServerInfo
.mBaseUrl
);
1422 String username
= mUsernameInput
.getText().toString().trim();
1424 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1426 String accountName
= com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.
1427 buildAccountName(uri
, username
);
1428 Account newAccount
= new Account(accountName
, MainApp
.getAccountType());
1429 if (AccountUtils
.exists(newAccount
, getApplicationContext())) {
1430 // fail - not a new account, but an existing one; disallow
1431 RemoteOperationResult result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_NEW
);
1432 updateAuthStatusIconAndText(result
);
1434 Log_OC
.d(TAG
, result
.getLogMessage());
1438 mAccount
= newAccount
;
1440 if (isOAuth
|| isSaml
) {
1441 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
); // with external authorizations, the password is never input in the app
1443 mAccountMgr
.addAccountExplicitly(mAccount
, mPasswordInput
.getText().toString(), null
);
1446 /// add the new account as default in preferences, if there is none already
1447 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1448 if (defaultAccount
== null
) {
1449 SharedPreferences
.Editor editor
= PreferenceManager
1450 .getDefaultSharedPreferences(this).edit();
1451 editor
.putString("select_oc_account", accountName
);
1455 /// prepare result to return to the Authenticator
1456 // TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done
1457 final Intent intent
= new Intent();
1458 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, MainApp
.getAccountType());
1459 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1461 intent.putExtra(AccountManager.KEY_AUTHTOKEN, MainApp.getAccountType()); */
1462 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1463 if (isOAuth
|| isSaml
) {
1464 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1466 /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
1467 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion());
1468 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_OC_BASE_URL
, mServerInfo
.mBaseUrl
);
1471 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
, "TRUE");
1472 } else if (isOAuth
) {
1473 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
, "TRUE");
1476 setAccountAuthenticatorResult(intent
.getExtras());
1477 setResult(RESULT_OK
, intent
);
1485 * Starts and activity to open the 'new account' page in the ownCloud web site
1487 * @param view 'Account register' button
1489 public void onRegisterClick(View view
) {
1490 Intent register
= new Intent(Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.welcome_link_url
)));
1491 setResult(RESULT_CANCELED
);
1492 startActivity(register
);
1497 * Updates the content and visibility state of the icon and text associated
1498 * to the last check on the ownCloud server.
1500 * @param serverStatusText Resource identifier of the text to show.
1501 * @param serverStatusIcon Resource identifier of the icon to show.
1503 private void showServerStatus() {
1504 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1505 mServerStatusView
.setVisibility(View
.INVISIBLE
);
1508 mServerStatusView
.setText(mServerStatusText
);
1509 mServerStatusView
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1510 mServerStatusView
.setVisibility(View
.VISIBLE
);
1517 * Updates the content and visibility state of the icon and text associated
1518 * to the interactions with the OAuth authorization server.
1520 private void showAuthStatus() {
1521 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1522 mAuthStatusView
.setVisibility(View
.INVISIBLE
);
1525 mAuthStatusView
.setText(mAuthStatusText
);
1526 mAuthStatusView
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1527 mAuthStatusView
.setVisibility(View
.VISIBLE
);
1532 private void showRefreshButton (boolean show
) {
1534 mRefreshButton
.setVisibility(View
.VISIBLE
);
1536 mRefreshButton
.setVisibility(View
.GONE
);
1541 * Called when the refresh button in the input field for ownCloud host is clicked.
1543 * Performs a new check on the URL in the input field.
1545 * @param view Refresh 'button'
1547 public void onRefreshClick(View view
) {
1553 * Called when the eye icon in the password field is clicked.
1555 * Toggles the visibility of the password in the field.
1557 public void onViewPasswordClick() {
1558 int selectionStart
= mPasswordInput
.getSelectionStart();
1559 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1560 if (isPasswordVisible()) {
1565 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1570 * Called when the checkbox for OAuth authorization is clicked.
1572 * Hides or shows the input fields for user & password.
1574 * @param view 'View password' 'button'
1576 public void onCheckClick(View view
) {
1577 CheckBox oAuth2Check
= (CheckBox
)view
;
1578 if (oAuth2Check
.isChecked()) {
1579 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
1581 mAuthTokenType
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
1583 updateAuthenticationPreFragmentVisibility();
1588 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1590 * Used to trigger the authentication check when the user presses 'enter' after writing the password,
1591 * or to throw the server test when the only field on screen is the URL input field.
1594 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1595 if (actionId
== EditorInfo
.IME_ACTION_DONE
&& inputField
!= null
&& inputField
.equals(mPasswordInput
)) {
1596 if (mOkButton
.isEnabled()) {
1597 mOkButton
.performClick();
1600 } else if (actionId
== EditorInfo
.IME_ACTION_NEXT
&& inputField
!= null
&& inputField
.equals(mHostUrlInput
)) {
1601 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
)) {
1605 return false
; // always return false to grant that the software keyboard is hidden anyway
1609 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1611 private int fuzz
= 75;
1617 public boolean onTouch(View view
, MotionEvent event
) {
1618 Drawable rightDrawable
= null
;
1619 if (view
instanceof TextView
) {
1620 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1621 if (drawables
.length
> 2) {
1622 rightDrawable
= drawables
[2];
1625 if (rightDrawable
!= null
) {
1626 final int x
= (int) event
.getX();
1627 final int y
= (int) event
.getY();
1628 final Rect bounds
= rightDrawable
.getBounds();
1629 if (x
>= (view
.getRight() - bounds
.width() - fuzz
) && x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
)
1630 && y
>= (view
.getPaddingTop() - fuzz
) && y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1632 return onDrawableTouch(event
);
1638 public abstract boolean onDrawableTouch(final MotionEvent event
);
1642 private void getRemoteUserNameOperation(String sessionCookie
, boolean followRedirects
) {
1644 Intent getUserNameIntent
= new Intent();
1645 getUserNameIntent
.setAction(OperationsService
.ACTION_GET_USER_NAME
);
1646 getUserNameIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
1647 getUserNameIntent
.putExtra(OperationsService
.EXTRA_COOKIE
, sessionCookie
);
1649 if (mOperationsServiceBinder
!= null
) {
1650 //Log_OC.wtf(TAG, "starting getRemoteUserNameOperation..." );
1651 mWaitingForOpId
= mOperationsServiceBinder
.newOperation(getUserNameIntent
);
1657 public void onSsoFinished(String sessionCookie
) {
1658 if (sessionCookie
!= null
&& sessionCookie
.length() > 0) {
1659 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1660 mAuthToken
= sessionCookie
;
1661 getRemoteUserNameOperation(sessionCookie
, true
);
1662 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1663 if (fd
!= null
&& fd
instanceof SherlockDialogFragment
) {
1664 Dialog d
= ((SherlockDialogFragment
)fd
).getDialog();
1665 if (d
!= null
&& d
.isShowing()) {
1672 Log_OC
.d(TAG
, "SSO failed");
1678 public boolean onTouchEvent(MotionEvent event
) {
1679 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
) &&
1680 mHostUrlInput
.hasFocus() && event
.getAction() == MotionEvent
.ACTION_DOWN
) {
1683 return super.onTouchEvent(event
);
1688 * Show untrusted cert dialog
1690 public void showUntrustedCertDialog(X509Certificate x509Certificate
, SslError error
, SslErrorHandler handler
) {
1691 // Show a dialog with the certificate info
1692 SslUntrustedCertDialog dialog
= null
;
1693 if (x509Certificate
== null
) {
1694 dialog
= SslUntrustedCertDialog
.newInstanceForEmptySslError(error
, handler
);
1696 dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError(x509Certificate
, error
, handler
);
1698 FragmentManager fm
= getSupportFragmentManager();
1699 FragmentTransaction ft
= fm
.beginTransaction();
1700 ft
.addToBackStack(null
);
1701 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1706 * Show untrusted cert dialog
1708 private void showUntrustedCertDialog(RemoteOperationResult result
) {
1709 // Show a dialog with the certificate info
1710 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1711 FragmentManager fm
= getSupportFragmentManager();
1712 FragmentTransaction ft
= fm
.beginTransaction();
1713 ft
.addToBackStack(null
);
1714 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1719 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1721 public void onSavedCertificate() {
1722 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1724 // if SAML dialog is not shown, the SslDialog was shown due to an SSL error in the server check
1730 * Called from SslValidatorDialog when a new server certificate could not be saved
1731 * when the user requested it.
1734 public void onFailedSavingCertificate() {
1735 dismissDialog(SAML_DIALOG_TAG
);
1736 Toast
.makeText(this, R
.string
.ssl_validator_not_saved
, Toast
.LENGTH_LONG
).show();
1740 public void onCancelCertificate() {
1741 dismissDialog(SAML_DIALOG_TAG
);
1745 private void doOnResumeAndBound() {
1746 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1747 mOperationsServiceBinder
.addOperationListener(AuthenticatorActivity
.this, mHandler
);
1748 if (mWaitingForOpId
<= Integer
.MAX_VALUE
) {
1749 mOperationsServiceBinder
.dispatchResultIfFinished((int)mWaitingForOpId
, this);
1752 if (mPendingAutoCheck
) {
1758 private void dismissDialog(String dialogTag
){
1759 Fragment frag
= getSupportFragmentManager().findFragmentByTag(dialogTag
);
1760 if (frag
!= null
&& frag
instanceof SherlockDialogFragment
) {
1761 SherlockDialogFragment dialog
= (SherlockDialogFragment
) frag
;
1768 * Implements callback methods for service binding.
1770 private class OperationsServiceConnection
implements ServiceConnection
{
1773 public void onServiceConnected(ComponentName component
, IBinder service
) {
1774 if (component
.equals(new ComponentName(AuthenticatorActivity
.this, OperationsService
.class))) {
1775 //Log_OC.wtf(TAG, "Operations service connected");
1776 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
1778 doOnResumeAndBound();
1787 public void onServiceDisconnected(ComponentName component
) {
1788 if (component
.equals(new ComponentName(AuthenticatorActivity
.this, OperationsService
.class))) {
1789 Log_OC
.e(TAG
, "Operations service crashed");
1790 mOperationsServiceBinder
= null
;
1797 * Create and show dialog for request authentication to the user
1801 public void createAuthenticationDialog(WebView webView
, HttpAuthHandler handler
) {
1803 // Show a dialog with the certificate info
1804 CredentialsDialogFragment dialog
= CredentialsDialogFragment
.newInstanceForCredentials(webView
, handler
);
1805 FragmentManager fm
= getSupportFragmentManager();
1806 FragmentTransaction ft
= fm
.beginTransaction();
1807 ft
.addToBackStack(null
);
1808 dialog
.setCancelable(false
);
1809 dialog
.show(ft
, CREDENTIALS_DIALOG_TAG
);
1811 if (!mIsFirstAuthAttempt
) {
1812 Toast
.makeText(getApplicationContext(), getText(R
.string
.saml_authentication_wrong_pass
), Toast
.LENGTH_LONG
).show();
1814 mIsFirstAuthAttempt
= false
;
1819 * For retrieving the clicking on authentication cancel button
1821 public void doNegativeAuthenticatioDialogClick(){
1822 mIsFirstAuthAttempt
= true
;