2 * ownCloud Android client application
4 * @author Bartek Przybylski
5 * @author David A. Velasco
7 * Copyright (C) 2012 Bartek Przybylski
8 * Copyright (C) 2015 ownCloud Inc.
10 * This program is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2,
12 * as published by the Free Software Foundation.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 package com
.owncloud
.android
.authentication
;
26 import android
.accounts
.Account
;
27 import android
.accounts
.AccountManager
;
28 import android
.app
.Dialog
;
29 import android
.content
.ComponentName
;
30 import android
.content
.Context
;
31 import android
.content
.Intent
;
32 import android
.content
.ServiceConnection
;
33 import android
.content
.SharedPreferences
;
34 import android
.graphics
.Rect
;
35 import android
.graphics
.drawable
.Drawable
;
36 import android
.net
.Uri
;
37 import android
.net
.http
.SslError
;
38 import android
.os
.Bundle
;
39 import android
.os
.Handler
;
40 import android
.os
.IBinder
;
41 import android
.preference
.PreferenceManager
;
42 import android
.support
.v4
.app
.DialogFragment
;
43 import android
.support
.v4
.app
.Fragment
;
44 import android
.support
.v4
.app
.FragmentManager
;
45 import android
.support
.v4
.app
.FragmentTransaction
;
46 import android
.text
.Editable
;
47 import android
.text
.InputType
;
48 import android
.text
.TextWatcher
;
49 import android
.view
.KeyEvent
;
50 import android
.view
.MotionEvent
;
51 import android
.view
.View
;
52 import android
.view
.View
.OnFocusChangeListener
;
53 import android
.view
.View
.OnTouchListener
;
54 import android
.view
.inputmethod
.EditorInfo
;
55 import android
.webkit
.HttpAuthHandler
;
56 import android
.webkit
.SslErrorHandler
;
57 import android
.webkit
.WebView
;
58 import android
.widget
.Button
;
59 import android
.widget
.CheckBox
;
60 import android
.widget
.EditText
;
61 import android
.widget
.TextView
;
62 import android
.widget
.TextView
.OnEditorActionListener
;
63 import android
.widget
.Toast
;
65 import com
.owncloud
.android
.MainApp
;
66 import com
.owncloud
.android
.R
;
67 import com
.owncloud
.android
.authentication
.SsoWebViewClient
.SsoWebViewClientListener
;
68 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
69 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentialsFactory
;
70 import com
.owncloud
.android
.lib
.common
.accounts
.AccountTypeUtils
;
71 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
72 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.Constants
;
73 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
74 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
75 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
76 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
77 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
78 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
79 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
80 import com
.owncloud
.android
.lib
.resources
.users
.GetRemoteUserNameOperation
;
81 import com
.owncloud
.android
.operations
.DetectAuthenticationMethodOperation
.AuthenticationMethod
;
82 import com
.owncloud
.android
.operations
.GetServerInfoOperation
;
83 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
84 import com
.owncloud
.android
.services
.OperationsService
;
85 import com
.owncloud
.android
.services
.OperationsService
.OperationsServiceBinder
;
86 import com
.owncloud
.android
.ui
.dialog
.CredentialsDialogFragment
;
87 import com
.owncloud
.android
.ui
.dialog
.IndeterminateProgressDialog
;
88 import com
.owncloud
.android
.ui
.dialog
.SamlWebViewDialog
;
89 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
90 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
91 import com
.owncloud
.android
.utils
.DisplayUtils
;
93 import java
.security
.cert
.X509Certificate
;
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 View mCenteredRefreshButton
;
180 private TextView mAuthStatusView
;
182 private int mAuthStatusText
= 0, mAuthStatusIcon
= 0;
184 private String mAuthToken
= "";
185 private AuthenticatorAsyncTask mAsyncTask
;
187 private boolean mIsFirstAuthAttempt
;
189 /// Identifier of operation in progress which result shouldn't be lost
190 private long mWaitingForOpId
= Long
.MAX_VALUE
;
192 private final String BASIC_TOKEN_TYPE
= AccountTypeUtils
.getAuthTokenTypePass(
193 MainApp
.getAccountType());
194 private final String OAUTH_TOKEN_TYPE
= AccountTypeUtils
.getAuthTokenTypeAccessToken(
195 MainApp
.getAccountType());
196 private final String SAML_TOKEN_TYPE
=
197 AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
203 * IMPORTANT ENTRY POINT 1: activity is shown to the user
206 protected void onCreate(Bundle savedInstanceState
) {
207 //Log_OC.wtf(TAG, "onCreate init");
208 super.onCreate(savedInstanceState
);
210 // Workaround, for fixing a problem with Android Library Suppor v7 19
211 //getWindow().requestFeature(Window.FEATURE_NO_TITLE);
212 if (getSupportActionBar() != null
) {
213 getSupportActionBar().hide();
215 getSupportActionBar().setDisplayHomeAsUpEnabled(false
);
216 getSupportActionBar().setDisplayShowHomeEnabled(false
);
217 getSupportActionBar().setDisplayShowTitleEnabled(false
);
220 mIsFirstAuthAttempt
= true
;
222 // bind to Operations Service
223 mOperationsServiceConnection
= new OperationsServiceConnection();
224 if (!bindService(new Intent(this, OperationsService
.class),
225 mOperationsServiceConnection
,
226 Context
.BIND_AUTO_CREATE
)) {
228 R
.string
.error_cant_bind_to_operations_service
,
234 /// init activity state
235 mAccountMgr
= AccountManager
.get(this);
236 mNewCapturedUriFromOAuth2Redirection
= null
;
239 mAction
= getIntent().getByteExtra(EXTRA_ACTION
, ACTION_CREATE
);
240 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
241 if (savedInstanceState
== null
) {
244 mAuthTokenType
= savedInstanceState
.getString(KEY_AUTH_TOKEN_TYPE
);
245 mWaitingForOpId
= savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
);
246 mIsFirstAuthAttempt
= savedInstanceState
.getBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
);
249 /// load user interface
250 setContentView(R
.layout
.account_setup
);
252 /// initialize general UI elements
255 mOkButton
= findViewById(R
.id
.buttonOK
);
256 mOkButton
.setOnClickListener(new View
.OnClickListener() {
259 public void onClick(View v
) {
264 mCenteredRefreshButton
= findViewById(R
.id
.centeredRefreshButton
);
265 mCenteredRefreshButton
.setOnClickListener(new View
.OnClickListener() {
268 public void onClick(View v
) {
273 mOkButton
= findViewById(R
.id
.buttonOK
);
274 mOkButton
.setOnClickListener(new View
.OnClickListener() {
277 public void onClick(View v
) {
282 mCenteredRefreshButton
= findViewById(R
.id
.centeredRefreshButton
);
283 mCenteredRefreshButton
.setOnClickListener(new View
.OnClickListener() {
286 public void onClick(View v
) {
292 /// initialize block to be moved to single Fragment to check server and get info about it
293 initServerPreFragment(savedInstanceState
);
295 /// initialize block to be moved to single Fragment to retrieve and validate credentials
296 initAuthorizationPreFragment(savedInstanceState
);
298 //Log_OC.wtf(TAG, "onCreate end");
301 private void initAuthTokenType() {
303 getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
304 if (mAuthTokenType
== null
) {
305 if (mAccount
!= null
) {
306 boolean oAuthRequired
=
307 (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
) != null
);
308 boolean samlWebSsoRequired
= (
309 mAccountMgr
.getUserData(
310 mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
313 mAuthTokenType
= chooseAuthTokenType(oAuthRequired
, samlWebSsoRequired
);
316 boolean oAuthSupported
= AUTH_ON
.equals(getString(R
.string
.auth_method_oauth2
));
317 boolean samlWebSsoSupported
=
318 AUTH_ON
.equals(getString(R
.string
.auth_method_saml_web_sso
));
319 mAuthTokenType
= chooseAuthTokenType(oAuthSupported
, samlWebSsoSupported
);
324 private String
chooseAuthTokenType(boolean oauth
, boolean saml
) {
326 return SAML_TOKEN_TYPE
;
328 return OAUTH_TOKEN_TYPE
;
330 return BASIC_TOKEN_TYPE
;
336 * Configures elements in the user interface under direct control of the Activity.
338 private void initOverallUi() {
340 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
341 boolean isWelcomeLinkVisible
= getResources().getBoolean(R
.bool
.show_welcome_link
);
343 String instructionsMessageText
= null
;
344 if (mAction
== ACTION_UPDATE_EXPIRED_TOKEN
) {
345 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
346 .equals(mAuthTokenType
)) {
347 instructionsMessageText
= getString(R
.string
.auth_expired_oauth_token_toast
);
349 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType())
350 .equals(mAuthTokenType
)) {
351 instructionsMessageText
= getString(R
.string
.auth_expired_saml_sso_token_toast
);
354 instructionsMessageText
= getString(R
.string
.auth_expired_basic_auth_toast
);
358 /// step 2 - set properties of UI elements (text, visibility, enabled...)
359 Button welcomeLink
= (Button
) findViewById(R
.id
.welcome_link
);
360 welcomeLink
.setVisibility(isWelcomeLinkVisible ? View
.VISIBLE
: View
.GONE
);
362 String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
364 TextView instructionsView
= (TextView
) findViewById(R
.id
.instructions_message
);
365 if (instructionsMessageText
!= null
) {
366 instructionsView
.setVisibility(View
.VISIBLE
);
367 instructionsView
.setText(instructionsMessageText
);
369 instructionsView
.setVisibility(View
.GONE
);
376 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
378 private void initServerPreFragment(Bundle savedInstanceState
) {
380 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
381 boolean isUrlInputAllowed
= getResources().getBoolean(R
.bool
.show_server_url_input
);
382 if (savedInstanceState
== null
) {
383 if (mAccount
!= null
) {
384 mServerInfo
.mBaseUrl
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_BASE_URL
);
385 // TODO do next in a setter for mBaseUrl
386 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
387 mServerInfo
.mVersion
= AccountUtils
.getServerVersion(mAccount
);
389 mServerInfo
.mBaseUrl
= getString(R
.string
.server_url
).trim();
390 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
393 mServerStatusText
= savedInstanceState
.getInt(KEY_SERVER_STATUS_TEXT
);
394 mServerStatusIcon
= savedInstanceState
.getInt(KEY_SERVER_STATUS_ICON
);
396 mServerIsValid
= savedInstanceState
.getBoolean(KEY_SERVER_VALID
);
397 mServerIsChecked
= savedInstanceState
.getBoolean(KEY_SERVER_CHECKED
);
400 mServerInfo
.mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
401 mServerInfo
.mBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
402 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
403 if (ocVersion
!= null
) {
404 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
406 mServerInfo
.mAuthMethod
= AuthenticationMethod
.valueOf(
407 savedInstanceState
.getString(KEY_SERVER_AUTH_METHOD
));
411 /// step 2 - set properties of UI elements (text, visibility, enabled...)
412 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
413 // Convert IDN to Unicode
414 mHostUrlInput
.setText(DisplayUtils
.convertIdn(mServerInfo
.mBaseUrl
, false
));
415 if (mAction
!= ACTION_CREATE
) {
416 /// lock things that should not change
417 mHostUrlInput
.setEnabled(false
);
418 mHostUrlInput
.setFocusable(false
);
420 if (isUrlInputAllowed
) {
421 mRefreshButton
= findViewById(R
.id
.embeddedRefreshButton
);
423 findViewById(R
.id
.hostUrlFrame
).setVisibility(View
.GONE
);
424 mRefreshButton
= findViewById(R
.id
.centeredRefreshButton
);
426 showRefreshButton(mServerIsChecked
&& !mServerIsValid
&&
427 mWaitingForOpId
> Integer
.MAX_VALUE
);
428 mServerStatusView
= (TextView
) findViewById(R
.id
.server_status_text
);
431 /// step 3 - bind some listeners and options
432 mHostUrlInput
.setImeOptions(EditorInfo
.IME_ACTION_NEXT
);
433 mHostUrlInput
.setOnEditorActionListener(this);
435 /// step 4 - create listeners that will be bound at onResume
436 mHostUrlInputWatcher
= new TextWatcher() {
439 public void afterTextChanged(Editable s
) {
440 if (mOkButton
.isEnabled() &&
441 !mServerInfo
.mBaseUrl
.equals(
442 normalizeUrl(s
.toString(), mServerInfo
.mIsSslConn
))) {
443 mOkButton
.setEnabled(false
);
448 public void beforeTextChanged(CharSequence s
, int start
, int count
, int after
) {
452 public void onTextChanged(CharSequence s
, int start
, int before
, int count
) {
453 if (mAuthStatusIcon
!= 0) {
454 Log_OC
.d(TAG
, "onTextChanged: hiding authentication status");
463 // TODO find out if this is really necessary, or if it can done in a different way
464 findViewById(R
.id
.scroll
).setOnTouchListener(new OnTouchListener() {
466 public boolean onTouch(View view
, MotionEvent event
) {
467 if (event
.getAction() == MotionEvent
.ACTION_DOWN
) {
469 AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(
470 MainApp
.getAccountType()
471 ).equals(mAuthTokenType
) &&
472 mHostUrlInput
.hasFocus()
482 /// step 4 - mark automatic check to be started when OperationsService is ready
483 mPendingAutoCheck
= (savedInstanceState
== null
&&
484 (mAction
!= ACTION_CREATE
|| !isUrlInputAllowed
));
490 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
492 private void initAuthorizationPreFragment(Bundle savedInstanceState
) {
494 /// step 0 - get UI elements in layout
495 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
496 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
497 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
498 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
499 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
500 mAuthStatusView
= (TextView
) findViewById(R
.id
.auth_status_text
);
502 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
503 String presetUserName
= null
;
504 boolean isPasswordExposed
= false
;
505 if (savedInstanceState
== null
) {
506 if (mAccount
!= null
) {
507 presetUserName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
511 isPasswordExposed
= savedInstanceState
.getBoolean(KEY_PASSWORD_EXPOSED
, false
);
512 mAuthStatusText
= savedInstanceState
.getInt(KEY_AUTH_STATUS_TEXT
);
513 mAuthStatusIcon
= savedInstanceState
.getInt(KEY_AUTH_STATUS_ICON
);
514 mAuthToken
= savedInstanceState
.getString(KEY_AUTH_TOKEN
);
517 /// step 2 - set properties of UI elements (text, visibility, enabled...)
518 mOAuth2Check
.setChecked(
519 AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
520 .equals(mAuthTokenType
));
521 if (presetUserName
!= null
) {
522 mUsernameInput
.setText(presetUserName
);
524 if (mAction
!= ACTION_CREATE
) {
525 mUsernameInput
.setEnabled(false
);
526 mUsernameInput
.setFocusable(false
);
528 mPasswordInput
.setText(""); // clean password to avoid social hacking
529 if (isPasswordExposed
) {
532 updateAuthenticationPreFragmentVisibility();
534 mOkButton
.setEnabled(mServerIsValid
);
537 /// step 3 - bind listeners
538 // bindings for password input field
539 mPasswordInput
.setOnFocusChangeListener(this);
540 mPasswordInput
.setImeOptions(EditorInfo
.IME_ACTION_DONE
);
541 mPasswordInput
.setOnEditorActionListener(this);
542 mPasswordInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
544 public boolean onDrawableTouch(final MotionEvent event
) {
545 if (event
.getAction() == MotionEvent
.ACTION_UP
) {
546 AuthenticatorActivity
.this.onViewPasswordClick();
556 * Changes the visibility of input elements depending on
557 * the current authorization method.
559 private void updateAuthenticationPreFragmentVisibility () {
560 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
561 equals(mAuthTokenType
)) {
562 // SAML-based web Single Sign On
563 mOAuth2Check
.setVisibility(View
.GONE
);
564 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
565 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
566 mUsernameInput
.setVisibility(View
.GONE
);
567 mPasswordInput
.setVisibility(View
.GONE
);
570 if (mAction
== ACTION_CREATE
&&
571 AUTH_OPTIONAL
.equals(getString(R
.string
.auth_method_oauth2
))) {
572 mOAuth2Check
.setVisibility(View
.VISIBLE
);
574 mOAuth2Check
.setVisibility(View
.GONE
);
577 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
578 equals(mAuthTokenType
)) {
579 // OAuth 2 authorization
581 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
582 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
583 mUsernameInput
.setVisibility(View
.GONE
);
584 mPasswordInput
.setVisibility(View
.GONE
);
587 // basic HTTP authorization
588 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
589 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
590 mUsernameInput
.setVisibility(View
.VISIBLE
);
591 mPasswordInput
.setVisibility(View
.VISIBLE
);
599 * Saves relevant state before {@link #onPause()}
601 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag,
602 * intended to defer the processing of the redirection caught in
603 * {@link #onNewIntent(Intent)} until {@link #onResume()}
605 * See {@link super#onSaveInstanceState(Bundle)}
608 protected void onSaveInstanceState(Bundle outState
) {
609 //Log_OC.wtf(TAG, "onSaveInstanceState init" );
610 super.onSaveInstanceState(outState
);
613 outState
.putString(KEY_AUTH_TOKEN_TYPE
, mAuthTokenType
);
614 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mWaitingForOpId
);
616 /// Server PRE-fragment state
617 outState
.putInt(KEY_SERVER_STATUS_TEXT
, mServerStatusText
);
618 outState
.putInt(KEY_SERVER_STATUS_ICON
, mServerStatusIcon
);
619 outState
.putBoolean(KEY_SERVER_CHECKED
, mServerIsChecked
);
620 outState
.putBoolean(KEY_SERVER_VALID
, mServerIsValid
);
621 outState
.putBoolean(KEY_IS_SSL_CONN
, mServerInfo
.mIsSslConn
);
622 outState
.putString(KEY_HOST_URL_TEXT
, mServerInfo
.mBaseUrl
);
623 if (mServerInfo
.mVersion
!= null
) {
624 outState
.putString(KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion());
626 outState
.putString(KEY_SERVER_AUTH_METHOD
, mServerInfo
.mAuthMethod
.name());
628 /// Authentication PRE-fragment state
629 outState
.putBoolean(KEY_PASSWORD_EXPOSED
, isPasswordVisible());
630 outState
.putInt(KEY_AUTH_STATUS_ICON
, mAuthStatusIcon
);
631 outState
.putInt(KEY_AUTH_STATUS_TEXT
, mAuthStatusText
);
632 outState
.putString(KEY_AUTH_TOKEN
, mAuthToken
);
635 outState
.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
, mIsFirstAuthAttempt
);
637 /// AsyncTask (User and password)
638 outState
.putString(KEY_USERNAME
, mUsernameInput
.getText().toString());
639 outState
.putString(KEY_PASSWORD
, mPasswordInput
.getText().toString());
641 if (mAsyncTask
!= null
) {
642 mAsyncTask
.cancel(true
);
643 outState
.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS
, true
);
645 outState
.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS
, false
);
649 //Log_OC.wtf(TAG, "onSaveInstanceState end" );
653 public void onRestoreInstanceState(Bundle savedInstanceState
) {
654 super.onRestoreInstanceState(savedInstanceState
);
657 boolean inProgress
= savedInstanceState
.getBoolean(KEY_ASYNC_TASK_IN_PROGRESS
);
659 String username
= savedInstanceState
.getString(KEY_USERNAME
);
660 String password
= savedInstanceState
.getString(KEY_PASSWORD
);
662 OwnCloudCredentials credentials
= null
;
663 if (BASIC_TOKEN_TYPE
.equals(mAuthTokenType
)) {
664 credentials
= OwnCloudCredentialsFactory
.newBasicCredentials(username
, password
);
666 } else if (OAUTH_TOKEN_TYPE
.equals(mAuthTokenType
)) {
667 credentials
= OwnCloudCredentialsFactory
.newBearerCredentials(mAuthToken
);
670 accessRootFolder(credentials
);
675 * The redirection triggered by the OAuth authentication server as response to the
676 * GET AUTHORIZATION request is caught here.
678 * To make this possible, this activity needs to be qualified with android:launchMode =
679 * "singleTask" in the AndroidManifest.xml file.
682 protected void onNewIntent (Intent intent
) {
683 Log_OC
.d(TAG
, "onNewIntent()");
684 Uri data
= intent
.getData();
685 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
686 mNewCapturedUriFromOAuth2Redirection
= data
;
692 * The redirection triggered by the OAuth authentication server as response to the
693 * GET AUTHORIZATION, and deferred in {@link #onNewIntent(Intent)}, is processed here.
696 protected void onResume() {
699 // bound here to avoid spurious changes triggered by Android on device rotations
700 mHostUrlInput
.setOnFocusChangeListener(this);
701 mHostUrlInput
.addTextChangedListener(mHostUrlInputWatcher
);
703 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
704 getOAuth2AccessTokenFromCapturedRedirection();
707 if (mOperationsServiceBinder
!= null
) {
708 doOnResumeAndBound();
715 protected void onPause() {
716 if (mOperationsServiceBinder
!= null
) {
717 mOperationsServiceBinder
.removeOperationListener(this);
720 mHostUrlInput
.removeTextChangedListener(mHostUrlInputWatcher
);
721 mHostUrlInput
.setOnFocusChangeListener(null
);
727 protected void onDestroy() {
729 mHostUrlInputWatcher
= null
;
731 if (mOperationsServiceConnection
!= null
) {
732 unbindService(mOperationsServiceConnection
);
733 mOperationsServiceBinder
= null
;
740 * Parses the redirection with the response to the GET AUTHORIZATION request to the
741 * oAuth server and requests for the access token (GET ACCESS TOKEN)
743 private void getOAuth2AccessTokenFromCapturedRedirection() {
744 /// Parse data from OAuth redirection
745 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
746 mNewCapturedUriFromOAuth2Redirection
= null
;
748 /// Showing the dialog with instructions for the user.
749 IndeterminateProgressDialog dialog
=
750 IndeterminateProgressDialog
.newInstance(R
.string
.auth_getting_authorization
, true
);
751 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
753 /// GET ACCESS TOKEN to the oAuth server
754 Intent getServerInfoIntent
= new Intent();
755 getServerInfoIntent
.setAction(OperationsService
.ACTION_OAUTH2_GET_ACCESS_TOKEN
);
757 getServerInfoIntent
.putExtra(
758 OperationsService
.EXTRA_SERVER_URL
,
759 mOAuthTokenEndpointText
.getText().toString().trim());
761 getServerInfoIntent
.putExtra(
762 OperationsService
.EXTRA_OAUTH2_QUERY_PARAMETERS
,
765 if (mOperationsServiceBinder
!= null
) {
766 //Log_OC.wtf(TAG, "getting access token..." );
767 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
774 * Handles the change of focus on the text inputs for the server URL and the password
776 public void onFocusChange(View view
, boolean hasFocus
) {
777 if (view
.getId() == R
.id
.hostUrlInput
) {
779 onUrlInputFocusLost();
782 showRefreshButton(false
);
785 } else if (view
.getId() == R
.id
.account_password
) {
786 onPasswordFocusChanged(hasFocus
);
792 * Handles changes in focus on the text input for the server URL.
794 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
795 * other field. The operation to check the existence of the server in the entered URL is
798 * When hasFocus: user 'comes back' to write again the server URL.
800 private void onUrlInputFocusLost() {
801 if (!mServerInfo
.mBaseUrl
.equals(
802 normalizeUrl(mHostUrlInput
.getText().toString(), mServerInfo
.mIsSslConn
))) {
803 // check server again only if the user changed something in the field
806 mOkButton
.setEnabled(mServerIsValid
);
807 showRefreshButton(!mServerIsValid
);
812 private void checkOcServer() {
813 String uri
= mHostUrlInput
.getText().toString().trim();
814 mServerIsValid
= false
;
815 mServerIsChecked
= false
;
816 mOkButton
.setEnabled(false
);
817 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
818 showRefreshButton(false
);
820 if (uri
.length() != 0) {
821 // Handle internationalized domain names
822 uri
= DisplayUtils
.convertIdn(uri
, true
);
824 mServerStatusText
= R
.string
.auth_testing_connection
;
825 mServerStatusIcon
= R
.drawable
.progress_small
;
828 Intent getServerInfoIntent
= new Intent();
829 getServerInfoIntent
.setAction(OperationsService
.ACTION_GET_SERVER_INFO
);
830 getServerInfoIntent
.putExtra(
831 OperationsService
.EXTRA_SERVER_URL
,
832 normalizeUrlSuffix(uri
)
834 if (mOperationsServiceBinder
!= null
) {
835 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
837 Log_OC
.wtf(TAG
, "Server check tried with OperationService unbound!" );
841 mServerStatusText
= 0;
842 mServerStatusIcon
= 0;
849 * Handles changes in focus on the text input for the password (basic authorization).
851 * When (hasFocus), the button to toggle password visibility is shown.
853 * When (!hasFocus), the button is made invisible and the password is hidden.
855 * @param hasFocus 'True' if focus is received, 'false' if is lost
857 private void onPasswordFocusChanged(boolean hasFocus
) {
859 showViewPasswordButton();
862 hidePasswordButton();
867 private void showViewPasswordButton() {
868 int drawable
= R
.drawable
.ic_view
;
869 if (isPasswordVisible()) {
870 drawable
= R
.drawable
.ic_hide
;
872 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable
, 0);
875 private boolean isPasswordVisible() {
876 return ((mPasswordInput
.getInputType() & InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) ==
877 InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
880 private void hidePasswordButton() {
881 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
884 private void showPassword() {
885 mPasswordInput
.setInputType(
886 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
888 showViewPasswordButton();
891 private void hidePassword() {
892 mPasswordInput
.setInputType(
893 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
895 showViewPasswordButton();
899 * Checks the credentials of the user in the root of the ownCloud server
900 * before creating a new local account.
902 * For basic authorization, a check of existence of the root folder is
905 * For OAuth, starts the flow to get an access token; the credentials test
906 * is postponed until it is available.
908 * IMPORTANT ENTRY POINT 4
910 public void onOkClick() {
911 // this check should be unnecessary
912 if (mServerInfo
.mVersion
== null
||
913 !mServerInfo
.mVersion
.isVersionValid() ||
914 mServerInfo
.mBaseUrl
== null
||
915 mServerInfo
.mBaseUrl
.length() == 0) {
916 mServerStatusIcon
= R
.drawable
.common_error
;
917 mServerStatusText
= R
.string
.auth_wtf_reenter_URL
;
919 mOkButton
.setEnabled(false
);
923 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
924 equals(mAuthTokenType
)) {
926 startOauthorization();
927 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
928 equals(mAuthTokenType
)) {
930 startSamlBasedFederatedSingleSignOnAuthorization();
932 checkBasicAuthorization();
938 * Tests the credentials entered by the user performing a check of existence on
939 * the root folder of the ownCloud server.
941 private void checkBasicAuthorization() {
942 /// get basic credentials entered by user
943 String username
= mUsernameInput
.getText().toString();
944 String password
= mPasswordInput
.getText().toString();
946 /// be gentle with the user
947 IndeterminateProgressDialog dialog
=
948 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
949 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
951 /// validate credentials accessing the root folder
952 OwnCloudCredentials credentials
= OwnCloudCredentialsFactory
.newBasicCredentials(username
,
954 accessRootFolder(credentials
);
957 private void accessRootFolder(OwnCloudCredentials credentials
) {
958 mAsyncTask
= new AuthenticatorAsyncTask(this);
959 Object
[] params
= { mServerInfo
.mBaseUrl
, credentials
};
960 mAsyncTask
.execute(params
);
965 * Starts the OAuth 'grant type' flow to get an access token, with
966 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
968 private void startOauthorization() {
969 // be gentle with the user
970 mAuthStatusIcon
= R
.drawable
.progress_small
;
971 mAuthStatusText
= R
.string
.oauth_login_connection
;
974 // GET AUTHORIZATION request
975 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
976 Uri
.Builder uriBuilder
= uri
.buildUpon();
977 uriBuilder
.appendQueryParameter(
978 OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
)
980 uriBuilder
.appendQueryParameter(
981 OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
)
983 uriBuilder
.appendQueryParameter(
984 OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
)
986 uriBuilder
.appendQueryParameter(
987 OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
)
989 uri
= uriBuilder
.build();
990 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
991 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
997 * Starts the Web Single Sign On flow to get access to the root folder
1000 private void startSamlBasedFederatedSingleSignOnAuthorization() {
1001 /// be gentle with the user
1002 mAuthStatusIcon
= R
.drawable
.progress_small
;
1003 mAuthStatusText
= R
.string
.auth_connecting_auth_server
;
1006 /// Show SAML-based SSO web dialog
1007 String targetUrl
= mServerInfo
.mBaseUrl
1008 + AccountUtils
.getWebdavPath(mServerInfo
.mVersion
, mAuthTokenType
);
1009 SamlWebViewDialog dialog
= SamlWebViewDialog
.newInstance(targetUrl
, targetUrl
);
1010 dialog
.show(getSupportFragmentManager(), SAML_DIALOG_TAG
);
1014 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
1016 * Dispatches the operation flow to the right method.
1019 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1021 if (operation
instanceof GetServerInfoOperation
) {
1022 if (operation
.hashCode() == mWaitingForOpId
) {
1023 onGetServerInfoFinish(result
);
1024 } // else nothing ; only the last check operation is considered;
1025 // multiple can be started if the user amends a URL quickly
1027 } else if (operation
instanceof OAuth2GetAccessToken
) {
1028 onGetOAuthAccessTokenFinish(result
);
1030 } else if (operation
instanceof GetRemoteUserNameOperation
) {
1031 onGetUserNameFinish(result
);
1036 private void onGetUserNameFinish(RemoteOperationResult result
) {
1037 mWaitingForOpId
= Long
.MAX_VALUE
;
1038 if (result
.isSuccess()) {
1039 boolean success
= false
;
1040 String username
= (String
) result
.getData().get(0);
1042 if ( mAction
== ACTION_CREATE
) {
1043 mUsernameInput
.setText(username
);
1044 success
= createAccount(result
);
1047 if (!mUsernameInput
.getText().toString().equals(username
)) {
1048 // fail - not a new account, but an existing one; disallow
1049 result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_THE_SAME
);
1051 updateAuthStatusIconAndText(result
);
1053 Log_OC
.d(TAG
, result
.getLogMessage());
1056 updateAccountAuthentication();
1059 } catch (AccountNotFoundException e
) {
1060 Log_OC
.e(TAG
, "Account " + mAccount
+ " was removed!", e
);
1061 Toast
.makeText(this, R
.string
.auth_account_does_not_exist
,
1062 Toast
.LENGTH_SHORT
).show();
1071 updateStatusIconFailUserName();
1073 Log_OC
.e(TAG
, "Access to user name failed: " + result
.getLogMessage());
1079 * Processes the result of the server check performed when the user finishes the enter of the
1082 * @param result Result of the check.
1084 private void onGetServerInfoFinish(RemoteOperationResult result
) {
1085 /// update activity state
1086 mServerIsChecked
= true
;
1087 mWaitingForOpId
= Long
.MAX_VALUE
;
1089 // update server status, but don't show it yet
1090 updateServerStatusIconAndText(result
);
1092 if (result
.isSuccess()) {
1094 // 1. connection succeeded, and we know if it's SSL or not
1095 // 2. server is installed
1096 // 3. we got the server version
1097 // 4. we got the authentication method required by the server
1098 mServerInfo
= (GetServerInfoOperation
.ServerInfo
) (result
.getData().get(0));
1100 if (!authSupported(mServerInfo
.mAuthMethod
)) {
1102 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1103 mServerIsValid
= false
;
1106 mServerIsValid
= true
;
1110 mServerIsValid
= false
;
1114 showRefreshButton(!mServerIsValid
);
1116 mOkButton
.setEnabled(mServerIsValid
);
1118 /// very special case (TODO: move to a common place for all the remote operations)
1119 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1120 showUntrustedCertDialog(result
);
1125 private boolean authSupported(AuthenticationMethod authMethod
) {
1126 return (( BASIC_TOKEN_TYPE
.equals(mAuthTokenType
) &&
1127 AuthenticationMethod
.BASIC_HTTP_AUTH
.equals(authMethod
) ) ||
1128 ( OAUTH_TOKEN_TYPE
.equals(mAuthTokenType
) &&
1129 AuthenticationMethod
.BEARER_TOKEN
.equals(authMethod
)) ||
1130 ( SAML_TOKEN_TYPE
.equals(mAuthTokenType
) &&
1131 AuthenticationMethod
.SAML_WEB_SSO
.equals(authMethod
))
1136 // TODO remove, if possible
1137 private String
normalizeUrl(String url
, boolean sslWhenUnprefixed
) {
1138 if (url
!= null
&& url
.length() > 0) {
1140 if (!url
.toLowerCase().startsWith("http://") &&
1141 !url
.toLowerCase().startsWith("https://")) {
1142 if (sslWhenUnprefixed
) {
1143 url
= "https://" + url
;
1145 url
= "http://" + url
;
1149 url
= normalizeUrlSuffix(url
);
1151 return (url
!= null ? url
: "");
1155 private String
normalizeUrlSuffix(String url
) {
1156 if (url
.endsWith("/")) {
1157 url
= url
.substring(0, url
.length() - 1);
1159 url
= trimUrlWebdav(url
);
1164 // TODO remove, if possible
1165 private String
trimUrlWebdav(String url
){
1166 if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_4_0_AND_LATER
)){
1167 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_4_0_AND_LATER
.length());
1174 * Chooses the right icon and text to show to the user for the received operation result.
1176 * @param result Result of a remote operation performed in this activity
1178 private void updateServerStatusIconAndText(RemoteOperationResult result
) {
1179 mServerStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1181 switch (result
.getCode()) {
1183 mServerStatusIcon
= R
.drawable
.ic_lock
;
1184 mServerStatusText
= R
.string
.auth_secure_connection
;
1189 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1190 mServerStatusText
= R
.string
.auth_connection_established
;
1191 mServerStatusIcon
= R
.drawable
.ic_ok
;
1193 mServerStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1194 mServerStatusIcon
= R
.drawable
.ic_lock_open
;
1198 case NO_NETWORK_CONNECTION
:
1199 mServerStatusIcon
= R
.drawable
.no_network
;
1200 mServerStatusText
= R
.string
.auth_no_net_conn_title
;
1203 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1204 mServerStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1206 case BAD_OC_VERSION
:
1207 mServerStatusText
= R
.string
.auth_bad_oc_version_title
;
1209 case WRONG_CONNECTION
:
1210 mServerStatusText
= R
.string
.auth_wrong_connection_title
;
1213 mServerStatusText
= R
.string
.auth_timeout_title
;
1215 case INCORRECT_ADDRESS
:
1216 mServerStatusText
= R
.string
.auth_incorrect_address_title
;
1219 mServerStatusText
= R
.string
.auth_ssl_general_error_title
;
1222 mServerStatusText
= R
.string
.auth_unauthorized
;
1224 case HOST_NOT_AVAILABLE
:
1225 mServerStatusText
= R
.string
.auth_unknown_host_title
;
1227 case INSTANCE_NOT_CONFIGURED
:
1228 mServerStatusText
= R
.string
.auth_not_configured_title
;
1230 case FILE_NOT_FOUND
:
1231 mServerStatusText
= R
.string
.auth_incorrect_path_title
;
1234 mServerStatusText
= R
.string
.auth_oauth_error
;
1236 case OAUTH2_ERROR_ACCESS_DENIED
:
1237 mServerStatusText
= R
.string
.auth_oauth_error_access_denied
;
1239 case UNHANDLED_HTTP_CODE
:
1241 mServerStatusText
= R
.string
.auth_unknown_error_title
;
1243 case OK_REDIRECT_TO_NON_SECURE_CONNECTION
:
1244 mServerStatusIcon
= R
.drawable
.ic_lock_open
;
1245 mServerStatusText
= R
.string
.auth_redirect_non_secure_connection_title
;
1248 mServerStatusText
= 0;
1249 mServerStatusIcon
= 0;
1255 * Chooses the right icon and text to show to the user for the received operation result.
1257 * @param result Result of a remote operation performed in this activity
1259 private void updateAuthStatusIconAndText(RemoteOperationResult result
) {
1260 mAuthStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1262 switch (result
.getCode()) {
1264 mAuthStatusIcon
= R
.drawable
.ic_lock
;
1265 mAuthStatusText
= R
.string
.auth_secure_connection
;
1270 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1271 mAuthStatusText
= R
.string
.auth_connection_established
;
1272 mAuthStatusIcon
= R
.drawable
.ic_ok
;
1274 mAuthStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1275 mAuthStatusIcon
= R
.drawable
.ic_lock_open
;
1279 case NO_NETWORK_CONNECTION
:
1280 mAuthStatusIcon
= R
.drawable
.no_network
;
1281 mAuthStatusText
= R
.string
.auth_no_net_conn_title
;
1284 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1285 mAuthStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1287 case BAD_OC_VERSION
:
1288 mAuthStatusText
= R
.string
.auth_bad_oc_version_title
;
1290 case WRONG_CONNECTION
:
1291 mAuthStatusText
= R
.string
.auth_wrong_connection_title
;
1294 mAuthStatusText
= R
.string
.auth_timeout_title
;
1296 case INCORRECT_ADDRESS
:
1297 mAuthStatusText
= R
.string
.auth_incorrect_address_title
;
1300 mAuthStatusText
= R
.string
.auth_ssl_general_error_title
;
1303 mAuthStatusText
= R
.string
.auth_unauthorized
;
1305 case HOST_NOT_AVAILABLE
:
1306 mAuthStatusText
= R
.string
.auth_unknown_host_title
;
1308 case INSTANCE_NOT_CONFIGURED
:
1309 mAuthStatusText
= R
.string
.auth_not_configured_title
;
1311 case FILE_NOT_FOUND
:
1312 mAuthStatusText
= R
.string
.auth_incorrect_path_title
;
1315 mAuthStatusText
= R
.string
.auth_oauth_error
;
1317 case OAUTH2_ERROR_ACCESS_DENIED
:
1318 mAuthStatusText
= R
.string
.auth_oauth_error_access_denied
;
1320 case ACCOUNT_NOT_NEW
:
1321 mAuthStatusText
= R
.string
.auth_account_not_new
;
1323 case ACCOUNT_NOT_THE_SAME
:
1324 mAuthStatusText
= R
.string
.auth_account_not_the_same
;
1326 case UNHANDLED_HTTP_CODE
:
1328 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
1331 mAuthStatusText
= 0;
1332 mAuthStatusIcon
= 0;
1337 private void updateStatusIconFailUserName(){
1338 mAuthStatusIcon
= R
.drawable
.common_error
;
1339 mAuthStatusText
= R
.string
.auth_fail_get_user_name
;
1342 private void updateServerStatusIconNoRegularAuth(){
1343 mServerStatusIcon
= R
.drawable
.common_error
;
1344 mServerStatusText
= R
.string
.auth_can_not_auth_against_server
;
1348 * Processes the result of the request for and access token send
1349 * to an OAuth authorization server.
1351 * @param result Result of the operation.
1353 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result
) {
1354 mWaitingForOpId
= Long
.MAX_VALUE
;
1355 dismissDialog(WAIT_DIALOG_TAG
);
1357 if (result
.isSuccess()) {
1358 /// be gentle with the user
1359 IndeterminateProgressDialog dialog
=
1360 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
1361 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
1363 /// time to test the retrieved access token on the ownCloud server
1364 @SuppressWarnings("unchecked")
1365 Map
<String
, String
> tokens
= (Map
<String
, String
>)(result
.getData().get(0));
1366 mAuthToken
= tokens
.get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
1367 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mAuthToken
);
1369 /// validate token accessing to root folder / getting session
1370 OwnCloudCredentials credentials
= OwnCloudCredentialsFactory
.newBearerCredentials(
1372 accessRootFolder(credentials
);
1375 updateAuthStatusIconAndText(result
);
1377 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1383 * Processes the result of the access check performed to try the user credentials.
1385 * Creates a new account through the AccountManager.
1387 * @param result Result of the operation.
1390 public void onAuthenticatorTaskCallback(RemoteOperationResult result
) {
1391 mWaitingForOpId
= Long
.MAX_VALUE
;
1392 dismissDialog(WAIT_DIALOG_TAG
);
1394 if (result
.isSuccess()) {
1395 Log_OC
.d(TAG
, "Successful access - time to save the account");
1397 boolean success
= false
;
1399 if (mAction
== ACTION_CREATE
) {
1400 success
= createAccount(result
);
1404 updateAccountAuthentication();
1407 } catch (AccountNotFoundException e
) {
1408 Log_OC
.e(TAG
, "Account " + mAccount
+ " was removed!", e
);
1409 Toast
.makeText(this, R
.string
.auth_account_does_not_exist
,
1410 Toast
.LENGTH_SHORT
).show();
1419 } else if (result
.isServerFail() || result
.isException()) {
1420 /// server errors or exceptions in authorization take to requiring a new check of
1422 mServerIsChecked
= true
;
1423 mServerIsValid
= false
;
1424 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
1426 // update status icon and text
1427 updateServerStatusIconAndText(result
);
1429 mAuthStatusIcon
= 0;
1430 mAuthStatusText
= 0;
1433 // update input controls state
1434 showRefreshButton(true
);
1435 mOkButton
.setEnabled(false
);
1437 // very special case (TODO: move to a common place for all the remote operations)
1438 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1439 showUntrustedCertDialog(result
);
1442 } else { // authorization fail due to client side - probably wrong credentials
1443 updateAuthStatusIconAndText(result
);
1445 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1453 * Updates the authentication token.
1455 * Sets the proper response so that the AccountAuthenticator that started this activity
1456 * saves a new authorization token for mAccount.
1458 * Kills the session kept by OwnCloudClientManager so that a new one will created with
1459 * the new credentials when needed.
1461 private void updateAccountAuthentication() throws AccountNotFoundException
{
1463 Bundle response
= new Bundle();
1464 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1465 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
1467 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
1468 equals(mAuthTokenType
)) {
1469 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1470 // the next line is necessary, notifications are calling directly to the
1471 // AuthenticatorActivity to update, without AccountManager intervention
1472 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1474 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1475 equals(mAuthTokenType
)) {
1477 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1478 // the next line is necessary; by now, notifications are calling directly to the
1479 // AuthenticatorActivity to update, without AccountManager intervention
1480 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1483 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
1484 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
1486 setAccountAuthenticatorResult(response
);
1492 * Creates a new account through the Account Authenticator that started this activity.
1494 * This makes the account permanent.
1496 * TODO Decide how to name the OAuth accounts
1498 private boolean createAccount(RemoteOperationResult authResult
) {
1499 /// create and save new ownCloud account
1500 boolean isOAuth
= AccountTypeUtils
.
1501 getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
);
1502 boolean isSaml
= AccountTypeUtils
.
1503 getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
);
1505 String lastPermanentLocation
= authResult
.getLastPermanentLocation();
1506 if (lastPermanentLocation
!= null
) {
1507 mServerInfo
.mBaseUrl
= AccountUtils
.trimWebdavSuffix(lastPermanentLocation
);
1510 Uri uri
= Uri
.parse(mServerInfo
.mBaseUrl
);
1511 String username
= mUsernameInput
.getText().toString().trim();
1513 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1515 String accountName
= com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.
1516 buildAccountName(uri
, username
);
1517 Account newAccount
= new Account(accountName
, MainApp
.getAccountType());
1518 if (AccountUtils
.exists(newAccount
, getApplicationContext())) {
1519 // fail - not a new account, but an existing one; disallow
1520 RemoteOperationResult result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_NEW
);
1521 updateAuthStatusIconAndText(result
);
1523 Log_OC
.d(TAG
, result
.getLogMessage());
1527 mAccount
= newAccount
;
1529 if (isOAuth
|| isSaml
) {
1530 // with external authorizations, the password is never input in the app
1531 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
);
1533 mAccountMgr
.addAccountExplicitly(
1534 mAccount
, mPasswordInput
.getText().toString(), null
1538 // include account version with the new account
1539 mAccountMgr
.setUserData(
1541 Constants
.KEY_OC_ACCOUNT_VERSION
,
1542 Integer
.toString(AccountUtils
.ACCOUNT_VERSION
)
1545 /// add the new account as default in preferences, if there is none already
1546 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1547 if (defaultAccount
== null
) {
1548 SharedPreferences
.Editor editor
= PreferenceManager
1549 .getDefaultSharedPreferences(this).edit();
1550 editor
.putString("select_oc_account", accountName
);
1554 /// prepare result to return to the Authenticator
1555 // TODO check again what the Authenticator makes with it; probably has the same
1556 // effect as addAccountExplicitly, but it's not well done
1557 final Intent intent
= new Intent();
1558 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, MainApp
.getAccountType());
1559 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1560 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1561 if (isOAuth
|| isSaml
) {
1562 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1564 /// add user data to the new account; TODO probably can be done in the last parameter
1565 // addAccountExplicitly, or in KEY_USERDATA
1566 mAccountMgr
.setUserData(
1567 mAccount
, Constants
.KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion()
1569 mAccountMgr
.setUserData(
1570 mAccount
, Constants
.KEY_OC_BASE_URL
, mServerInfo
.mBaseUrl
1574 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
, "TRUE");
1575 } else if (isOAuth
) {
1576 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
, "TRUE");
1579 setAccountAuthenticatorResult(intent
.getExtras());
1580 setResult(RESULT_OK
, intent
);
1588 * Starts and activity to open the 'new account' page in the ownCloud web site
1590 * @param view 'Account register' button
1592 public void onRegisterClick(View view
) {
1593 Intent register
= new Intent(
1594 Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.welcome_link_url
))
1596 setResult(RESULT_CANCELED
);
1597 startActivity(register
);
1602 * Updates the content and visibility state of the icon and text associated
1603 * to the last check on the ownCloud server.
1606 private void showServerStatus() {
1607 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1608 mServerStatusView
.setVisibility(View
.INVISIBLE
);
1611 mServerStatusView
.setText(mServerStatusText
);
1612 mServerStatusView
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1613 mServerStatusView
.setVisibility(View
.VISIBLE
);
1620 * Updates the content and visibility state of the icon and text associated
1621 * to the interactions with the OAuth authorization server.
1623 private void showAuthStatus() {
1624 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1625 mAuthStatusView
.setVisibility(View
.INVISIBLE
);
1628 mAuthStatusView
.setText(mAuthStatusText
);
1629 mAuthStatusView
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1630 mAuthStatusView
.setVisibility(View
.VISIBLE
);
1635 private void showRefreshButton (boolean show
) {
1637 mRefreshButton
.setVisibility(View
.VISIBLE
);
1639 mRefreshButton
.setVisibility(View
.GONE
);
1644 * Called when the eye icon in the password field is clicked.
1646 * Toggles the visibility of the password in the field.
1648 public void onViewPasswordClick() {
1649 int selectionStart
= mPasswordInput
.getSelectionStart();
1650 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1651 if (isPasswordVisible()) {
1656 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1661 * Called when the checkbox for OAuth authorization is clicked.
1663 * Hides or shows the input fields for user & password.
1665 * @param view 'View password' 'button'
1667 public void onCheckClick(View view
) {
1668 CheckBox oAuth2Check
= (CheckBox
)view
;
1669 if (oAuth2Check
.isChecked()) {
1670 mAuthTokenType
= OAUTH_TOKEN_TYPE
;
1672 mAuthTokenType
= BASIC_TOKEN_TYPE
;
1674 updateAuthenticationPreFragmentVisibility();
1679 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1681 * Used to trigger the authentication check when the user presses 'enter' after writing the
1682 * password, or to throw the server test when the only field on screen is the URL input field.
1685 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1686 if (actionId
== EditorInfo
.IME_ACTION_DONE
&& inputField
!= null
&&
1687 inputField
.equals(mPasswordInput
)) {
1688 if (mOkButton
.isEnabled()) {
1689 mOkButton
.performClick();
1692 } else if (actionId
== EditorInfo
.IME_ACTION_NEXT
&& inputField
!= null
&&
1693 inputField
.equals(mHostUrlInput
)) {
1694 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1695 equals(mAuthTokenType
)) {
1699 return false
; // always return false to grant that the software keyboard is hidden anyway
1703 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1705 private int fuzz
= 75;
1711 public boolean onTouch(View view
, MotionEvent event
) {
1712 Drawable rightDrawable
= null
;
1713 if (view
instanceof TextView
) {
1714 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1715 if (drawables
.length
> 2) {
1716 rightDrawable
= drawables
[2];
1719 if (rightDrawable
!= null
) {
1720 final int x
= (int) event
.getX();
1721 final int y
= (int) event
.getY();
1722 final Rect bounds
= rightDrawable
.getBounds();
1723 if ( x
>= (view
.getRight() - bounds
.width() - fuzz
) &&
1724 x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
) &&
1725 y
>= (view
.getPaddingTop() - fuzz
) &&
1726 y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1728 return onDrawableTouch(event
);
1734 public abstract boolean onDrawableTouch(final MotionEvent event
);
1738 private void getRemoteUserNameOperation(String sessionCookie
) {
1740 Intent getUserNameIntent
= new Intent();
1741 getUserNameIntent
.setAction(OperationsService
.ACTION_GET_USER_NAME
);
1742 getUserNameIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
1743 getUserNameIntent
.putExtra(OperationsService
.EXTRA_COOKIE
, sessionCookie
);
1745 if (mOperationsServiceBinder
!= null
) {
1746 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getUserNameIntent
);
1752 public void onSsoFinished(String sessionCookie
) {
1753 if (sessionCookie
!= null
&& sessionCookie
.length() > 0) {
1754 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1755 mAuthToken
= sessionCookie
;
1756 getRemoteUserNameOperation(sessionCookie
);
1757 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1758 if (fd
!= null
&& fd
instanceof DialogFragment
) {
1759 Dialog d
= ((DialogFragment
)fd
).getDialog();
1760 if (d
!= null
&& d
.isShowing()) {
1767 Log_OC
.d(TAG
, "SSO failed");
1773 public boolean onTouchEvent(MotionEvent event
) {
1774 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1775 equals(mAuthTokenType
) &&
1776 mHostUrlInput
.hasFocus() && event
.getAction() == MotionEvent
.ACTION_DOWN
) {
1779 return super.onTouchEvent(event
);
1784 * Show untrusted cert dialog
1786 public void showUntrustedCertDialog(
1787 X509Certificate x509Certificate
, SslError error
, SslErrorHandler handler
1789 // Show a dialog with the certificate info
1790 SslUntrustedCertDialog dialog
;
1791 if (x509Certificate
== null
) {
1792 dialog
= SslUntrustedCertDialog
.newInstanceForEmptySslError(error
, handler
);
1794 dialog
= SslUntrustedCertDialog
.
1795 newInstanceForFullSslError(x509Certificate
, error
, handler
);
1797 FragmentManager fm
= getSupportFragmentManager();
1798 FragmentTransaction ft
= fm
.beginTransaction();
1799 ft
.addToBackStack(null
);
1800 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1805 * Show untrusted cert dialog
1807 private void showUntrustedCertDialog(RemoteOperationResult result
) {
1808 // Show a dialog with the certificate info
1809 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.
1810 newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1811 FragmentManager fm
= getSupportFragmentManager();
1812 FragmentTransaction ft
= fm
.beginTransaction();
1813 ft
.addToBackStack(null
);
1814 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1819 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1821 public void onSavedCertificate() {
1822 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1824 // if SAML dialog is not shown,
1825 // the SslDialog was shown due to an SSL error in the server check
1831 * Called from SslValidatorDialog when a new server certificate could not be saved
1832 * when the user requested it.
1835 public void onFailedSavingCertificate() {
1836 dismissDialog(SAML_DIALOG_TAG
);
1837 Toast
.makeText(this, R
.string
.ssl_validator_not_saved
, Toast
.LENGTH_LONG
).show();
1841 public void onCancelCertificate() {
1842 dismissDialog(SAML_DIALOG_TAG
);
1846 private void doOnResumeAndBound() {
1847 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1848 mOperationsServiceBinder
.addOperationListener(AuthenticatorActivity
.this, mHandler
);
1849 if (mWaitingForOpId
<= Integer
.MAX_VALUE
) {
1850 mOperationsServiceBinder
.dispatchResultIfFinished((int)mWaitingForOpId
, this);
1853 if (mPendingAutoCheck
) {
1859 private void dismissDialog(String dialogTag
){
1860 Fragment frag
= getSupportFragmentManager().findFragmentByTag(dialogTag
);
1861 if (frag
!= null
&& frag
instanceof DialogFragment
) {
1862 DialogFragment dialog
= (DialogFragment
) frag
;
1869 * Implements callback methods for service binding.
1871 private class OperationsServiceConnection
implements ServiceConnection
{
1874 public void onServiceConnected(ComponentName component
, IBinder service
) {
1875 if (component
.equals(
1876 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1878 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
1880 doOnResumeAndBound();
1887 public void onServiceDisconnected(ComponentName component
) {
1888 if (component
.equals(
1889 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1891 Log_OC
.e(TAG
, "Operations service crashed");
1892 mOperationsServiceBinder
= null
;
1899 * Create and show dialog for request authentication to the user
1900 * @param webView Web view to emebd into the authentication dialog.
1901 * @param handler Object responsible for catching and recovering HTTP authentication fails.
1903 public void createAuthenticationDialog(WebView webView
, HttpAuthHandler handler
) {
1905 // Show a dialog with the certificate info
1906 CredentialsDialogFragment dialog
=
1907 CredentialsDialogFragment
.newInstanceForCredentials(webView
, handler
);
1908 FragmentManager fm
= getSupportFragmentManager();
1909 FragmentTransaction ft
= fm
.beginTransaction();
1910 ft
.addToBackStack(null
);
1911 dialog
.setCancelable(false
);
1912 dialog
.show(ft
, CREDENTIALS_DIALOG_TAG
);
1914 if (!mIsFirstAuthAttempt
) {
1916 getApplicationContext(),
1917 getText(R
.string
.saml_authentication_wrong_pass
),
1921 mIsFirstAuthAttempt
= false
;
1926 * For retrieving the clicking on authentication cancel button
1928 public void doNegativeAuthenticatioDialogClick(){
1929 mIsFirstAuthAttempt
= true
;