1 /* ownCloud Android client application
3 * @author Bartek Przybylski
4 * @author David A. Velasco
6 * Copyright (C) 2012 Bartek Przybylski
7 * Copyright (C) 2012-2015 ownCloud Inc.
9 * This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2,
11 * as published by the Free Software Foundation.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 package com
.owncloud
.android
.authentication
;
25 import java
.security
.cert
.X509Certificate
;
28 import android
.accounts
.Account
;
29 import android
.accounts
.AccountManager
;
30 import android
.app
.Dialog
;
31 import android
.content
.ComponentName
;
32 import android
.content
.Context
;
33 import android
.content
.Intent
;
34 import android
.content
.ServiceConnection
;
35 import android
.content
.SharedPreferences
;
36 import android
.graphics
.Rect
;
37 import android
.graphics
.drawable
.Drawable
;
38 import android
.net
.Uri
;
39 import android
.net
.http
.SslError
;
40 import android
.os
.Bundle
;
41 import android
.os
.Handler
;
42 import android
.os
.IBinder
;
43 import android
.preference
.PreferenceManager
;
44 import android
.support
.v4
.app
.Fragment
;
45 import android
.support
.v4
.app
.FragmentManager
;
46 import android
.support
.v4
.app
.FragmentTransaction
;
47 import android
.text
.Editable
;
48 import android
.text
.InputType
;
49 import android
.text
.TextWatcher
;
50 import android
.view
.KeyEvent
;
51 import android
.view
.MotionEvent
;
52 import android
.view
.View
;
53 import android
.view
.View
.OnFocusChangeListener
;
54 import android
.view
.View
.OnTouchListener
;
55 import android
.view
.Window
;
56 import android
.view
.inputmethod
.EditorInfo
;
57 import android
.webkit
.HttpAuthHandler
;
58 import android
.webkit
.SslErrorHandler
;
59 import android
.webkit
.WebView
;
60 import android
.widget
.Button
;
61 import android
.widget
.CheckBox
;
62 import android
.widget
.EditText
;
63 import android
.widget
.TextView
;
64 import android
.widget
.TextView
.OnEditorActionListener
;
65 import android
.widget
.Toast
;
67 import com
.actionbarsherlock
.app
.SherlockDialogFragment
;
68 import com
.owncloud
.android
.MainApp
;
69 import com
.owncloud
.android
.R
;
70 import com
.owncloud
.android
.authentication
.SsoWebViewClient
.SsoWebViewClientListener
;
71 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
72 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentialsFactory
;
73 import com
.owncloud
.android
.lib
.common
.accounts
.AccountTypeUtils
;
74 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
75 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.Constants
;
76 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
77 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
78 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
79 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
80 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
81 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
82 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
83 import com
.owncloud
.android
.lib
.resources
.users
.GetRemoteUserNameOperation
;
84 import com
.owncloud
.android
.operations
.DetectAuthenticationMethodOperation
.AuthenticationMethod
;
85 import com
.owncloud
.android
.operations
.GetServerInfoOperation
;
86 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
87 import com
.owncloud
.android
.services
.OperationsService
;
88 import com
.owncloud
.android
.services
.OperationsService
.OperationsServiceBinder
;
89 import com
.owncloud
.android
.ui
.dialog
.CredentialsDialogFragment
;
90 import com
.owncloud
.android
.ui
.dialog
.IndeterminateProgressDialog
;
91 import com
.owncloud
.android
.ui
.dialog
.SamlWebViewDialog
;
92 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
93 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
94 import com
.owncloud
.android
.utils
.DisplayUtils
;
97 * This Activity is used to add an ownCloud account to the App
99 public class AuthenticatorActivity
extends AccountAuthenticatorActivity
100 implements OnRemoteOperationListener
, OnFocusChangeListener
, OnEditorActionListener
,
101 SsoWebViewClientListener
, OnSslUntrustedCertListener
,
102 AuthenticatorAsyncTask
.OnAuthenticatorTaskListener
{
104 private static final String TAG
= AuthenticatorActivity
.class.getSimpleName();
106 public static final String EXTRA_ACTION
= "ACTION";
107 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
109 private static final String KEY_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
111 private static final String KEY_HOST_URL_TEXT
= "HOST_URL_TEXT";
112 private static final String KEY_OC_VERSION
= "OC_VERSION";
113 private static final String KEY_SERVER_VALID
= "SERVER_VALID";
114 private static final String KEY_SERVER_CHECKED
= "SERVER_CHECKED";
115 private static final String KEY_SERVER_STATUS_TEXT
= "SERVER_STATUS_TEXT";
116 private static final String KEY_SERVER_STATUS_ICON
= "SERVER_STATUS_ICON";
117 private static final String KEY_IS_SSL_CONN
= "IS_SSL_CONN";
118 private static final String KEY_PASSWORD_EXPOSED
= "PASSWORD_VISIBLE";
119 private static final String KEY_AUTH_STATUS_TEXT
= "AUTH_STATUS_TEXT";
120 private static final String KEY_AUTH_STATUS_ICON
= "AUTH_STATUS_ICON";
121 private static final String KEY_SERVER_AUTH_METHOD
= "SERVER_AUTH_METHOD";
122 private static final String KEY_WAITING_FOR_OP_ID
= "WAITING_FOR_OP_ID";
123 private static final String KEY_AUTH_TOKEN
= "AUTH_TOKEN";
125 private static final String AUTH_ON
= "on";
126 private static final String AUTH_OPTIONAL
= "optional";
128 public static final byte ACTION_CREATE
= 0;
129 public static final byte ACTION_UPDATE_TOKEN
= 1; // requested by the user
130 public static final byte ACTION_UPDATE_EXPIRED_TOKEN
= 2; // detected by the app
132 private static final String UNTRUSTED_CERT_DIALOG_TAG
= "UNTRUSTED_CERT_DIALOG";
133 private static final String SAML_DIALOG_TAG
= "SAML_DIALOG";
134 private static final String WAIT_DIALOG_TAG
= "WAIT_DIALOG";
135 private static final String CREDENTIALS_DIALOG_TAG
= "CREDENTIALS_DIALOG";
136 private static final String KEY_AUTH_IS_FIRST_ATTEMPT_TAG
= "KEY_AUTH_IS_FIRST_ATTEMPT";
138 private static final String KEY_USERNAME
= "USERNAME";
139 private static final String KEY_PASSWORD
= "PASSWORD";
140 private static final String KEY_ASYNC_TASK_IN_PROGRESS
= "AUTH_IN_PROGRESS";
142 /// parameters from EXTRAs in starter Intent
143 private byte mAction
;
144 private Account mAccount
;
145 private String mAuthTokenType
;
148 /// activity-level references / state
149 private final Handler mHandler
= new Handler();
150 private ServiceConnection mOperationsServiceConnection
= null
;
151 private OperationsServiceBinder mOperationsServiceBinder
= null
;
152 private AccountManager mAccountMgr
;
153 private Uri mNewCapturedUriFromOAuth2Redirection
;
156 /// Server PRE-Fragment elements
157 private EditText mHostUrlInput
;
158 private View mRefreshButton
;
159 private TextView mServerStatusView
;
161 private TextWatcher mHostUrlInputWatcher
;
162 private int mServerStatusText
= 0, mServerStatusIcon
= 0;
164 private boolean mServerIsChecked
= false
;
165 private boolean mServerIsValid
= false
;
166 private boolean mPendingAutoCheck
= false
;
168 private GetServerInfoOperation
.ServerInfo mServerInfo
=
169 new GetServerInfoOperation
.ServerInfo();
172 /// Authentication PRE-Fragment elements
173 private CheckBox mOAuth2Check
;
174 private TextView mOAuthAuthEndpointText
;
175 private TextView mOAuthTokenEndpointText
;
176 private EditText mUsernameInput
;
177 private EditText mPasswordInput
;
178 private View mOkButton
;
179 private TextView mAuthStatusView
;
181 private int mAuthStatusText
= 0, mAuthStatusIcon
= 0;
183 private String mAuthToken
= "";
184 private AuthenticatorAsyncTask mAsyncTask
;
186 private boolean mIsFirstAuthAttempt
;
188 /// Identifier of operation in progress which result shouldn't be lost
189 private long mWaitingForOpId
= Long
.MAX_VALUE
;
191 private final String BASIC_TOKEN_TYPE
= AccountTypeUtils
.getAuthTokenTypePass(MainApp
.getAccountType());
192 private final String OAUTH_TOKEN_TYPE
= AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType());
193 private final String SAML_TOKEN_TYPE
=
194 AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
200 * IMPORTANT ENTRY POINT 1: activity is shown to the user
203 protected void onCreate(Bundle savedInstanceState
) {
204 //Log_OC.wtf(TAG, "onCreate init");
205 super.onCreate(savedInstanceState
);
206 getWindow().requestFeature(Window
.FEATURE_NO_TITLE
);
208 mIsFirstAuthAttempt
= true
;
210 // bind to Operations Service
211 mOperationsServiceConnection
= new OperationsServiceConnection();
212 if (!bindService(new Intent(this, OperationsService
.class),
213 mOperationsServiceConnection
,
214 Context
.BIND_AUTO_CREATE
)) {
216 R
.string
.error_cant_bind_to_operations_service
,
222 /// init activity state
223 mAccountMgr
= AccountManager
.get(this);
224 mNewCapturedUriFromOAuth2Redirection
= null
;
227 mAction
= getIntent().getByteExtra(EXTRA_ACTION
, ACTION_CREATE
);
228 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
229 if (savedInstanceState
== null
) {
232 mAuthTokenType
= savedInstanceState
.getString(KEY_AUTH_TOKEN_TYPE
);
233 mWaitingForOpId
= savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
);
234 mIsFirstAuthAttempt
= savedInstanceState
.getBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
);
237 /// load user interface
238 setContentView(R
.layout
.account_setup
);
240 /// initialize general UI elements
243 mOkButton
= findViewById(R
.id
.buttonOK
);
245 /// initialize block to be moved to single Fragment to check server and get info about it
246 initServerPreFragment(savedInstanceState
);
248 /// initialize block to be moved to single Fragment to retrieve and validate credentials
249 initAuthorizationPreFragment(savedInstanceState
);
251 //Log_OC.wtf(TAG, "onCreate end");
254 private void initAuthTokenType() {
256 getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
257 if (mAuthTokenType
== null
) {
258 if (mAccount
!= null
) {
259 boolean oAuthRequired
=
260 (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
) != null
);
261 boolean samlWebSsoRequired
= (
262 mAccountMgr
.getUserData(
263 mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
266 mAuthTokenType
= chooseAuthTokenType(oAuthRequired
, samlWebSsoRequired
);
269 boolean oAuthSupported
= AUTH_ON
.equals(getString(R
.string
.auth_method_oauth2
));
270 boolean samlWebSsoSupported
=
271 AUTH_ON
.equals(getString(R
.string
.auth_method_saml_web_sso
));
272 mAuthTokenType
= chooseAuthTokenType(oAuthSupported
, samlWebSsoSupported
);
277 private String
chooseAuthTokenType(boolean oauth
, boolean saml
) {
279 return SAML_TOKEN_TYPE
;
281 return OAUTH_TOKEN_TYPE
;
283 return BASIC_TOKEN_TYPE
;
289 * Configures elements in the user interface under direct control of the Activity.
291 private void initOverallUi() {
293 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
294 boolean isWelcomeLinkVisible
= getResources().getBoolean(R
.bool
.show_welcome_link
);
296 String instructionsMessageText
= null
;
297 if (mAction
== ACTION_UPDATE_EXPIRED_TOKEN
) {
298 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
299 .equals(mAuthTokenType
)) {
300 instructionsMessageText
= getString(R
.string
.auth_expired_oauth_token_toast
);
302 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType())
303 .equals(mAuthTokenType
)) {
304 instructionsMessageText
= getString(R
.string
.auth_expired_saml_sso_token_toast
);
307 instructionsMessageText
= getString(R
.string
.auth_expired_basic_auth_toast
);
311 /// step 2 - set properties of UI elements (text, visibility, enabled...)
312 Button welcomeLink
= (Button
) findViewById(R
.id
.welcome_link
);
313 welcomeLink
.setVisibility(isWelcomeLinkVisible ? View
.VISIBLE
: View
.GONE
);
315 String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
317 TextView instructionsView
= (TextView
) findViewById(R
.id
.instructions_message
);
318 if (instructionsMessageText
!= null
) {
319 instructionsView
.setVisibility(View
.VISIBLE
);
320 instructionsView
.setText(instructionsMessageText
);
322 instructionsView
.setVisibility(View
.GONE
);
329 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
331 private void initServerPreFragment(Bundle savedInstanceState
) {
333 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
334 boolean isUrlInputAllowed
= getResources().getBoolean(R
.bool
.show_server_url_input
);
335 if (savedInstanceState
== null
) {
336 if (mAccount
!= null
) {
337 mServerInfo
.mBaseUrl
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_BASE_URL
);
338 // TODO do next in a setter for mBaseUrl
339 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
340 String ocVersion
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_VERSION
);
341 if (ocVersion
!= null
) {
342 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
345 mServerInfo
.mBaseUrl
= getString(R
.string
.server_url
).trim();
346 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
349 mServerStatusText
= savedInstanceState
.getInt(KEY_SERVER_STATUS_TEXT
);
350 mServerStatusIcon
= savedInstanceState
.getInt(KEY_SERVER_STATUS_ICON
);
352 mServerIsValid
= savedInstanceState
.getBoolean(KEY_SERVER_VALID
);
353 mServerIsChecked
= savedInstanceState
.getBoolean(KEY_SERVER_CHECKED
);
356 mServerInfo
.mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
357 mServerInfo
.mBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
358 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
359 if (ocVersion
!= null
) {
360 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
362 mServerInfo
.mAuthMethod
= AuthenticationMethod
.valueOf(
363 savedInstanceState
.getString(KEY_SERVER_AUTH_METHOD
));
367 /// step 2 - set properties of UI elements (text, visibility, enabled...)
368 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
369 // Convert IDN to Unicode
370 mHostUrlInput
.setText(DisplayUtils
.convertIdn(mServerInfo
.mBaseUrl
, false
));
371 if (mAction
!= ACTION_CREATE
) {
372 /// lock things that should not change
373 mHostUrlInput
.setEnabled(false
);
374 mHostUrlInput
.setFocusable(false
);
376 if (isUrlInputAllowed
) {
377 mRefreshButton
= findViewById(R
.id
.embeddedRefreshButton
);
379 findViewById(R
.id
.hostUrlFrame
).setVisibility(View
.GONE
);
380 mRefreshButton
= findViewById(R
.id
.centeredRefreshButton
);
382 showRefreshButton(mServerIsChecked
&& !mServerIsValid
&&
383 mWaitingForOpId
> Integer
.MAX_VALUE
);
384 mServerStatusView
= (TextView
) findViewById(R
.id
.server_status_text
);
387 /// step 3 - bind some listeners and options
388 mHostUrlInput
.setImeOptions(EditorInfo
.IME_ACTION_NEXT
);
389 mHostUrlInput
.setOnEditorActionListener(this);
391 /// step 4 - create listeners that will be bound at onResume
392 mHostUrlInputWatcher
= new TextWatcher() {
395 public void afterTextChanged(Editable s
) {
396 if (mOkButton
.isEnabled() &&
397 !mServerInfo
.mBaseUrl
.equals(
398 normalizeUrl(s
.toString(), mServerInfo
.mIsSslConn
))) {
399 mOkButton
.setEnabled(false
);
404 public void beforeTextChanged(CharSequence s
, int start
, int count
, int after
) {
408 public void onTextChanged(CharSequence s
, int start
, int before
, int count
) {
409 if (mAuthStatusIcon
!= 0) {
410 Log_OC
.d(TAG
, "onTextChanged: hiding authentication status");
419 // TODO find out if this is really necessary, or if it can done in a different way
420 findViewById(R
.id
.scroll
).setOnTouchListener(new OnTouchListener() {
422 public boolean onTouch(View view
, MotionEvent event
) {
423 if (event
.getAction() == MotionEvent
.ACTION_DOWN
) {
425 AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(
426 MainApp
.getAccountType()
427 ).equals(mAuthTokenType
) &&
428 mHostUrlInput
.hasFocus()
438 /// step 4 - mark automatic check to be started when OperationsService is ready
439 mPendingAutoCheck
= (savedInstanceState
== null
&&
440 (mAction
!= ACTION_CREATE
|| !isUrlInputAllowed
));
446 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
448 private void initAuthorizationPreFragment(Bundle savedInstanceState
) {
450 /// step 0 - get UI elements in layout
451 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
452 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
453 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
454 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
455 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
456 mAuthStatusView
= (TextView
) findViewById(R
.id
.auth_status_text
);
458 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
459 String presetUserName
= null
;
460 boolean isPasswordExposed
= false
;
461 if (savedInstanceState
== null
) {
462 if (mAccount
!= null
) {
463 presetUserName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
467 isPasswordExposed
= savedInstanceState
.getBoolean(KEY_PASSWORD_EXPOSED
, false
);
468 mAuthStatusText
= savedInstanceState
.getInt(KEY_AUTH_STATUS_TEXT
);
469 mAuthStatusIcon
= savedInstanceState
.getInt(KEY_AUTH_STATUS_ICON
);
470 mAuthToken
= savedInstanceState
.getString(KEY_AUTH_TOKEN
);
473 /// step 2 - set properties of UI elements (text, visibility, enabled...)
474 mOAuth2Check
.setChecked(
475 AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
476 .equals(mAuthTokenType
));
477 if (presetUserName
!= null
) {
478 mUsernameInput
.setText(presetUserName
);
480 if (mAction
!= ACTION_CREATE
) {
481 mUsernameInput
.setEnabled(false
);
482 mUsernameInput
.setFocusable(false
);
484 mPasswordInput
.setText(""); // clean password to avoid social hacking
485 if (isPasswordExposed
) {
488 updateAuthenticationPreFragmentVisibility();
490 mOkButton
.setEnabled(mServerIsValid
);
493 /// step 3 - bind listeners
494 // bindings for password input field
495 mPasswordInput
.setOnFocusChangeListener(this);
496 mPasswordInput
.setImeOptions(EditorInfo
.IME_ACTION_DONE
);
497 mPasswordInput
.setOnEditorActionListener(this);
498 mPasswordInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
500 public boolean onDrawableTouch(final MotionEvent event
) {
501 if (event
.getAction() == MotionEvent
.ACTION_UP
) {
502 AuthenticatorActivity
.this.onViewPasswordClick();
512 * Changes the visibility of input elements depending on
513 * the current authorization method.
515 private void updateAuthenticationPreFragmentVisibility () {
516 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
517 equals(mAuthTokenType
)) {
518 // SAML-based web Single Sign On
519 mOAuth2Check
.setVisibility(View
.GONE
);
520 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
521 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
522 mUsernameInput
.setVisibility(View
.GONE
);
523 mPasswordInput
.setVisibility(View
.GONE
);
526 if (mAction
== ACTION_CREATE
&&
527 AUTH_OPTIONAL
.equals(getString(R
.string
.auth_method_oauth2
))) {
528 mOAuth2Check
.setVisibility(View
.VISIBLE
);
530 mOAuth2Check
.setVisibility(View
.GONE
);
533 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
534 equals(mAuthTokenType
)) {
535 // OAuth 2 authorization
537 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
538 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
539 mUsernameInput
.setVisibility(View
.GONE
);
540 mPasswordInput
.setVisibility(View
.GONE
);
543 // basic HTTP authorization
544 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
545 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
546 mUsernameInput
.setVisibility(View
.VISIBLE
);
547 mPasswordInput
.setVisibility(View
.VISIBLE
);
555 * Saves relevant state before {@link #onPause()}
557 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag,
558 * intended to defer the processing of the redirection caught in
559 * {@link #onNewIntent(Intent)} until {@link #onResume()}
561 * See {@link #onSaveInstanceState(Bundle)}
564 protected void onSaveInstanceState(Bundle outState
) {
565 //Log_OC.wtf(TAG, "onSaveInstanceState init" );
566 super.onSaveInstanceState(outState
);
569 outState
.putString(KEY_AUTH_TOKEN_TYPE
, mAuthTokenType
);
570 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mWaitingForOpId
);
572 /// Server PRE-fragment state
573 outState
.putInt(KEY_SERVER_STATUS_TEXT
, mServerStatusText
);
574 outState
.putInt(KEY_SERVER_STATUS_ICON
, mServerStatusIcon
);
575 outState
.putBoolean(KEY_SERVER_CHECKED
, mServerIsChecked
);
576 outState
.putBoolean(KEY_SERVER_VALID
, mServerIsValid
);
577 outState
.putBoolean(KEY_IS_SSL_CONN
, mServerInfo
.mIsSslConn
);
578 outState
.putString(KEY_HOST_URL_TEXT
, mServerInfo
.mBaseUrl
);
579 if (mServerInfo
.mVersion
!= null
) {
580 outState
.putString(KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion());
582 outState
.putString(KEY_SERVER_AUTH_METHOD
, mServerInfo
.mAuthMethod
.name());
584 /// Authentication PRE-fragment state
585 outState
.putBoolean(KEY_PASSWORD_EXPOSED
, isPasswordVisible());
586 outState
.putInt(KEY_AUTH_STATUS_ICON
, mAuthStatusIcon
);
587 outState
.putInt(KEY_AUTH_STATUS_TEXT
, mAuthStatusText
);
588 outState
.putString(KEY_AUTH_TOKEN
, mAuthToken
);
591 outState
.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
, mIsFirstAuthAttempt
);
593 /// AsyncTask (User and password)
594 outState
.putString(KEY_USERNAME
, mUsernameInput
.getText().toString());
595 outState
.putString(KEY_PASSWORD
, mPasswordInput
.getText().toString());
597 if (mAsyncTask
!= null
) {
598 mAsyncTask
.cancel(true
);
599 outState
.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS
, true
);
601 outState
.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS
, false
);
605 //Log_OC.wtf(TAG, "onSaveInstanceState end" );
609 public void onRestoreInstanceState(Bundle savedInstanceState
) {
610 super.onRestoreInstanceState(savedInstanceState
);
613 boolean inProgress
= savedInstanceState
.getBoolean(KEY_ASYNC_TASK_IN_PROGRESS
);
615 String username
= savedInstanceState
.getString(KEY_USERNAME
);
616 String password
= savedInstanceState
.getString(KEY_PASSWORD
);
618 OwnCloudCredentials credentials
= null
;
619 if (BASIC_TOKEN_TYPE
.equals(mAuthTokenType
)) {
620 credentials
= OwnCloudCredentialsFactory
.newBasicCredentials(username
, password
);
622 } else if (OAUTH_TOKEN_TYPE
.equals(mAuthTokenType
)) {
623 credentials
= OwnCloudCredentialsFactory
.newBearerCredentials(mAuthToken
);
626 accessRootFolder(credentials
);
631 * The redirection triggered by the OAuth authentication server as response to the
632 * GET AUTHORIZATION request is caught here.
634 * To make this possible, this activity needs to be qualified with android:launchMode =
635 * "singleTask" in the AndroidManifest.xml file.
638 protected void onNewIntent (Intent intent
) {
639 Log_OC
.d(TAG
, "onNewIntent()");
640 Uri data
= intent
.getData();
641 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
642 mNewCapturedUriFromOAuth2Redirection
= data
;
648 * The redirection triggered by the OAuth authentication server as response to the
649 * GET AUTHORIZATION, and deferred in {@link #onNewIntent(Intent)}, is processed here.
652 protected void onResume() {
655 // bound here to avoid spurious changes triggered by Android on device rotations
656 mHostUrlInput
.setOnFocusChangeListener(this);
657 mHostUrlInput
.addTextChangedListener(mHostUrlInputWatcher
);
659 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
660 getOAuth2AccessTokenFromCapturedRedirection();
663 if (mOperationsServiceBinder
!= null
) {
664 doOnResumeAndBound();
671 protected void onPause() {
672 if (mOperationsServiceBinder
!= null
) {
673 mOperationsServiceBinder
.removeOperationListener(this);
676 mHostUrlInput
.removeTextChangedListener(mHostUrlInputWatcher
);
677 mHostUrlInput
.setOnFocusChangeListener(null
);
683 protected void onDestroy() {
685 mHostUrlInputWatcher
= null
;
687 if (mOperationsServiceConnection
!= null
) {
688 unbindService(mOperationsServiceConnection
);
689 mOperationsServiceBinder
= null
;
696 * Parses the redirection with the response to the GET AUTHORIZATION request to the
697 * oAuth server and requests for the access token (GET ACCESS TOKEN)
699 private void getOAuth2AccessTokenFromCapturedRedirection() {
700 /// Parse data from OAuth redirection
701 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
702 mNewCapturedUriFromOAuth2Redirection
= null
;
704 /// Showing the dialog with instructions for the user.
705 IndeterminateProgressDialog dialog
=
706 IndeterminateProgressDialog
.newInstance(R
.string
.auth_getting_authorization
, true
);
707 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
709 /// GET ACCESS TOKEN to the oAuth server
710 Intent getServerInfoIntent
= new Intent();
711 getServerInfoIntent
.setAction(OperationsService
.ACTION_OAUTH2_GET_ACCESS_TOKEN
);
713 getServerInfoIntent
.putExtra(
714 OperationsService
.EXTRA_SERVER_URL
,
715 mOAuthTokenEndpointText
.getText().toString().trim());
717 getServerInfoIntent
.putExtra(
718 OperationsService
.EXTRA_OAUTH2_QUERY_PARAMETERS
,
721 if (mOperationsServiceBinder
!= null
) {
722 //Log_OC.wtf(TAG, "getting access token..." );
723 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
730 * Handles the change of focus on the text inputs for the server URL and the password
732 public void onFocusChange(View view
, boolean hasFocus
) {
733 if (view
.getId() == R
.id
.hostUrlInput
) {
735 onUrlInputFocusLost();
738 showRefreshButton(false
);
741 } else if (view
.getId() == R
.id
.account_password
) {
742 onPasswordFocusChanged(hasFocus
);
748 * Handles changes in focus on the text input for the server URL.
750 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
751 * other field. The operation to check the existence of the server in the entered URL is
754 * When hasFocus: user 'comes back' to write again the server URL.
756 private void onUrlInputFocusLost() {
757 if (!mServerInfo
.mBaseUrl
.equals(
758 normalizeUrl(mHostUrlInput
.getText().toString(), mServerInfo
.mIsSslConn
))) {
759 // check server again only if the user changed something in the field
762 mOkButton
.setEnabled(mServerIsValid
);
763 showRefreshButton(!mServerIsValid
);
768 private void checkOcServer() {
769 String uri
= mHostUrlInput
.getText().toString().trim();
770 mServerIsValid
= false
;
771 mServerIsChecked
= false
;
772 mOkButton
.setEnabled(false
);
773 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
774 showRefreshButton(false
);
776 if (uri
.length() != 0) {
777 // Handle internationalized domain names
778 uri
= DisplayUtils
.convertIdn(uri
, true
);
779 mServerStatusText
= R
.string
.auth_testing_connection
;
780 mServerStatusIcon
= R
.drawable
.progress_small
;
783 Intent getServerInfoIntent
= new Intent();
784 getServerInfoIntent
.setAction(OperationsService
.ACTION_GET_SERVER_INFO
);
785 getServerInfoIntent
.putExtra(
786 OperationsService
.EXTRA_SERVER_URL
,
787 normalizeUrlSuffix(uri
)
789 if (mOperationsServiceBinder
!= null
) {
790 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
792 Log_OC
.wtf(TAG
, "Server check tried with OperationService unbound!" );
796 mServerStatusText
= 0;
797 mServerStatusIcon
= 0;
804 * Handles changes in focus on the text input for the password (basic authorization).
806 * When (hasFocus), the button to toggle password visibility is shown.
808 * When (!hasFocus), the button is made invisible and the password is hidden.
810 * @param hasFocus 'True' if focus is received, 'false' if is lost
812 private void onPasswordFocusChanged(boolean hasFocus
) {
814 showViewPasswordButton();
817 hidePasswordButton();
822 private void showViewPasswordButton() {
823 int drawable
= R
.drawable
.ic_view
;
824 if (isPasswordVisible()) {
825 drawable
= R
.drawable
.ic_hide
;
827 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable
, 0);
830 private boolean isPasswordVisible() {
831 return ((mPasswordInput
.getInputType() & InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) ==
832 InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
835 private void hidePasswordButton() {
836 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
839 private void showPassword() {
840 mPasswordInput
.setInputType(
841 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
843 showViewPasswordButton();
846 private void hidePassword() {
847 mPasswordInput
.setInputType(
848 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
850 showViewPasswordButton();
854 * Checks the credentials of the user in the root of the ownCloud server
855 * before creating a new local account.
857 * For basic authorization, a check of existence of the root folder is
860 * For OAuth, starts the flow to get an access token; the credentials test
861 * is postponed until it is available.
863 * IMPORTANT ENTRY POINT 4
865 * @param view OK button
867 public void onOkClick(View view
) {
868 // this check should be unnecessary
869 if (mServerInfo
.mVersion
== null
||
870 !mServerInfo
.mVersion
.isVersionValid() ||
871 mServerInfo
.mBaseUrl
== null
||
872 mServerInfo
.mBaseUrl
.length() == 0) {
873 mServerStatusIcon
= R
.drawable
.common_error
;
874 mServerStatusText
= R
.string
.auth_wtf_reenter_URL
;
876 mOkButton
.setEnabled(false
);
880 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
881 equals(mAuthTokenType
)) {
883 startOauthorization();
884 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
885 equals(mAuthTokenType
)) {
887 startSamlBasedFederatedSingleSignOnAuthorization();
889 checkBasicAuthorization();
895 * Tests the credentials entered by the user performing a check of existence on
896 * the root folder of the ownCloud server.
898 private void checkBasicAuthorization() {
899 /// get basic credentials entered by user
900 String username
= mUsernameInput
.getText().toString();
901 String password
= mPasswordInput
.getText().toString();
903 /// be gentle with the user
904 IndeterminateProgressDialog dialog
=
905 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
906 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
908 /// validate credentials accessing the root folder
909 OwnCloudCredentials credentials
= OwnCloudCredentialsFactory
.newBasicCredentials(username
, password
);
910 accessRootFolder(credentials
);
913 private void accessRootFolder(OwnCloudCredentials credentials
) {
914 mAsyncTask
= new AuthenticatorAsyncTask(this);
915 Object
[] params
= { mServerInfo
.mBaseUrl
, credentials
};
916 mAsyncTask
.execute(params
);
921 * Starts the OAuth 'grant type' flow to get an access token, with
922 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
924 private void startOauthorization() {
925 // be gentle with the user
926 mAuthStatusIcon
= R
.drawable
.progress_small
;
927 mAuthStatusText
= R
.string
.oauth_login_connection
;
930 // GET AUTHORIZATION request
931 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
932 Uri
.Builder uriBuilder
= uri
.buildUpon();
933 uriBuilder
.appendQueryParameter(
934 OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
)
936 uriBuilder
.appendQueryParameter(
937 OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
)
939 uriBuilder
.appendQueryParameter(
940 OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
)
942 uriBuilder
.appendQueryParameter(
943 OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
)
945 uri
= uriBuilder
.build();
946 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
947 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
953 * Starts the Web Single Sign On flow to get access to the root folder
956 private void startSamlBasedFederatedSingleSignOnAuthorization() {
957 /// be gentle with the user
958 mAuthStatusIcon
= R
.drawable
.progress_small
;
959 mAuthStatusText
= R
.string
.auth_connecting_auth_server
;
962 /// Show SAML-based SSO web dialog
963 String targetUrl
= mServerInfo
.mBaseUrl
964 + AccountUtils
.getWebdavPath(mServerInfo
.mVersion
, mAuthTokenType
);
965 SamlWebViewDialog dialog
= SamlWebViewDialog
.newInstance(targetUrl
, targetUrl
);
966 dialog
.show(getSupportFragmentManager(), SAML_DIALOG_TAG
);
970 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
972 * Dispatches the operation flow to the right method.
975 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
977 if (operation
instanceof GetServerInfoOperation
) {
978 if (operation
.hashCode() == mWaitingForOpId
) {
979 onGetServerInfoFinish(result
);
980 } // else nothing ; only the last check operation is considered;
981 // multiple can be started if the user amends a URL quickly
983 } else if (operation
instanceof OAuth2GetAccessToken
) {
984 onGetOAuthAccessTokenFinish(result
);
986 } else if (operation
instanceof GetRemoteUserNameOperation
) {
987 onGetUserNameFinish(result
);
992 private void onGetUserNameFinish(RemoteOperationResult result
) {
993 mWaitingForOpId
= Long
.MAX_VALUE
;
994 if (result
.isSuccess()) {
995 boolean success
= false
;
996 String username
= (String
) result
.getData().get(0);
998 if ( mAction
== ACTION_CREATE
) {
999 mUsernameInput
.setText(username
);
1000 success
= createAccount();
1003 if (!mUsernameInput
.getText().toString().equals(username
)) {
1004 // fail - not a new account, but an existing one; disallow
1005 result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_THE_SAME
);
1007 updateAuthStatusIconAndText(result
);
1009 Log_OC
.d(TAG
, result
.getLogMessage());
1012 updateAccountAuthentication();
1015 } catch (AccountNotFoundException e
) {
1016 Log_OC
.e(TAG
, "Account " + mAccount
+ " was removed!", e
);
1017 Toast
.makeText(this, R
.string
.auth_account_does_not_exist
, Toast
.LENGTH_SHORT
).show();
1026 updateStatusIconFailUserName();
1028 Log_OC
.e(TAG
, "Access to user name failed: " + result
.getLogMessage());
1034 * Processes the result of the server check performed when the user finishes the enter of the
1037 * @param result Result of the check.
1039 private void onGetServerInfoFinish(RemoteOperationResult result
) {
1040 /// update activity state
1041 mServerIsChecked
= true
;
1042 mWaitingForOpId
= Long
.MAX_VALUE
;
1044 // update server status, but don't show it yet
1045 updateServerStatusIconAndText(result
);
1047 if (result
.isSuccess()) {
1049 // 1. connection succeeded, and we know if it's SSL or not
1050 // 2. server is installed
1051 // 3. we got the server version
1052 // 4. we got the authentication method required by the server
1053 mServerInfo
= (GetServerInfoOperation
.ServerInfo
) (result
.getData().get(0));
1055 if (!authSupported(mServerInfo
.mAuthMethod
)) {
1057 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1058 mServerIsValid
= false
;
1061 mServerIsValid
= true
;
1065 mServerIsValid
= false
;
1069 showRefreshButton(!mServerIsValid
);
1071 mOkButton
.setEnabled(mServerIsValid
);
1073 /// very special case (TODO: move to a common place for all the remote operations)
1074 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1075 showUntrustedCertDialog(result
);
1080 private boolean authSupported(AuthenticationMethod authMethod
) {
1081 return (( BASIC_TOKEN_TYPE
.equals(mAuthTokenType
) &&
1082 AuthenticationMethod
.BASIC_HTTP_AUTH
.equals(authMethod
) ) ||
1083 ( OAUTH_TOKEN_TYPE
.equals(mAuthTokenType
) &&
1084 AuthenticationMethod
.BEARER_TOKEN
.equals(authMethod
)) ||
1085 ( SAML_TOKEN_TYPE
.equals(mAuthTokenType
) &&
1086 AuthenticationMethod
.SAML_WEB_SSO
.equals(authMethod
))
1091 // TODO remove, if possible
1092 private String
normalizeUrl(String url
, boolean sslWhenUnprefixed
) {
1093 if (url
!= null
&& url
.length() > 0) {
1095 if (!url
.toLowerCase().startsWith("http://") &&
1096 !url
.toLowerCase().startsWith("https://")) {
1097 if (sslWhenUnprefixed
) {
1098 url
= "https://" + url
;
1100 url
= "http://" + url
;
1104 url
= normalizeUrlSuffix(url
);
1106 return (url
!= null ? url
: "");
1110 private String
normalizeUrlSuffix(String url
) {
1111 if (url
.endsWith("/")) {
1112 url
= url
.substring(0, url
.length() - 1);
1114 url
= trimUrlWebdav(url
);
1119 // TODO remove, if possible
1120 private String
trimUrlWebdav(String url
){
1121 if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_4_0
)){
1122 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_4_0
.length());
1123 } else if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_2_0
)){
1124 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_2_0
.length());
1125 } else if (url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_1_2
)){
1126 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_1_2
.length());
1128 return (url
!= null ? url
: "");
1133 * Chooses the right icon and text to show to the user for the received operation result.
1135 * @param result Result of a remote operation performed in this activity
1137 private void updateServerStatusIconAndText(RemoteOperationResult result
) {
1138 mServerStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1140 switch (result
.getCode()) {
1142 mServerStatusIcon
= android
.R
.drawable
.ic_secure
;
1143 mServerStatusText
= R
.string
.auth_secure_connection
;
1148 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1149 mServerStatusText
= R
.string
.auth_connection_established
;
1150 mServerStatusIcon
= R
.drawable
.ic_ok
;
1152 mServerStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1153 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1157 case NO_NETWORK_CONNECTION
:
1158 mServerStatusIcon
= R
.drawable
.no_network
;
1159 mServerStatusText
= R
.string
.auth_no_net_conn_title
;
1162 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1163 mServerStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1165 case BAD_OC_VERSION
:
1166 mServerStatusText
= R
.string
.auth_bad_oc_version_title
;
1168 case WRONG_CONNECTION
:
1169 mServerStatusText
= R
.string
.auth_wrong_connection_title
;
1172 mServerStatusText
= R
.string
.auth_timeout_title
;
1174 case INCORRECT_ADDRESS
:
1175 mServerStatusText
= R
.string
.auth_incorrect_address_title
;
1178 mServerStatusText
= R
.string
.auth_ssl_general_error_title
;
1181 mServerStatusText
= R
.string
.auth_unauthorized
;
1183 case HOST_NOT_AVAILABLE
:
1184 mServerStatusText
= R
.string
.auth_unknown_host_title
;
1186 case INSTANCE_NOT_CONFIGURED
:
1187 mServerStatusText
= R
.string
.auth_not_configured_title
;
1189 case FILE_NOT_FOUND
:
1190 mServerStatusText
= R
.string
.auth_incorrect_path_title
;
1193 mServerStatusText
= R
.string
.auth_oauth_error
;
1195 case OAUTH2_ERROR_ACCESS_DENIED
:
1196 mServerStatusText
= R
.string
.auth_oauth_error_access_denied
;
1198 case UNHANDLED_HTTP_CODE
:
1200 mServerStatusText
= R
.string
.auth_unknown_error_title
;
1202 case OK_REDIRECT_TO_NON_SECURE_CONNECTION
:
1203 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1204 mServerStatusText
= R
.string
.auth_redirect_non_secure_connection_title
;
1207 mServerStatusText
= 0;
1208 mServerStatusIcon
= 0;
1214 * Chooses the right icon and text to show to the user for the received operation result.
1216 * @param result Result of a remote operation performed in this activity
1218 private void updateAuthStatusIconAndText(RemoteOperationResult result
) {
1219 mAuthStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1221 switch (result
.getCode()) {
1223 mAuthStatusIcon
= android
.R
.drawable
.ic_secure
;
1224 mAuthStatusText
= R
.string
.auth_secure_connection
;
1229 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1230 mAuthStatusText
= R
.string
.auth_connection_established
;
1231 mAuthStatusIcon
= R
.drawable
.ic_ok
;
1233 mAuthStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1234 mAuthStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1238 case NO_NETWORK_CONNECTION
:
1239 mAuthStatusIcon
= R
.drawable
.no_network
;
1240 mAuthStatusText
= R
.string
.auth_no_net_conn_title
;
1243 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1244 mAuthStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1246 case BAD_OC_VERSION
:
1247 mAuthStatusText
= R
.string
.auth_bad_oc_version_title
;
1249 case WRONG_CONNECTION
:
1250 mAuthStatusText
= R
.string
.auth_wrong_connection_title
;
1253 mAuthStatusText
= R
.string
.auth_timeout_title
;
1255 case INCORRECT_ADDRESS
:
1256 mAuthStatusText
= R
.string
.auth_incorrect_address_title
;
1259 mAuthStatusText
= R
.string
.auth_ssl_general_error_title
;
1262 mAuthStatusText
= R
.string
.auth_unauthorized
;
1264 case HOST_NOT_AVAILABLE
:
1265 mAuthStatusText
= R
.string
.auth_unknown_host_title
;
1267 case INSTANCE_NOT_CONFIGURED
:
1268 mAuthStatusText
= R
.string
.auth_not_configured_title
;
1270 case FILE_NOT_FOUND
:
1271 mAuthStatusText
= R
.string
.auth_incorrect_path_title
;
1274 mAuthStatusText
= R
.string
.auth_oauth_error
;
1276 case OAUTH2_ERROR_ACCESS_DENIED
:
1277 mAuthStatusText
= R
.string
.auth_oauth_error_access_denied
;
1279 case ACCOUNT_NOT_NEW
:
1280 mAuthStatusText
= R
.string
.auth_account_not_new
;
1282 case ACCOUNT_NOT_THE_SAME
:
1283 mAuthStatusText
= R
.string
.auth_account_not_the_same
;
1285 case UNHANDLED_HTTP_CODE
:
1287 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
1290 mAuthStatusText
= 0;
1291 mAuthStatusIcon
= 0;
1296 private void updateStatusIconFailUserName(){
1297 mAuthStatusIcon
= R
.drawable
.common_error
;
1298 mAuthStatusText
= R
.string
.auth_fail_get_user_name
;
1301 private void updateServerStatusIconNoRegularAuth(){
1302 mServerStatusIcon
= R
.drawable
.common_error
;
1303 mServerStatusText
= R
.string
.auth_can_not_auth_against_server
;
1307 * Processes the result of the request for and access token send
1308 * to an OAuth authorization server.
1310 * @param result Result of the operation.
1312 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result
) {
1313 mWaitingForOpId
= Long
.MAX_VALUE
;
1314 dismissDialog(WAIT_DIALOG_TAG
);
1316 if (result
.isSuccess()) {
1317 /// be gentle with the user
1318 IndeterminateProgressDialog dialog
=
1319 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
1320 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
1322 /// time to test the retrieved access token on the ownCloud server
1323 @SuppressWarnings("unchecked")
1324 Map
<String
, String
> tokens
= (Map
<String
, String
>)(result
.getData().get(0));
1325 mAuthToken
= tokens
.get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
1326 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mAuthToken
);
1328 /// validate token accessing to root folder / getting session
1329 OwnCloudCredentials credentials
= OwnCloudCredentialsFactory
.newBearerCredentials(mAuthToken
);
1330 accessRootFolder(credentials
);
1333 updateAuthStatusIconAndText(result
);
1335 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1341 * Processes the result of the access check performed to try the user credentials.
1343 * Creates a new account through the AccountManager.
1345 * @param result Result of the operation.
1348 public void onAuthenticatorTaskCallback(RemoteOperationResult result
) {
1349 mWaitingForOpId
= Long
.MAX_VALUE
;
1350 dismissDialog(WAIT_DIALOG_TAG
);
1352 if (result
.isSuccess()) {
1353 Log_OC
.d(TAG
, "Successful access - time to save the account");
1355 boolean success
= false
;
1356 if (mAction
== ACTION_CREATE
) {
1357 success
= createAccount();
1361 updateAccountAuthentication();
1364 } catch (AccountNotFoundException e
) {
1365 Log_OC
.e(TAG
, "Account " + mAccount
+ " was removed!", e
);
1366 Toast
.makeText(this, R
.string
.auth_account_does_not_exist
, Toast
.LENGTH_SHORT
).show();
1375 } else if (result
.isServerFail() || result
.isException()) {
1376 /// server errors or exceptions in authorization take to requiring a new check of
1378 mServerIsChecked
= true
;
1379 mServerIsValid
= false
;
1380 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
1382 // update status icon and text
1383 updateServerStatusIconAndText(result
);
1385 mAuthStatusIcon
= 0;
1386 mAuthStatusText
= 0;
1389 // update input controls state
1390 showRefreshButton(true
);
1391 mOkButton
.setEnabled(false
);
1393 // very special case (TODO: move to a common place for all the remote operations)
1394 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1395 showUntrustedCertDialog(result
);
1398 } else { // authorization fail due to client side - probably wrong credentials
1399 updateAuthStatusIconAndText(result
);
1401 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1409 * Updates the authentication token.
1411 * Sets the proper response so that the AccountAuthenticator that started this activity
1412 * saves a new authorization token for mAccount.
1414 * Kills the session kept by OwnCloudClientManager so that a new one will created with
1415 * the new credentials when needed.
1417 private void updateAccountAuthentication() throws AccountNotFoundException
{
1419 Bundle response
= new Bundle();
1420 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1421 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
1423 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
1424 equals(mAuthTokenType
)) {
1425 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1426 // the next line is necessary, notifications are calling directly to the
1427 // AuthenticatorActivity to update, without AccountManager intervention
1428 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1430 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1431 equals(mAuthTokenType
)) {
1433 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1434 // the next line is necessary; by now, notifications are calling directly to the
1435 // AuthenticatorActivity to update, without AccountManager intervention
1436 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1439 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
1440 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
1442 setAccountAuthenticatorResult(response
);
1448 * Creates a new account through the Account Authenticator that started this activity.
1450 * This makes the account permanent.
1452 * TODO Decide how to name the OAuth accounts
1454 private boolean createAccount() {
1455 /// create and save new ownCloud account
1456 boolean isOAuth
= AccountTypeUtils
.
1457 getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
);
1458 boolean isSaml
= AccountTypeUtils
.
1459 getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
);
1461 Uri uri
= Uri
.parse(mServerInfo
.mBaseUrl
);
1462 String username
= mUsernameInput
.getText().toString().trim();
1464 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1466 String accountName
= com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.
1467 buildAccountName(uri
, username
);
1468 Account newAccount
= new Account(accountName
, MainApp
.getAccountType());
1469 if (AccountUtils
.exists(newAccount
, getApplicationContext())) {
1470 // fail - not a new account, but an existing one; disallow
1471 RemoteOperationResult result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_NEW
);
1472 updateAuthStatusIconAndText(result
);
1474 Log_OC
.d(TAG
, result
.getLogMessage());
1478 mAccount
= newAccount
;
1480 if (isOAuth
|| isSaml
) {
1481 // with external authorizations, the password is never input in the app
1482 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
);
1484 mAccountMgr
.addAccountExplicitly(
1485 mAccount
, mPasswordInput
.getText().toString(), null
1489 /// add the new account as default in preferences, if there is none already
1490 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1491 if (defaultAccount
== null
) {
1492 SharedPreferences
.Editor editor
= PreferenceManager
1493 .getDefaultSharedPreferences(this).edit();
1494 editor
.putString("select_oc_account", accountName
);
1498 /// prepare result to return to the Authenticator
1499 // TODO check again what the Authenticator makes with it; probably has the same
1500 // effect as addAccountExplicitly, but it's not well done
1501 final Intent intent
= new Intent();
1502 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, MainApp
.getAccountType());
1503 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1504 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1505 if (isOAuth
|| isSaml
) {
1506 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1508 /// add user data to the new account; TODO probably can be done in the last parameter
1509 // addAccountExplicitly, or in KEY_USERDATA
1510 mAccountMgr
.setUserData(
1511 mAccount
, Constants
.KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion()
1513 mAccountMgr
.setUserData(
1514 mAccount
, Constants
.KEY_OC_BASE_URL
, mServerInfo
.mBaseUrl
1518 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
, "TRUE");
1519 } else if (isOAuth
) {
1520 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
, "TRUE");
1523 setAccountAuthenticatorResult(intent
.getExtras());
1524 setResult(RESULT_OK
, intent
);
1532 * Starts and activity to open the 'new account' page in the ownCloud web site
1534 * @param view 'Account register' button
1536 public void onRegisterClick(View view
) {
1537 Intent register
= new Intent(
1538 Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.welcome_link_url
))
1540 setResult(RESULT_CANCELED
);
1541 startActivity(register
);
1546 * Updates the content and visibility state of the icon and text associated
1547 * to the last check on the ownCloud server.
1550 private void showServerStatus() {
1551 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1552 mServerStatusView
.setVisibility(View
.INVISIBLE
);
1555 mServerStatusView
.setText(mServerStatusText
);
1556 mServerStatusView
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1557 mServerStatusView
.setVisibility(View
.VISIBLE
);
1564 * Updates the content and visibility state of the icon and text associated
1565 * to the interactions with the OAuth authorization server.
1567 private void showAuthStatus() {
1568 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1569 mAuthStatusView
.setVisibility(View
.INVISIBLE
);
1572 mAuthStatusView
.setText(mAuthStatusText
);
1573 mAuthStatusView
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1574 mAuthStatusView
.setVisibility(View
.VISIBLE
);
1579 private void showRefreshButton (boolean show
) {
1581 mRefreshButton
.setVisibility(View
.VISIBLE
);
1583 mRefreshButton
.setVisibility(View
.GONE
);
1588 * Called when the refresh button in the input field for ownCloud host is clicked.
1590 * Performs a new check on the URL in the input field.
1592 * @param view Refresh 'button'
1594 public void onRefreshClick(View view
) {
1600 * Called when the eye icon in the password field is clicked.
1602 * Toggles the visibility of the password in the field.
1604 public void onViewPasswordClick() {
1605 int selectionStart
= mPasswordInput
.getSelectionStart();
1606 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1607 if (isPasswordVisible()) {
1612 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1617 * Called when the checkbox for OAuth authorization is clicked.
1619 * Hides or shows the input fields for user & password.
1621 * @param view 'View password' 'button'
1623 public void onCheckClick(View view
) {
1624 CheckBox oAuth2Check
= (CheckBox
)view
;
1625 if (oAuth2Check
.isChecked()) {
1626 mAuthTokenType
= OAUTH_TOKEN_TYPE
;
1628 mAuthTokenType
= BASIC_TOKEN_TYPE
;
1630 updateAuthenticationPreFragmentVisibility();
1635 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1637 * Used to trigger the authentication check when the user presses 'enter' after writing the
1638 * password, or to throw the server test when the only field on screen is the URL input field.
1641 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1642 if (actionId
== EditorInfo
.IME_ACTION_DONE
&& inputField
!= null
&&
1643 inputField
.equals(mPasswordInput
)) {
1644 if (mOkButton
.isEnabled()) {
1645 mOkButton
.performClick();
1648 } else if (actionId
== EditorInfo
.IME_ACTION_NEXT
&& inputField
!= null
&&
1649 inputField
.equals(mHostUrlInput
)) {
1650 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1651 equals(mAuthTokenType
)) {
1655 return false
; // always return false to grant that the software keyboard is hidden anyway
1659 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1661 private int fuzz
= 75;
1667 public boolean onTouch(View view
, MotionEvent event
) {
1668 Drawable rightDrawable
= null
;
1669 if (view
instanceof TextView
) {
1670 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1671 if (drawables
.length
> 2) {
1672 rightDrawable
= drawables
[2];
1675 if (rightDrawable
!= null
) {
1676 final int x
= (int) event
.getX();
1677 final int y
= (int) event
.getY();
1678 final Rect bounds
= rightDrawable
.getBounds();
1679 if ( x
>= (view
.getRight() - bounds
.width() - fuzz
) &&
1680 x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
) &&
1681 y
>= (view
.getPaddingTop() - fuzz
) &&
1682 y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1684 return onDrawableTouch(event
);
1690 public abstract boolean onDrawableTouch(final MotionEvent event
);
1694 private void getRemoteUserNameOperation(String sessionCookie
, boolean followRedirects
) {
1696 Intent getUserNameIntent
= new Intent();
1697 getUserNameIntent
.setAction(OperationsService
.ACTION_GET_USER_NAME
);
1698 getUserNameIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
1699 getUserNameIntent
.putExtra(OperationsService
.EXTRA_COOKIE
, sessionCookie
);
1701 if (mOperationsServiceBinder
!= null
) {
1702 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getUserNameIntent
);
1708 public void onSsoFinished(String sessionCookie
) {
1709 if (sessionCookie
!= null
&& sessionCookie
.length() > 0) {
1710 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1711 mAuthToken
= sessionCookie
;
1712 getRemoteUserNameOperation(sessionCookie
, true
);
1713 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1714 if (fd
!= null
&& fd
instanceof SherlockDialogFragment
) {
1715 Dialog d
= ((SherlockDialogFragment
)fd
).getDialog();
1716 if (d
!= null
&& d
.isShowing()) {
1723 Log_OC
.d(TAG
, "SSO failed");
1729 public boolean onTouchEvent(MotionEvent event
) {
1730 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1731 equals(mAuthTokenType
) &&
1732 mHostUrlInput
.hasFocus() && event
.getAction() == MotionEvent
.ACTION_DOWN
) {
1735 return super.onTouchEvent(event
);
1740 * Show untrusted cert dialog
1742 public void showUntrustedCertDialog(
1743 X509Certificate x509Certificate
, SslError error
, SslErrorHandler handler
1745 // Show a dialog with the certificate info
1746 SslUntrustedCertDialog dialog
= null
;
1747 if (x509Certificate
== null
) {
1748 dialog
= SslUntrustedCertDialog
.newInstanceForEmptySslError(error
, handler
);
1750 dialog
= SslUntrustedCertDialog
.
1751 newInstanceForFullSslError(x509Certificate
, error
, handler
);
1753 FragmentManager fm
= getSupportFragmentManager();
1754 FragmentTransaction ft
= fm
.beginTransaction();
1755 ft
.addToBackStack(null
);
1756 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1761 * Show untrusted cert dialog
1763 private void showUntrustedCertDialog(RemoteOperationResult result
) {
1764 // Show a dialog with the certificate info
1765 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.
1766 newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1767 FragmentManager fm
= getSupportFragmentManager();
1768 FragmentTransaction ft
= fm
.beginTransaction();
1769 ft
.addToBackStack(null
);
1770 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1775 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1777 public void onSavedCertificate() {
1778 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1780 // if SAML dialog is not shown,
1781 // the SslDialog was shown due to an SSL error in the server check
1787 * Called from SslValidatorDialog when a new server certificate could not be saved
1788 * when the user requested it.
1791 public void onFailedSavingCertificate() {
1792 dismissDialog(SAML_DIALOG_TAG
);
1793 Toast
.makeText(this, R
.string
.ssl_validator_not_saved
, Toast
.LENGTH_LONG
).show();
1797 public void onCancelCertificate() {
1798 dismissDialog(SAML_DIALOG_TAG
);
1802 private void doOnResumeAndBound() {
1803 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1804 mOperationsServiceBinder
.addOperationListener(AuthenticatorActivity
.this, mHandler
);
1805 if (mWaitingForOpId
<= Integer
.MAX_VALUE
) {
1806 mOperationsServiceBinder
.dispatchResultIfFinished((int)mWaitingForOpId
, this);
1809 if (mPendingAutoCheck
) {
1815 private void dismissDialog(String dialogTag
){
1816 Fragment frag
= getSupportFragmentManager().findFragmentByTag(dialogTag
);
1817 if (frag
!= null
&& frag
instanceof SherlockDialogFragment
) {
1818 SherlockDialogFragment dialog
= (SherlockDialogFragment
) frag
;
1825 * Implements callback methods for service binding.
1827 private class OperationsServiceConnection
implements ServiceConnection
{
1830 public void onServiceConnected(ComponentName component
, IBinder service
) {
1831 if (component
.equals(
1832 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1834 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
1836 doOnResumeAndBound();
1845 public void onServiceDisconnected(ComponentName component
) {
1846 if (component
.equals(
1847 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1849 Log_OC
.e(TAG
, "Operations service crashed");
1850 mOperationsServiceBinder
= null
;
1857 * Create and show dialog for request authentication to the user
1861 public void createAuthenticationDialog(WebView webView
, HttpAuthHandler handler
) {
1863 // Show a dialog with the certificate info
1864 CredentialsDialogFragment dialog
=
1865 CredentialsDialogFragment
.newInstanceForCredentials(webView
, handler
);
1866 FragmentManager fm
= getSupportFragmentManager();
1867 FragmentTransaction ft
= fm
.beginTransaction();
1868 ft
.addToBackStack(null
);
1869 dialog
.setCancelable(false
);
1870 dialog
.show(ft
, CREDENTIALS_DIALOG_TAG
);
1872 if (!mIsFirstAuthAttempt
) {
1874 getApplicationContext(),
1875 getText(R
.string
.saml_authentication_wrong_pass
),
1879 mIsFirstAuthAttempt
= false
;
1884 * For retrieving the clicking on authentication cancel button
1886 public void doNegativeAuthenticatioDialogClick(){
1887 mIsFirstAuthAttempt
= true
;