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 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(
192 MainApp
.getAccountType());
193 private final String OAUTH_TOKEN_TYPE
= AccountTypeUtils
.getAuthTokenTypeAccessToken(
194 MainApp
.getAccountType());
195 private final String SAML_TOKEN_TYPE
=
196 AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
202 * IMPORTANT ENTRY POINT 1: activity is shown to the user
205 protected void onCreate(Bundle savedInstanceState
) {
206 //Log_OC.wtf(TAG, "onCreate init");
207 super.onCreate(savedInstanceState
);
209 // Workaround, for fixing a problem with Android Library Suppor v7 19
210 //getWindow().requestFeature(Window.FEATURE_NO_TITLE);
211 if (getSupportActionBar() != null
) {
212 getSupportActionBar().hide();
214 getSupportActionBar().setDisplayHomeAsUpEnabled(false
);
215 getSupportActionBar().setDisplayShowHomeEnabled(false
);
216 getSupportActionBar().setDisplayShowTitleEnabled(false
);
219 mIsFirstAuthAttempt
= true
;
221 // bind to Operations Service
222 mOperationsServiceConnection
= new OperationsServiceConnection();
223 if (!bindService(new Intent(this, OperationsService
.class),
224 mOperationsServiceConnection
,
225 Context
.BIND_AUTO_CREATE
)) {
227 R
.string
.error_cant_bind_to_operations_service
,
233 /// init activity state
234 mAccountMgr
= AccountManager
.get(this);
235 mNewCapturedUriFromOAuth2Redirection
= null
;
238 mAction
= getIntent().getByteExtra(EXTRA_ACTION
, ACTION_CREATE
);
239 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
240 if (savedInstanceState
== null
) {
243 mAuthTokenType
= savedInstanceState
.getString(KEY_AUTH_TOKEN_TYPE
);
244 mWaitingForOpId
= savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
);
245 mIsFirstAuthAttempt
= savedInstanceState
.getBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
);
248 /// load user interface
249 setContentView(R
.layout
.account_setup
);
251 /// initialize general UI elements
254 mOkButton
= findViewById(R
.id
.buttonOK
);
255 mOkButton
.setOnClickListener(new View
.OnClickListener() {
258 public void onClick(View v
) {
263 findViewById(R
.id
.centeredRefreshButton
).setOnClickListener(new View
.OnClickListener() {
266 public void onClick(View v
) {
271 findViewById(R
.id
.embeddedRefreshButton
).setOnClickListener(new View
.OnClickListener() {
274 public void onClick(View v
) {
280 /// initialize block to be moved to single Fragment to check server and get info about it
281 initServerPreFragment(savedInstanceState
);
283 /// initialize block to be moved to single Fragment to retrieve and validate credentials
284 initAuthorizationPreFragment(savedInstanceState
);
286 //Log_OC.wtf(TAG, "onCreate end");
289 private void initAuthTokenType() {
291 getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
292 if (mAuthTokenType
== null
) {
293 if (mAccount
!= null
) {
294 boolean oAuthRequired
=
295 (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
) != null
);
296 boolean samlWebSsoRequired
= (
297 mAccountMgr
.getUserData(
298 mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
301 mAuthTokenType
= chooseAuthTokenType(oAuthRequired
, samlWebSsoRequired
);
304 boolean oAuthSupported
= AUTH_ON
.equals(getString(R
.string
.auth_method_oauth2
));
305 boolean samlWebSsoSupported
=
306 AUTH_ON
.equals(getString(R
.string
.auth_method_saml_web_sso
));
307 mAuthTokenType
= chooseAuthTokenType(oAuthSupported
, samlWebSsoSupported
);
312 private String
chooseAuthTokenType(boolean oauth
, boolean saml
) {
314 return SAML_TOKEN_TYPE
;
316 return OAUTH_TOKEN_TYPE
;
318 return BASIC_TOKEN_TYPE
;
324 * Configures elements in the user interface under direct control of the Activity.
326 private void initOverallUi() {
328 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
329 boolean isWelcomeLinkVisible
= getResources().getBoolean(R
.bool
.show_welcome_link
);
331 String instructionsMessageText
= null
;
332 if (mAction
== ACTION_UPDATE_EXPIRED_TOKEN
) {
333 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
334 .equals(mAuthTokenType
)) {
335 instructionsMessageText
= getString(R
.string
.auth_expired_oauth_token_toast
);
337 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType())
338 .equals(mAuthTokenType
)) {
339 instructionsMessageText
= getString(R
.string
.auth_expired_saml_sso_token_toast
);
342 instructionsMessageText
= getString(R
.string
.auth_expired_basic_auth_toast
);
346 /// step 2 - set properties of UI elements (text, visibility, enabled...)
347 Button welcomeLink
= (Button
) findViewById(R
.id
.welcome_link
);
348 welcomeLink
.setVisibility(isWelcomeLinkVisible ? View
.VISIBLE
: View
.GONE
);
350 String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
352 TextView instructionsView
= (TextView
) findViewById(R
.id
.instructions_message
);
353 if (instructionsMessageText
!= null
) {
354 instructionsView
.setVisibility(View
.VISIBLE
);
355 instructionsView
.setText(instructionsMessageText
);
357 instructionsView
.setVisibility(View
.GONE
);
364 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
366 private void initServerPreFragment(Bundle savedInstanceState
) {
368 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
369 boolean isUrlInputAllowed
= getResources().getBoolean(R
.bool
.show_server_url_input
);
370 if (savedInstanceState
== null
) {
371 if (mAccount
!= null
) {
372 mServerInfo
.mBaseUrl
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_BASE_URL
);
373 // TODO do next in a setter for mBaseUrl
374 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
375 mServerInfo
.mVersion
= AccountUtils
.getServerVersion(mAccount
);
377 mServerInfo
.mBaseUrl
= getString(R
.string
.server_url
).trim();
378 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
381 mServerStatusText
= savedInstanceState
.getInt(KEY_SERVER_STATUS_TEXT
);
382 mServerStatusIcon
= savedInstanceState
.getInt(KEY_SERVER_STATUS_ICON
);
384 mServerIsValid
= savedInstanceState
.getBoolean(KEY_SERVER_VALID
);
385 mServerIsChecked
= savedInstanceState
.getBoolean(KEY_SERVER_CHECKED
);
388 mServerInfo
.mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
389 mServerInfo
.mBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
390 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
391 if (ocVersion
!= null
) {
392 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
394 mServerInfo
.mAuthMethod
= AuthenticationMethod
.valueOf(
395 savedInstanceState
.getString(KEY_SERVER_AUTH_METHOD
));
399 /// step 2 - set properties of UI elements (text, visibility, enabled...)
400 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
401 // Convert IDN to Unicode
402 mHostUrlInput
.setText(DisplayUtils
.convertIdn(mServerInfo
.mBaseUrl
, false
));
403 if (mAction
!= ACTION_CREATE
) {
404 /// lock things that should not change
405 mHostUrlInput
.setEnabled(false
);
406 mHostUrlInput
.setFocusable(false
);
408 if (isUrlInputAllowed
) {
409 mRefreshButton
= findViewById(R
.id
.embeddedRefreshButton
);
411 findViewById(R
.id
.hostUrlFrame
).setVisibility(View
.GONE
);
412 mRefreshButton
= findViewById(R
.id
.centeredRefreshButton
);
414 showRefreshButton(mServerIsChecked
&& !mServerIsValid
&&
415 mWaitingForOpId
> Integer
.MAX_VALUE
);
416 mServerStatusView
= (TextView
) findViewById(R
.id
.server_status_text
);
419 /// step 3 - bind some listeners and options
420 mHostUrlInput
.setImeOptions(EditorInfo
.IME_ACTION_NEXT
);
421 mHostUrlInput
.setOnEditorActionListener(this);
423 /// step 4 - create listeners that will be bound at onResume
424 mHostUrlInputWatcher
= new TextWatcher() {
427 public void afterTextChanged(Editable s
) {
428 if (mOkButton
.isEnabled() &&
429 !mServerInfo
.mBaseUrl
.equals(
430 normalizeUrl(s
.toString(), mServerInfo
.mIsSslConn
))) {
431 mOkButton
.setEnabled(false
);
436 public void beforeTextChanged(CharSequence s
, int start
, int count
, int after
) {
440 public void onTextChanged(CharSequence s
, int start
, int before
, int count
) {
441 if (mAuthStatusIcon
!= 0) {
442 Log_OC
.d(TAG
, "onTextChanged: hiding authentication status");
451 // TODO find out if this is really necessary, or if it can done in a different way
452 findViewById(R
.id
.scroll
).setOnTouchListener(new OnTouchListener() {
454 public boolean onTouch(View view
, MotionEvent event
) {
455 if (event
.getAction() == MotionEvent
.ACTION_DOWN
) {
457 AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(
458 MainApp
.getAccountType()
459 ).equals(mAuthTokenType
) &&
460 mHostUrlInput
.hasFocus()
470 /// step 4 - mark automatic check to be started when OperationsService is ready
471 mPendingAutoCheck
= (savedInstanceState
== null
&&
472 (mAction
!= ACTION_CREATE
|| !isUrlInputAllowed
));
478 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
480 private void initAuthorizationPreFragment(Bundle savedInstanceState
) {
482 /// step 0 - get UI elements in layout
483 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
484 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
485 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
486 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
487 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
488 mAuthStatusView
= (TextView
) findViewById(R
.id
.auth_status_text
);
490 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
491 String presetUserName
= null
;
492 boolean isPasswordExposed
= false
;
493 if (savedInstanceState
== null
) {
494 if (mAccount
!= null
) {
495 presetUserName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
499 isPasswordExposed
= savedInstanceState
.getBoolean(KEY_PASSWORD_EXPOSED
, false
);
500 mAuthStatusText
= savedInstanceState
.getInt(KEY_AUTH_STATUS_TEXT
);
501 mAuthStatusIcon
= savedInstanceState
.getInt(KEY_AUTH_STATUS_ICON
);
502 mAuthToken
= savedInstanceState
.getString(KEY_AUTH_TOKEN
);
505 /// step 2 - set properties of UI elements (text, visibility, enabled...)
506 mOAuth2Check
.setChecked(
507 AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
508 .equals(mAuthTokenType
));
509 if (presetUserName
!= null
) {
510 mUsernameInput
.setText(presetUserName
);
512 if (mAction
!= ACTION_CREATE
) {
513 mUsernameInput
.setEnabled(false
);
514 mUsernameInput
.setFocusable(false
);
516 mPasswordInput
.setText(""); // clean password to avoid social hacking
517 if (isPasswordExposed
) {
520 updateAuthenticationPreFragmentVisibility();
522 mOkButton
.setEnabled(mServerIsValid
);
525 /// step 3 - bind listeners
526 // bindings for password input field
527 mPasswordInput
.setOnFocusChangeListener(this);
528 mPasswordInput
.setImeOptions(EditorInfo
.IME_ACTION_DONE
);
529 mPasswordInput
.setOnEditorActionListener(this);
530 mPasswordInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
532 public boolean onDrawableTouch(final MotionEvent event
) {
533 if (event
.getAction() == MotionEvent
.ACTION_UP
) {
534 AuthenticatorActivity
.this.onViewPasswordClick();
544 * Changes the visibility of input elements depending on
545 * the current authorization method.
547 private void updateAuthenticationPreFragmentVisibility () {
548 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
549 equals(mAuthTokenType
)) {
550 // SAML-based web Single Sign On
551 mOAuth2Check
.setVisibility(View
.GONE
);
552 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
553 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
554 mUsernameInput
.setVisibility(View
.GONE
);
555 mPasswordInput
.setVisibility(View
.GONE
);
558 if (mAction
== ACTION_CREATE
&&
559 AUTH_OPTIONAL
.equals(getString(R
.string
.auth_method_oauth2
))) {
560 mOAuth2Check
.setVisibility(View
.VISIBLE
);
562 mOAuth2Check
.setVisibility(View
.GONE
);
565 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
566 equals(mAuthTokenType
)) {
567 // OAuth 2 authorization
569 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
570 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
571 mUsernameInput
.setVisibility(View
.GONE
);
572 mPasswordInput
.setVisibility(View
.GONE
);
575 // basic HTTP authorization
576 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
577 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
578 mUsernameInput
.setVisibility(View
.VISIBLE
);
579 mPasswordInput
.setVisibility(View
.VISIBLE
);
587 * Saves relevant state before {@link #onPause()}
589 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag,
590 * intended to defer the processing of the redirection caught in
591 * {@link #onNewIntent(Intent)} until {@link #onResume()}
593 * See {@link super#onSaveInstanceState(Bundle)}
596 protected void onSaveInstanceState(Bundle outState
) {
597 //Log_OC.wtf(TAG, "onSaveInstanceState init" );
598 super.onSaveInstanceState(outState
);
601 outState
.putString(KEY_AUTH_TOKEN_TYPE
, mAuthTokenType
);
602 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mWaitingForOpId
);
604 /// Server PRE-fragment state
605 outState
.putInt(KEY_SERVER_STATUS_TEXT
, mServerStatusText
);
606 outState
.putInt(KEY_SERVER_STATUS_ICON
, mServerStatusIcon
);
607 outState
.putBoolean(KEY_SERVER_CHECKED
, mServerIsChecked
);
608 outState
.putBoolean(KEY_SERVER_VALID
, mServerIsValid
);
609 outState
.putBoolean(KEY_IS_SSL_CONN
, mServerInfo
.mIsSslConn
);
610 outState
.putString(KEY_HOST_URL_TEXT
, mServerInfo
.mBaseUrl
);
611 if (mServerInfo
.mVersion
!= null
) {
612 outState
.putString(KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion());
614 outState
.putString(KEY_SERVER_AUTH_METHOD
, mServerInfo
.mAuthMethod
.name());
616 /// Authentication PRE-fragment state
617 outState
.putBoolean(KEY_PASSWORD_EXPOSED
, isPasswordVisible());
618 outState
.putInt(KEY_AUTH_STATUS_ICON
, mAuthStatusIcon
);
619 outState
.putInt(KEY_AUTH_STATUS_TEXT
, mAuthStatusText
);
620 outState
.putString(KEY_AUTH_TOKEN
, mAuthToken
);
623 outState
.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
, mIsFirstAuthAttempt
);
625 /// AsyncTask (User and password)
626 outState
.putString(KEY_USERNAME
, mUsernameInput
.getText().toString());
627 outState
.putString(KEY_PASSWORD
, mPasswordInput
.getText().toString());
629 if (mAsyncTask
!= null
) {
630 mAsyncTask
.cancel(true
);
631 outState
.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS
, true
);
633 outState
.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS
, false
);
637 //Log_OC.wtf(TAG, "onSaveInstanceState end" );
641 public void onRestoreInstanceState(Bundle savedInstanceState
) {
642 super.onRestoreInstanceState(savedInstanceState
);
645 boolean inProgress
= savedInstanceState
.getBoolean(KEY_ASYNC_TASK_IN_PROGRESS
);
647 String username
= savedInstanceState
.getString(KEY_USERNAME
);
648 String password
= savedInstanceState
.getString(KEY_PASSWORD
);
650 OwnCloudCredentials credentials
= null
;
651 if (BASIC_TOKEN_TYPE
.equals(mAuthTokenType
)) {
652 credentials
= OwnCloudCredentialsFactory
.newBasicCredentials(username
, password
);
654 } else if (OAUTH_TOKEN_TYPE
.equals(mAuthTokenType
)) {
655 credentials
= OwnCloudCredentialsFactory
.newBearerCredentials(mAuthToken
);
658 accessRootFolder(credentials
);
663 * The redirection triggered by the OAuth authentication server as response to the
664 * GET AUTHORIZATION request is caught here.
666 * To make this possible, this activity needs to be qualified with android:launchMode =
667 * "singleTask" in the AndroidManifest.xml file.
670 protected void onNewIntent (Intent intent
) {
671 Log_OC
.d(TAG
, "onNewIntent()");
672 Uri data
= intent
.getData();
673 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
674 mNewCapturedUriFromOAuth2Redirection
= data
;
680 * The redirection triggered by the OAuth authentication server as response to the
681 * GET AUTHORIZATION, and deferred in {@link #onNewIntent(Intent)}, is processed here.
684 protected void onResume() {
687 // bound here to avoid spurious changes triggered by Android on device rotations
688 mHostUrlInput
.setOnFocusChangeListener(this);
689 mHostUrlInput
.addTextChangedListener(mHostUrlInputWatcher
);
691 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
692 getOAuth2AccessTokenFromCapturedRedirection();
695 if (mOperationsServiceBinder
!= null
) {
696 doOnResumeAndBound();
703 protected void onPause() {
704 if (mOperationsServiceBinder
!= null
) {
705 mOperationsServiceBinder
.removeOperationListener(this);
708 mHostUrlInput
.removeTextChangedListener(mHostUrlInputWatcher
);
709 mHostUrlInput
.setOnFocusChangeListener(null
);
715 protected void onDestroy() {
717 mHostUrlInputWatcher
= null
;
719 if (mOperationsServiceConnection
!= null
) {
720 unbindService(mOperationsServiceConnection
);
721 mOperationsServiceBinder
= null
;
728 * Parses the redirection with the response to the GET AUTHORIZATION request to the
729 * oAuth server and requests for the access token (GET ACCESS TOKEN)
731 private void getOAuth2AccessTokenFromCapturedRedirection() {
732 /// Parse data from OAuth redirection
733 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
734 mNewCapturedUriFromOAuth2Redirection
= null
;
736 /// Showing the dialog with instructions for the user.
737 IndeterminateProgressDialog dialog
=
738 IndeterminateProgressDialog
.newInstance(R
.string
.auth_getting_authorization
, true
);
739 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
741 /// GET ACCESS TOKEN to the oAuth server
742 Intent getServerInfoIntent
= new Intent();
743 getServerInfoIntent
.setAction(OperationsService
.ACTION_OAUTH2_GET_ACCESS_TOKEN
);
745 getServerInfoIntent
.putExtra(
746 OperationsService
.EXTRA_SERVER_URL
,
747 mOAuthTokenEndpointText
.getText().toString().trim());
749 getServerInfoIntent
.putExtra(
750 OperationsService
.EXTRA_OAUTH2_QUERY_PARAMETERS
,
753 if (mOperationsServiceBinder
!= null
) {
754 //Log_OC.wtf(TAG, "getting access token..." );
755 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
762 * Handles the change of focus on the text inputs for the server URL and the password
764 public void onFocusChange(View view
, boolean hasFocus
) {
765 if (view
.getId() == R
.id
.hostUrlInput
) {
767 onUrlInputFocusLost();
770 showRefreshButton(false
);
773 } else if (view
.getId() == R
.id
.account_password
) {
774 onPasswordFocusChanged(hasFocus
);
780 * Handles changes in focus on the text input for the server URL.
782 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
783 * other field. The operation to check the existence of the server in the entered URL is
786 * When hasFocus: user 'comes back' to write again the server URL.
788 private void onUrlInputFocusLost() {
789 if (!mServerInfo
.mBaseUrl
.equals(
790 normalizeUrl(mHostUrlInput
.getText().toString(), mServerInfo
.mIsSslConn
))) {
791 // check server again only if the user changed something in the field
794 mOkButton
.setEnabled(mServerIsValid
);
795 showRefreshButton(!mServerIsValid
);
800 private void checkOcServer() {
801 String uri
= mHostUrlInput
.getText().toString().trim();
802 mServerIsValid
= false
;
803 mServerIsChecked
= false
;
804 mOkButton
.setEnabled(false
);
805 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
806 showRefreshButton(false
);
808 if (uri
.length() != 0) {
809 uri
= stripIndexPhpOrAppsFiles(uri
, mHostUrlInput
);
811 // Handle internationalized domain names
812 uri
= DisplayUtils
.convertIdn(uri
, true
);
814 mServerStatusText
= R
.string
.auth_testing_connection
;
815 mServerStatusIcon
= R
.drawable
.progress_small
;
818 Intent getServerInfoIntent
= new Intent();
819 getServerInfoIntent
.setAction(OperationsService
.ACTION_GET_SERVER_INFO
);
820 getServerInfoIntent
.putExtra(
821 OperationsService
.EXTRA_SERVER_URL
,
822 normalizeUrlSuffix(uri
)
824 if (mOperationsServiceBinder
!= null
) {
825 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
827 Log_OC
.wtf(TAG
, "Server check tried with OperationService unbound!" );
831 mServerStatusText
= 0;
832 mServerStatusIcon
= 0;
839 * Handles changes in focus on the text input for the password (basic authorization).
841 * When (hasFocus), the button to toggle password visibility is shown.
843 * When (!hasFocus), the button is made invisible and the password is hidden.
845 * @param hasFocus 'True' if focus is received, 'false' if is lost
847 private void onPasswordFocusChanged(boolean hasFocus
) {
849 showViewPasswordButton();
852 hidePasswordButton();
857 private void showViewPasswordButton() {
858 int drawable
= R
.drawable
.ic_view
;
859 if (isPasswordVisible()) {
860 drawable
= R
.drawable
.ic_hide
;
862 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable
, 0);
865 private boolean isPasswordVisible() {
866 return ((mPasswordInput
.getInputType() & InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) ==
867 InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
870 private void hidePasswordButton() {
871 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
874 private void showPassword() {
875 mPasswordInput
.setInputType(
876 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
878 showViewPasswordButton();
881 private void hidePassword() {
882 mPasswordInput
.setInputType(
883 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
885 showViewPasswordButton();
889 * Checks the credentials of the user in the root of the ownCloud server
890 * before creating a new local account.
892 * For basic authorization, a check of existence of the root folder is
895 * For OAuth, starts the flow to get an access token; the credentials test
896 * is postponed until it is available.
898 * IMPORTANT ENTRY POINT 4
900 public void onOkClick() {
901 // this check should be unnecessary
902 if (mServerInfo
.mVersion
== null
||
903 !mServerInfo
.mVersion
.isVersionValid() ||
904 mServerInfo
.mBaseUrl
== null
||
905 mServerInfo
.mBaseUrl
.length() == 0) {
906 mServerStatusIcon
= R
.drawable
.common_error
;
907 mServerStatusText
= R
.string
.auth_wtf_reenter_URL
;
909 mOkButton
.setEnabled(false
);
913 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
914 equals(mAuthTokenType
)) {
916 startOauthorization();
917 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
918 equals(mAuthTokenType
)) {
920 startSamlBasedFederatedSingleSignOnAuthorization();
922 checkBasicAuthorization();
928 * Tests the credentials entered by the user performing a check of existence on
929 * the root folder of the ownCloud server.
931 private void checkBasicAuthorization() {
932 /// get basic credentials entered by user
933 String username
= mUsernameInput
.getText().toString();
934 String password
= mPasswordInput
.getText().toString();
936 /// be gentle with the user
937 IndeterminateProgressDialog dialog
=
938 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
939 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
941 /// validate credentials accessing the root folder
942 OwnCloudCredentials credentials
= OwnCloudCredentialsFactory
.newBasicCredentials(username
,
944 accessRootFolder(credentials
);
947 private void accessRootFolder(OwnCloudCredentials credentials
) {
948 mAsyncTask
= new AuthenticatorAsyncTask(this);
949 Object
[] params
= { mServerInfo
.mBaseUrl
, credentials
};
950 mAsyncTask
.execute(params
);
955 * Starts the OAuth 'grant type' flow to get an access token, with
956 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
958 private void startOauthorization() {
959 // be gentle with the user
960 mAuthStatusIcon
= R
.drawable
.progress_small
;
961 mAuthStatusText
= R
.string
.oauth_login_connection
;
964 // GET AUTHORIZATION request
965 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
966 Uri
.Builder uriBuilder
= uri
.buildUpon();
967 uriBuilder
.appendQueryParameter(
968 OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
)
970 uriBuilder
.appendQueryParameter(
971 OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
)
973 uriBuilder
.appendQueryParameter(
974 OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
)
976 uriBuilder
.appendQueryParameter(
977 OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
)
979 uri
= uriBuilder
.build();
980 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
981 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
987 * Starts the Web Single Sign On flow to get access to the root folder
990 private void startSamlBasedFederatedSingleSignOnAuthorization() {
991 /// be gentle with the user
992 mAuthStatusIcon
= R
.drawable
.progress_small
;
993 mAuthStatusText
= R
.string
.auth_connecting_auth_server
;
996 /// Show SAML-based SSO web dialog
997 String targetUrl
= mServerInfo
.mBaseUrl
998 + AccountUtils
.getWebdavPath(mServerInfo
.mVersion
, mAuthTokenType
);
999 SamlWebViewDialog dialog
= SamlWebViewDialog
.newInstance(targetUrl
, targetUrl
);
1000 dialog
.show(getSupportFragmentManager(), SAML_DIALOG_TAG
);
1004 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
1006 * Dispatches the operation flow to the right method.
1009 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1011 if (operation
instanceof GetServerInfoOperation
) {
1012 if (operation
.hashCode() == mWaitingForOpId
) {
1013 onGetServerInfoFinish(result
);
1014 } // else nothing ; only the last check operation is considered;
1015 // multiple can be started if the user amends a URL quickly
1017 } else if (operation
instanceof OAuth2GetAccessToken
) {
1018 onGetOAuthAccessTokenFinish(result
);
1020 } else if (operation
instanceof GetRemoteUserNameOperation
) {
1021 onGetUserNameFinish(result
);
1026 private void onGetUserNameFinish(RemoteOperationResult result
) {
1027 mWaitingForOpId
= Long
.MAX_VALUE
;
1028 if (result
.isSuccess()) {
1029 boolean success
= false
;
1030 String username
= (String
) result
.getData().get(0);
1032 if ( mAction
== ACTION_CREATE
) {
1033 mUsernameInput
.setText(username
);
1034 success
= createAccount(result
);
1037 if (!mUsernameInput
.getText().toString().equals(username
)) {
1038 // fail - not a new account, but an existing one; disallow
1039 result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_THE_SAME
);
1041 updateAuthStatusIconAndText(result
);
1043 Log_OC
.d(TAG
, result
.getLogMessage());
1046 updateAccountAuthentication();
1049 } catch (AccountNotFoundException e
) {
1050 Log_OC
.e(TAG
, "Account " + mAccount
+ " was removed!", e
);
1051 Toast
.makeText(this, R
.string
.auth_account_does_not_exist
,
1052 Toast
.LENGTH_SHORT
).show();
1061 updateStatusIconFailUserName();
1063 Log_OC
.e(TAG
, "Access to user name failed: " + result
.getLogMessage());
1069 * Processes the result of the server check performed when the user finishes the enter of the
1072 * @param result Result of the check.
1074 private void onGetServerInfoFinish(RemoteOperationResult result
) {
1075 /// update activity state
1076 mServerIsChecked
= true
;
1077 mWaitingForOpId
= Long
.MAX_VALUE
;
1079 // update server status, but don't show it yet
1080 updateServerStatusIconAndText(result
);
1082 if (result
.isSuccess()) {
1084 // 1. connection succeeded, and we know if it's SSL or not
1085 // 2. server is installed
1086 // 3. we got the server version
1087 // 4. we got the authentication method required by the server
1088 mServerInfo
= (GetServerInfoOperation
.ServerInfo
) (result
.getData().get(0));
1090 if (!authSupported(mServerInfo
.mAuthMethod
)) {
1092 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1093 mServerIsValid
= false
;
1096 mServerIsValid
= true
;
1100 mServerIsValid
= false
;
1104 showRefreshButton(!mServerIsValid
);
1106 mOkButton
.setEnabled(mServerIsValid
);
1108 /// very special case (TODO: move to a common place for all the remote operations)
1109 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1110 showUntrustedCertDialog(result
);
1115 private boolean authSupported(AuthenticationMethod authMethod
) {
1116 return (( BASIC_TOKEN_TYPE
.equals(mAuthTokenType
) &&
1117 AuthenticationMethod
.BASIC_HTTP_AUTH
.equals(authMethod
) ) ||
1118 ( OAUTH_TOKEN_TYPE
.equals(mAuthTokenType
) &&
1119 AuthenticationMethod
.BEARER_TOKEN
.equals(authMethod
)) ||
1120 ( SAML_TOKEN_TYPE
.equals(mAuthTokenType
) &&
1121 AuthenticationMethod
.SAML_WEB_SSO
.equals(authMethod
))
1126 // TODO remove, if possible
1127 private String
normalizeUrl(String url
, boolean sslWhenUnprefixed
) {
1128 if (url
!= null
&& url
.length() > 0) {
1130 if (!url
.toLowerCase().startsWith("http://") &&
1131 !url
.toLowerCase().startsWith("https://")) {
1132 if (sslWhenUnprefixed
) {
1133 url
= "https://" + url
;
1135 url
= "http://" + url
;
1139 url
= normalizeUrlSuffix(url
);
1141 return (url
!= null ? url
: "");
1145 private String
normalizeUrlSuffix(String url
) {
1146 if (url
.endsWith("/")) {
1147 url
= url
.substring(0, url
.length() - 1);
1149 url
= trimUrlWebdav(url
);
1153 private String
stripIndexPhpOrAppsFiles(String url
, EditText mHostUrlInput
) {
1154 if (url
.endsWith("/index.php")) {
1155 url
= url
.substring(0, url
.lastIndexOf("/index.php"));
1156 mHostUrlInput
.setText(url
);
1157 } else if (url
.contains("/index.php/apps/")) {
1158 url
= url
.substring(0, url
.lastIndexOf("/index.php/apps/"));
1159 mHostUrlInput
.setText(url
);
1165 // TODO remove, if possible
1166 private String
trimUrlWebdav(String url
){
1167 if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_4_0_AND_LATER
)){
1168 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_4_0_AND_LATER
.length());
1175 * Chooses the right icon and text to show to the user for the received operation result.
1177 * @param result Result of a remote operation performed in this activity
1179 private void updateServerStatusIconAndText(RemoteOperationResult result
) {
1180 mServerStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1182 switch (result
.getCode()) {
1184 mServerStatusIcon
= R
.drawable
.ic_lock
;
1185 mServerStatusText
= R
.string
.auth_secure_connection
;
1190 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1191 mServerStatusText
= R
.string
.auth_connection_established
;
1192 mServerStatusIcon
= R
.drawable
.ic_ok
;
1194 mServerStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1195 mServerStatusIcon
= R
.drawable
.ic_lock_open
;
1199 case NO_NETWORK_CONNECTION
:
1200 mServerStatusIcon
= R
.drawable
.no_network
;
1201 mServerStatusText
= R
.string
.auth_no_net_conn_title
;
1204 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1205 mServerStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1207 case BAD_OC_VERSION
:
1208 mServerStatusText
= R
.string
.auth_bad_oc_version_title
;
1210 case WRONG_CONNECTION
:
1211 mServerStatusText
= R
.string
.auth_wrong_connection_title
;
1214 mServerStatusText
= R
.string
.auth_timeout_title
;
1216 case INCORRECT_ADDRESS
:
1217 mServerStatusText
= R
.string
.auth_incorrect_address_title
;
1220 mServerStatusText
= R
.string
.auth_ssl_general_error_title
;
1223 mServerStatusText
= R
.string
.auth_unauthorized
;
1225 case HOST_NOT_AVAILABLE
:
1226 mServerStatusText
= R
.string
.auth_unknown_host_title
;
1228 case INSTANCE_NOT_CONFIGURED
:
1229 mServerStatusText
= R
.string
.auth_not_configured_title
;
1231 case FILE_NOT_FOUND
:
1232 mServerStatusText
= R
.string
.auth_incorrect_path_title
;
1235 mServerStatusText
= R
.string
.auth_oauth_error
;
1237 case OAUTH2_ERROR_ACCESS_DENIED
:
1238 mServerStatusText
= R
.string
.auth_oauth_error_access_denied
;
1240 case UNHANDLED_HTTP_CODE
:
1242 mServerStatusText
= R
.string
.auth_unknown_error_title
;
1244 case OK_REDIRECT_TO_NON_SECURE_CONNECTION
:
1245 mServerStatusIcon
= R
.drawable
.ic_lock_open
;
1246 mServerStatusText
= R
.string
.auth_redirect_non_secure_connection_title
;
1249 mServerStatusText
= 0;
1250 mServerStatusIcon
= 0;
1256 * Chooses the right icon and text to show to the user for the received operation result.
1258 * @param result Result of a remote operation performed in this activity
1260 private void updateAuthStatusIconAndText(RemoteOperationResult result
) {
1261 mAuthStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1263 switch (result
.getCode()) {
1265 mAuthStatusIcon
= R
.drawable
.ic_lock
;
1266 mAuthStatusText
= R
.string
.auth_secure_connection
;
1271 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1272 mAuthStatusText
= R
.string
.auth_connection_established
;
1273 mAuthStatusIcon
= R
.drawable
.ic_ok
;
1275 mAuthStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1276 mAuthStatusIcon
= R
.drawable
.ic_lock_open
;
1280 case NO_NETWORK_CONNECTION
:
1281 mAuthStatusIcon
= R
.drawable
.no_network
;
1282 mAuthStatusText
= R
.string
.auth_no_net_conn_title
;
1285 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1286 mAuthStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1288 case BAD_OC_VERSION
:
1289 mAuthStatusText
= R
.string
.auth_bad_oc_version_title
;
1291 case WRONG_CONNECTION
:
1292 mAuthStatusText
= R
.string
.auth_wrong_connection_title
;
1295 mAuthStatusText
= R
.string
.auth_timeout_title
;
1297 case INCORRECT_ADDRESS
:
1298 mAuthStatusText
= R
.string
.auth_incorrect_address_title
;
1301 mAuthStatusText
= R
.string
.auth_ssl_general_error_title
;
1304 mAuthStatusText
= R
.string
.auth_unauthorized
;
1306 case HOST_NOT_AVAILABLE
:
1307 mAuthStatusText
= R
.string
.auth_unknown_host_title
;
1309 case INSTANCE_NOT_CONFIGURED
:
1310 mAuthStatusText
= R
.string
.auth_not_configured_title
;
1312 case FILE_NOT_FOUND
:
1313 mAuthStatusText
= R
.string
.auth_incorrect_path_title
;
1316 mAuthStatusText
= R
.string
.auth_oauth_error
;
1318 case OAUTH2_ERROR_ACCESS_DENIED
:
1319 mAuthStatusText
= R
.string
.auth_oauth_error_access_denied
;
1321 case ACCOUNT_NOT_NEW
:
1322 mAuthStatusText
= R
.string
.auth_account_not_new
;
1324 case ACCOUNT_NOT_THE_SAME
:
1325 mAuthStatusText
= R
.string
.auth_account_not_the_same
;
1327 case UNHANDLED_HTTP_CODE
:
1329 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
1332 mAuthStatusText
= 0;
1333 mAuthStatusIcon
= 0;
1338 private void updateStatusIconFailUserName(){
1339 mAuthStatusIcon
= R
.drawable
.common_error
;
1340 mAuthStatusText
= R
.string
.auth_fail_get_user_name
;
1343 private void updateServerStatusIconNoRegularAuth(){
1344 mServerStatusIcon
= R
.drawable
.common_error
;
1345 mServerStatusText
= R
.string
.auth_can_not_auth_against_server
;
1349 * Processes the result of the request for and access token send
1350 * to an OAuth authorization server.
1352 * @param result Result of the operation.
1354 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result
) {
1355 mWaitingForOpId
= Long
.MAX_VALUE
;
1356 dismissDialog(WAIT_DIALOG_TAG
);
1358 if (result
.isSuccess()) {
1359 /// be gentle with the user
1360 IndeterminateProgressDialog dialog
=
1361 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
1362 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
1364 /// time to test the retrieved access token on the ownCloud server
1365 @SuppressWarnings("unchecked")
1366 Map
<String
, String
> tokens
= (Map
<String
, String
>)(result
.getData().get(0));
1367 mAuthToken
= tokens
.get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
1368 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mAuthToken
);
1370 /// validate token accessing to root folder / getting session
1371 OwnCloudCredentials credentials
= OwnCloudCredentialsFactory
.newBearerCredentials(
1373 accessRootFolder(credentials
);
1376 updateAuthStatusIconAndText(result
);
1378 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1384 * Processes the result of the access check performed to try the user credentials.
1386 * Creates a new account through the AccountManager.
1388 * @param result Result of the operation.
1391 public void onAuthenticatorTaskCallback(RemoteOperationResult result
) {
1392 mWaitingForOpId
= Long
.MAX_VALUE
;
1393 dismissDialog(WAIT_DIALOG_TAG
);
1396 if (result
.isSuccess()) {
1397 Log_OC
.d(TAG
, "Successful access - time to save the account");
1399 boolean success
= false
;
1401 if (mAction
== ACTION_CREATE
) {
1402 success
= createAccount(result
);
1406 updateAccountAuthentication();
1409 } catch (AccountNotFoundException e
) {
1410 Log_OC
.e(TAG
, "Account " + mAccount
+ " was removed!", e
);
1411 Toast
.makeText(this, R
.string
.auth_account_does_not_exist
,
1412 Toast
.LENGTH_SHORT
).show();
1421 } else if (result
.isServerFail() || result
.isException()) {
1422 /// server errors or exceptions in authorization take to requiring a new check of
1424 mServerIsChecked
= true
;
1425 mServerIsValid
= false
;
1426 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
1428 // update status icon and text
1429 updateServerStatusIconAndText(result
);
1431 mAuthStatusIcon
= 0;
1432 mAuthStatusText
= 0;
1435 // update input controls state
1436 showRefreshButton(true
);
1437 mOkButton
.setEnabled(false
);
1439 // very special case (TODO: move to a common place for all the remote operations)
1440 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1441 showUntrustedCertDialog(result
);
1444 } else { // authorization fail due to client side - probably wrong credentials
1445 updateAuthStatusIconAndText(result
);
1447 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1455 * Updates the authentication token.
1457 * Sets the proper response so that the AccountAuthenticator that started this activity
1458 * saves a new authorization token for mAccount.
1460 * Kills the session kept by OwnCloudClientManager so that a new one will created with
1461 * the new credentials when needed.
1463 private void updateAccountAuthentication() throws AccountNotFoundException
{
1465 Bundle response
= new Bundle();
1466 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1467 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
1469 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
1470 equals(mAuthTokenType
)) {
1471 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1472 // the next line is necessary, notifications are calling directly to the
1473 // AuthenticatorActivity to update, without AccountManager intervention
1474 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1476 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1477 equals(mAuthTokenType
)) {
1479 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1480 // the next line is necessary; by now, notifications are calling directly to the
1481 // AuthenticatorActivity to update, without AccountManager intervention
1482 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1485 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
1486 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
1488 setAccountAuthenticatorResult(response
);
1494 * Creates a new account through the Account Authenticator that started this activity.
1496 * This makes the account permanent.
1498 * TODO Decide how to name the OAuth accounts
1500 private boolean createAccount(RemoteOperationResult authResult
) {
1501 /// create and save new ownCloud account
1502 boolean isOAuth
= AccountTypeUtils
.
1503 getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
);
1504 boolean isSaml
= AccountTypeUtils
.
1505 getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
);
1507 String lastPermanentLocation
= authResult
.getLastPermanentLocation();
1508 if (lastPermanentLocation
!= null
) {
1509 mServerInfo
.mBaseUrl
= AccountUtils
.trimWebdavSuffix(lastPermanentLocation
);
1512 Uri uri
= Uri
.parse(mServerInfo
.mBaseUrl
);
1513 String username
= mUsernameInput
.getText().toString().trim();
1515 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1517 String accountName
= com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.
1518 buildAccountName(uri
, username
);
1519 Account newAccount
= new Account(accountName
, MainApp
.getAccountType());
1520 if (AccountUtils
.exists(newAccount
, getApplicationContext())) {
1521 // fail - not a new account, but an existing one; disallow
1522 RemoteOperationResult result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_NEW
);
1523 updateAuthStatusIconAndText(result
);
1525 Log_OC
.d(TAG
, result
.getLogMessage());
1529 mAccount
= newAccount
;
1531 if (isOAuth
|| isSaml
) {
1532 // with external authorizations, the password is never input in the app
1533 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
);
1535 mAccountMgr
.addAccountExplicitly(
1536 mAccount
, mPasswordInput
.getText().toString(), null
1540 // include account version with the new account
1541 mAccountMgr
.setUserData(
1543 Constants
.KEY_OC_ACCOUNT_VERSION
,
1544 Integer
.toString(AccountUtils
.ACCOUNT_VERSION
)
1547 /// add the new account as default in preferences, if there is none already
1548 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1549 if (defaultAccount
== null
) {
1550 SharedPreferences
.Editor editor
= PreferenceManager
1551 .getDefaultSharedPreferences(this).edit();
1552 editor
.putString("select_oc_account", accountName
);
1556 /// prepare result to return to the Authenticator
1557 // TODO check again what the Authenticator makes with it; probably has the same
1558 // effect as addAccountExplicitly, but it's not well done
1559 final Intent intent
= new Intent();
1560 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, MainApp
.getAccountType());
1561 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1562 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1563 if (isOAuth
|| isSaml
) {
1564 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1566 /// add user data to the new account; TODO probably can be done in the last parameter
1567 // addAccountExplicitly, or in KEY_USERDATA
1568 mAccountMgr
.setUserData(
1569 mAccount
, Constants
.KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion()
1571 mAccountMgr
.setUserData(
1572 mAccount
, Constants
.KEY_OC_BASE_URL
, mServerInfo
.mBaseUrl
1576 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
, "TRUE");
1577 } else if (isOAuth
) {
1578 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
, "TRUE");
1581 setAccountAuthenticatorResult(intent
.getExtras());
1582 setResult(RESULT_OK
, intent
);
1590 * Starts and activity to open the 'new account' page in the ownCloud web site
1592 * @param view 'Account register' button
1594 public void onRegisterClick(View view
) {
1595 Intent register
= new Intent(
1596 Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.welcome_link_url
))
1598 setResult(RESULT_CANCELED
);
1599 startActivity(register
);
1604 * Updates the content and visibility state of the icon and text associated
1605 * to the last check on the ownCloud server.
1608 private void showServerStatus() {
1609 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1610 mServerStatusView
.setVisibility(View
.INVISIBLE
);
1613 mServerStatusView
.setText(mServerStatusText
);
1614 mServerStatusView
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1615 mServerStatusView
.setVisibility(View
.VISIBLE
);
1622 * Updates the content and visibility state of the icon and text associated
1623 * to the interactions with the OAuth authorization server.
1625 private void showAuthStatus() {
1626 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1627 mAuthStatusView
.setVisibility(View
.INVISIBLE
);
1630 mAuthStatusView
.setText(mAuthStatusText
);
1631 mAuthStatusView
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1632 mAuthStatusView
.setVisibility(View
.VISIBLE
);
1637 private void showRefreshButton (boolean show
) {
1639 mRefreshButton
.setVisibility(View
.VISIBLE
);
1641 mRefreshButton
.setVisibility(View
.GONE
);
1646 * Called when the eye icon in the password field is clicked.
1648 * Toggles the visibility of the password in the field.
1650 public void onViewPasswordClick() {
1651 int selectionStart
= mPasswordInput
.getSelectionStart();
1652 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1653 if (isPasswordVisible()) {
1658 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1663 * Called when the checkbox for OAuth authorization is clicked.
1665 * Hides or shows the input fields for user & password.
1667 * @param view 'View password' 'button'
1669 public void onCheckClick(View view
) {
1670 CheckBox oAuth2Check
= (CheckBox
)view
;
1671 if (oAuth2Check
.isChecked()) {
1672 mAuthTokenType
= OAUTH_TOKEN_TYPE
;
1674 mAuthTokenType
= BASIC_TOKEN_TYPE
;
1676 updateAuthenticationPreFragmentVisibility();
1681 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1683 * Used to trigger the authentication check when the user presses 'enter' after writing the
1684 * password, or to throw the server test when the only field on screen is the URL input field.
1687 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1688 if (actionId
== EditorInfo
.IME_ACTION_DONE
&& inputField
!= null
&&
1689 inputField
.equals(mPasswordInput
)) {
1690 if (mOkButton
.isEnabled()) {
1691 mOkButton
.performClick();
1694 } else if (actionId
== EditorInfo
.IME_ACTION_NEXT
&& inputField
!= null
&&
1695 inputField
.equals(mHostUrlInput
)) {
1696 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1697 equals(mAuthTokenType
)) {
1701 return false
; // always return false to grant that the software keyboard is hidden anyway
1705 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1707 private int fuzz
= 75;
1713 public boolean onTouch(View view
, MotionEvent event
) {
1714 Drawable rightDrawable
= null
;
1715 if (view
instanceof TextView
) {
1716 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1717 if (drawables
.length
> 2) {
1718 rightDrawable
= drawables
[2];
1721 if (rightDrawable
!= null
) {
1722 final int x
= (int) event
.getX();
1723 final int y
= (int) event
.getY();
1724 final Rect bounds
= rightDrawable
.getBounds();
1725 if ( x
>= (view
.getRight() - bounds
.width() - fuzz
) &&
1726 x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
) &&
1727 y
>= (view
.getPaddingTop() - fuzz
) &&
1728 y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1730 return onDrawableTouch(event
);
1736 public abstract boolean onDrawableTouch(final MotionEvent event
);
1740 private void getRemoteUserNameOperation(String sessionCookie
) {
1742 Intent getUserNameIntent
= new Intent();
1743 getUserNameIntent
.setAction(OperationsService
.ACTION_GET_USER_NAME
);
1744 getUserNameIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
1745 getUserNameIntent
.putExtra(OperationsService
.EXTRA_COOKIE
, sessionCookie
);
1747 if (mOperationsServiceBinder
!= null
) {
1748 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getUserNameIntent
);
1754 public void onSsoFinished(String sessionCookie
) {
1755 if (sessionCookie
!= null
&& sessionCookie
.length() > 0) {
1756 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1757 mAuthToken
= sessionCookie
;
1758 getRemoteUserNameOperation(sessionCookie
);
1759 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1760 if (fd
!= null
&& fd
instanceof DialogFragment
) {
1761 Dialog d
= ((DialogFragment
)fd
).getDialog();
1762 if (d
!= null
&& d
.isShowing()) {
1769 Log_OC
.d(TAG
, "SSO failed");
1775 public boolean onTouchEvent(MotionEvent event
) {
1776 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1777 equals(mAuthTokenType
) &&
1778 mHostUrlInput
.hasFocus() && event
.getAction() == MotionEvent
.ACTION_DOWN
) {
1781 return super.onTouchEvent(event
);
1786 * Show untrusted cert dialog
1788 public void showUntrustedCertDialog(
1789 X509Certificate x509Certificate
, SslError error
, SslErrorHandler handler
1791 // Show a dialog with the certificate info
1792 SslUntrustedCertDialog dialog
;
1793 if (x509Certificate
== null
) {
1794 dialog
= SslUntrustedCertDialog
.newInstanceForEmptySslError(error
, handler
);
1796 dialog
= SslUntrustedCertDialog
.
1797 newInstanceForFullSslError(x509Certificate
, error
, handler
);
1799 FragmentManager fm
= getSupportFragmentManager();
1800 FragmentTransaction ft
= fm
.beginTransaction();
1801 ft
.addToBackStack(null
);
1802 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1807 * Show untrusted cert dialog
1809 private void showUntrustedCertDialog(RemoteOperationResult result
) {
1810 // Show a dialog with the certificate info
1811 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.
1812 newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1813 FragmentManager fm
= getSupportFragmentManager();
1814 FragmentTransaction ft
= fm
.beginTransaction();
1815 ft
.addToBackStack(null
);
1816 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1821 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1823 public void onSavedCertificate() {
1824 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1826 // if SAML dialog is not shown,
1827 // the SslDialog was shown due to an SSL error in the server check
1833 * Called from SslValidatorDialog when a new server certificate could not be saved
1834 * when the user requested it.
1837 public void onFailedSavingCertificate() {
1838 dismissDialog(SAML_DIALOG_TAG
);
1839 Toast
.makeText(this, R
.string
.ssl_validator_not_saved
, Toast
.LENGTH_LONG
).show();
1843 public void onCancelCertificate() {
1844 dismissDialog(SAML_DIALOG_TAG
);
1848 private void doOnResumeAndBound() {
1849 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1850 mOperationsServiceBinder
.addOperationListener(AuthenticatorActivity
.this, mHandler
);
1851 if (mWaitingForOpId
<= Integer
.MAX_VALUE
) {
1852 mOperationsServiceBinder
.dispatchResultIfFinished((int)mWaitingForOpId
, this);
1855 if (mPendingAutoCheck
) {
1861 private void dismissDialog(String dialogTag
){
1862 Fragment frag
= getSupportFragmentManager().findFragmentByTag(dialogTag
);
1863 if (frag
!= null
&& frag
instanceof DialogFragment
) {
1864 DialogFragment dialog
= (DialogFragment
) frag
;
1871 * Implements callback methods for service binding.
1873 private class OperationsServiceConnection
implements ServiceConnection
{
1876 public void onServiceConnected(ComponentName component
, IBinder service
) {
1877 if (component
.equals(
1878 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1880 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
1882 doOnResumeAndBound();
1889 public void onServiceDisconnected(ComponentName component
) {
1890 if (component
.equals(
1891 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1893 Log_OC
.e(TAG
, "Operations service crashed");
1894 mOperationsServiceBinder
= null
;
1901 * Create and show dialog for request authentication to the user
1902 * @param webView Web view to emebd into the authentication dialog.
1903 * @param handler Object responsible for catching and recovering HTTP authentication fails.
1905 public void createAuthenticationDialog(WebView webView
, HttpAuthHandler handler
) {
1907 // Show a dialog with the certificate info
1908 CredentialsDialogFragment dialog
=
1909 CredentialsDialogFragment
.newInstanceForCredentials(webView
, handler
);
1910 FragmentManager fm
= getSupportFragmentManager();
1911 FragmentTransaction ft
= fm
.beginTransaction();
1912 ft
.addToBackStack(null
);
1913 dialog
.setCancelable(false
);
1914 dialog
.show(ft
, CREDENTIALS_DIALOG_TAG
);
1916 if (!mIsFirstAuthAttempt
) {
1918 getApplicationContext(),
1919 getText(R
.string
.saml_authentication_wrong_pass
),
1923 mIsFirstAuthAttempt
= false
;
1928 * For retrieving the clicking on authentication cancel button
1930 public void doNegativeAuthenticatioDialogClick(){
1931 mIsFirstAuthAttempt
= true
;