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 // Handle internationalized domain names
810 uri
= DisplayUtils
.convertIdn(uri
, true
);
812 mServerStatusText
= R
.string
.auth_testing_connection
;
813 mServerStatusIcon
= R
.drawable
.progress_small
;
816 Intent getServerInfoIntent
= new Intent();
817 getServerInfoIntent
.setAction(OperationsService
.ACTION_GET_SERVER_INFO
);
818 getServerInfoIntent
.putExtra(
819 OperationsService
.EXTRA_SERVER_URL
,
820 normalizeUrlSuffix(uri
)
822 if (mOperationsServiceBinder
!= null
) {
823 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
825 Log_OC
.wtf(TAG
, "Server check tried with OperationService unbound!" );
829 mServerStatusText
= 0;
830 mServerStatusIcon
= 0;
837 * Handles changes in focus on the text input for the password (basic authorization).
839 * When (hasFocus), the button to toggle password visibility is shown.
841 * When (!hasFocus), the button is made invisible and the password is hidden.
843 * @param hasFocus 'True' if focus is received, 'false' if is lost
845 private void onPasswordFocusChanged(boolean hasFocus
) {
847 showViewPasswordButton();
850 hidePasswordButton();
855 private void showViewPasswordButton() {
856 int drawable
= R
.drawable
.ic_view
;
857 if (isPasswordVisible()) {
858 drawable
= R
.drawable
.ic_hide
;
860 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable
, 0);
863 private boolean isPasswordVisible() {
864 return ((mPasswordInput
.getInputType() & InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) ==
865 InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
868 private void hidePasswordButton() {
869 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
872 private void showPassword() {
873 mPasswordInput
.setInputType(
874 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
876 showViewPasswordButton();
879 private void hidePassword() {
880 mPasswordInput
.setInputType(
881 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
883 showViewPasswordButton();
887 * Checks the credentials of the user in the root of the ownCloud server
888 * before creating a new local account.
890 * For basic authorization, a check of existence of the root folder is
893 * For OAuth, starts the flow to get an access token; the credentials test
894 * is postponed until it is available.
896 * IMPORTANT ENTRY POINT 4
898 public void onOkClick() {
899 // this check should be unnecessary
900 if (mServerInfo
.mVersion
== null
||
901 !mServerInfo
.mVersion
.isVersionValid() ||
902 mServerInfo
.mBaseUrl
== null
||
903 mServerInfo
.mBaseUrl
.length() == 0) {
904 mServerStatusIcon
= R
.drawable
.common_error
;
905 mServerStatusText
= R
.string
.auth_wtf_reenter_URL
;
907 mOkButton
.setEnabled(false
);
911 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
912 equals(mAuthTokenType
)) {
914 startOauthorization();
915 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
916 equals(mAuthTokenType
)) {
918 startSamlBasedFederatedSingleSignOnAuthorization();
920 checkBasicAuthorization();
926 * Tests the credentials entered by the user performing a check of existence on
927 * the root folder of the ownCloud server.
929 private void checkBasicAuthorization() {
930 /// get basic credentials entered by user
931 String username
= mUsernameInput
.getText().toString();
932 String password
= mPasswordInput
.getText().toString();
934 /// be gentle with the user
935 IndeterminateProgressDialog dialog
=
936 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
937 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
939 /// validate credentials accessing the root folder
940 OwnCloudCredentials credentials
= OwnCloudCredentialsFactory
.newBasicCredentials(username
,
942 accessRootFolder(credentials
);
945 private void accessRootFolder(OwnCloudCredentials credentials
) {
946 mAsyncTask
= new AuthenticatorAsyncTask(this);
947 Object
[] params
= { mServerInfo
.mBaseUrl
, credentials
};
948 mAsyncTask
.execute(params
);
953 * Starts the OAuth 'grant type' flow to get an access token, with
954 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
956 private void startOauthorization() {
957 // be gentle with the user
958 mAuthStatusIcon
= R
.drawable
.progress_small
;
959 mAuthStatusText
= R
.string
.oauth_login_connection
;
962 // GET AUTHORIZATION request
963 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
964 Uri
.Builder uriBuilder
= uri
.buildUpon();
965 uriBuilder
.appendQueryParameter(
966 OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
)
968 uriBuilder
.appendQueryParameter(
969 OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
)
971 uriBuilder
.appendQueryParameter(
972 OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
)
974 uriBuilder
.appendQueryParameter(
975 OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
)
977 uri
= uriBuilder
.build();
978 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
979 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
985 * Starts the Web Single Sign On flow to get access to the root folder
988 private void startSamlBasedFederatedSingleSignOnAuthorization() {
989 /// be gentle with the user
990 mAuthStatusIcon
= R
.drawable
.progress_small
;
991 mAuthStatusText
= R
.string
.auth_connecting_auth_server
;
994 /// Show SAML-based SSO web dialog
995 String targetUrl
= mServerInfo
.mBaseUrl
996 + AccountUtils
.getWebdavPath(mServerInfo
.mVersion
, mAuthTokenType
);
997 SamlWebViewDialog dialog
= SamlWebViewDialog
.newInstance(targetUrl
, targetUrl
);
998 dialog
.show(getSupportFragmentManager(), SAML_DIALOG_TAG
);
1002 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
1004 * Dispatches the operation flow to the right method.
1007 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
1009 if (operation
instanceof GetServerInfoOperation
) {
1010 if (operation
.hashCode() == mWaitingForOpId
) {
1011 onGetServerInfoFinish(result
);
1012 } // else nothing ; only the last check operation is considered;
1013 // multiple can be started if the user amends a URL quickly
1015 } else if (operation
instanceof OAuth2GetAccessToken
) {
1016 onGetOAuthAccessTokenFinish(result
);
1018 } else if (operation
instanceof GetRemoteUserNameOperation
) {
1019 onGetUserNameFinish(result
);
1024 private void onGetUserNameFinish(RemoteOperationResult result
) {
1025 mWaitingForOpId
= Long
.MAX_VALUE
;
1026 if (result
.isSuccess()) {
1027 boolean success
= false
;
1028 String username
= (String
) result
.getData().get(0);
1030 if ( mAction
== ACTION_CREATE
) {
1031 mUsernameInput
.setText(username
);
1032 success
= createAccount(result
);
1035 if (!mUsernameInput
.getText().toString().equals(username
)) {
1036 // fail - not a new account, but an existing one; disallow
1037 result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_THE_SAME
);
1039 updateAuthStatusIconAndText(result
);
1041 Log_OC
.d(TAG
, result
.getLogMessage());
1044 updateAccountAuthentication();
1047 } catch (AccountNotFoundException e
) {
1048 Log_OC
.e(TAG
, "Account " + mAccount
+ " was removed!", e
);
1049 Toast
.makeText(this, R
.string
.auth_account_does_not_exist
,
1050 Toast
.LENGTH_SHORT
).show();
1059 updateStatusIconFailUserName();
1061 Log_OC
.e(TAG
, "Access to user name failed: " + result
.getLogMessage());
1067 * Processes the result of the server check performed when the user finishes the enter of the
1070 * @param result Result of the check.
1072 private void onGetServerInfoFinish(RemoteOperationResult result
) {
1073 /// update activity state
1074 mServerIsChecked
= true
;
1075 mWaitingForOpId
= Long
.MAX_VALUE
;
1077 // update server status, but don't show it yet
1078 updateServerStatusIconAndText(result
);
1080 if (result
.isSuccess()) {
1082 // 1. connection succeeded, and we know if it's SSL or not
1083 // 2. server is installed
1084 // 3. we got the server version
1085 // 4. we got the authentication method required by the server
1086 mServerInfo
= (GetServerInfoOperation
.ServerInfo
) (result
.getData().get(0));
1088 if (!authSupported(mServerInfo
.mAuthMethod
)) {
1090 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1091 mServerIsValid
= false
;
1094 mServerIsValid
= true
;
1098 mServerIsValid
= false
;
1102 showRefreshButton(!mServerIsValid
);
1104 mOkButton
.setEnabled(mServerIsValid
);
1106 /// very special case (TODO: move to a common place for all the remote operations)
1107 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1108 showUntrustedCertDialog(result
);
1113 private boolean authSupported(AuthenticationMethod authMethod
) {
1114 return (( BASIC_TOKEN_TYPE
.equals(mAuthTokenType
) &&
1115 AuthenticationMethod
.BASIC_HTTP_AUTH
.equals(authMethod
) ) ||
1116 ( OAUTH_TOKEN_TYPE
.equals(mAuthTokenType
) &&
1117 AuthenticationMethod
.BEARER_TOKEN
.equals(authMethod
)) ||
1118 ( SAML_TOKEN_TYPE
.equals(mAuthTokenType
) &&
1119 AuthenticationMethod
.SAML_WEB_SSO
.equals(authMethod
))
1124 // TODO remove, if possible
1125 private String
normalizeUrl(String url
, boolean sslWhenUnprefixed
) {
1126 if (url
!= null
&& url
.length() > 0) {
1128 if (!url
.toLowerCase().startsWith("http://") &&
1129 !url
.toLowerCase().startsWith("https://")) {
1130 if (sslWhenUnprefixed
) {
1131 url
= "https://" + url
;
1133 url
= "http://" + url
;
1137 url
= normalizeUrlSuffix(url
);
1139 return (url
!= null ? url
: "");
1143 private String
normalizeUrlSuffix(String url
) {
1144 if (url
.endsWith("/")) {
1145 url
= url
.substring(0, url
.length() - 1);
1147 url
= trimUrlWebdav(url
);
1152 // TODO remove, if possible
1153 private String
trimUrlWebdav(String url
){
1154 if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_4_0_AND_LATER
)){
1155 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_4_0_AND_LATER
.length());
1162 * Chooses the right icon and text to show to the user for the received operation result.
1164 * @param result Result of a remote operation performed in this activity
1166 private void updateServerStatusIconAndText(RemoteOperationResult result
) {
1167 mServerStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1169 switch (result
.getCode()) {
1171 mServerStatusIcon
= R
.drawable
.ic_lock
;
1172 mServerStatusText
= R
.string
.auth_secure_connection
;
1177 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1178 mServerStatusText
= R
.string
.auth_connection_established
;
1179 mServerStatusIcon
= R
.drawable
.ic_ok
;
1181 mServerStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1182 mServerStatusIcon
= R
.drawable
.ic_lock_open
;
1186 case NO_NETWORK_CONNECTION
:
1187 mServerStatusIcon
= R
.drawable
.no_network
;
1188 mServerStatusText
= R
.string
.auth_no_net_conn_title
;
1191 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1192 mServerStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1194 case BAD_OC_VERSION
:
1195 mServerStatusText
= R
.string
.auth_bad_oc_version_title
;
1197 case WRONG_CONNECTION
:
1198 mServerStatusText
= R
.string
.auth_wrong_connection_title
;
1201 mServerStatusText
= R
.string
.auth_timeout_title
;
1203 case INCORRECT_ADDRESS
:
1204 mServerStatusText
= R
.string
.auth_incorrect_address_title
;
1207 mServerStatusText
= R
.string
.auth_ssl_general_error_title
;
1210 mServerStatusText
= R
.string
.auth_unauthorized
;
1212 case HOST_NOT_AVAILABLE
:
1213 mServerStatusText
= R
.string
.auth_unknown_host_title
;
1215 case INSTANCE_NOT_CONFIGURED
:
1216 mServerStatusText
= R
.string
.auth_not_configured_title
;
1218 case FILE_NOT_FOUND
:
1219 mServerStatusText
= R
.string
.auth_incorrect_path_title
;
1222 mServerStatusText
= R
.string
.auth_oauth_error
;
1224 case OAUTH2_ERROR_ACCESS_DENIED
:
1225 mServerStatusText
= R
.string
.auth_oauth_error_access_denied
;
1227 case UNHANDLED_HTTP_CODE
:
1229 mServerStatusText
= R
.string
.auth_unknown_error_title
;
1231 case OK_REDIRECT_TO_NON_SECURE_CONNECTION
:
1232 mServerStatusIcon
= R
.drawable
.ic_lock_open
;
1233 mServerStatusText
= R
.string
.auth_redirect_non_secure_connection_title
;
1236 mServerStatusText
= 0;
1237 mServerStatusIcon
= 0;
1243 * Chooses the right icon and text to show to the user for the received operation result.
1245 * @param result Result of a remote operation performed in this activity
1247 private void updateAuthStatusIconAndText(RemoteOperationResult result
) {
1248 mAuthStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1250 switch (result
.getCode()) {
1252 mAuthStatusIcon
= R
.drawable
.ic_lock
;
1253 mAuthStatusText
= R
.string
.auth_secure_connection
;
1258 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1259 mAuthStatusText
= R
.string
.auth_connection_established
;
1260 mAuthStatusIcon
= R
.drawable
.ic_ok
;
1262 mAuthStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1263 mAuthStatusIcon
= R
.drawable
.ic_lock_open
;
1267 case NO_NETWORK_CONNECTION
:
1268 mAuthStatusIcon
= R
.drawable
.no_network
;
1269 mAuthStatusText
= R
.string
.auth_no_net_conn_title
;
1272 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1273 mAuthStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1275 case BAD_OC_VERSION
:
1276 mAuthStatusText
= R
.string
.auth_bad_oc_version_title
;
1278 case WRONG_CONNECTION
:
1279 mAuthStatusText
= R
.string
.auth_wrong_connection_title
;
1282 mAuthStatusText
= R
.string
.auth_timeout_title
;
1284 case INCORRECT_ADDRESS
:
1285 mAuthStatusText
= R
.string
.auth_incorrect_address_title
;
1288 mAuthStatusText
= R
.string
.auth_ssl_general_error_title
;
1291 mAuthStatusText
= R
.string
.auth_unauthorized
;
1293 case HOST_NOT_AVAILABLE
:
1294 mAuthStatusText
= R
.string
.auth_unknown_host_title
;
1296 case INSTANCE_NOT_CONFIGURED
:
1297 mAuthStatusText
= R
.string
.auth_not_configured_title
;
1299 case FILE_NOT_FOUND
:
1300 mAuthStatusText
= R
.string
.auth_incorrect_path_title
;
1303 mAuthStatusText
= R
.string
.auth_oauth_error
;
1305 case OAUTH2_ERROR_ACCESS_DENIED
:
1306 mAuthStatusText
= R
.string
.auth_oauth_error_access_denied
;
1308 case ACCOUNT_NOT_NEW
:
1309 mAuthStatusText
= R
.string
.auth_account_not_new
;
1311 case ACCOUNT_NOT_THE_SAME
:
1312 mAuthStatusText
= R
.string
.auth_account_not_the_same
;
1314 case UNHANDLED_HTTP_CODE
:
1316 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
1319 mAuthStatusText
= 0;
1320 mAuthStatusIcon
= 0;
1325 private void updateStatusIconFailUserName(){
1326 mAuthStatusIcon
= R
.drawable
.common_error
;
1327 mAuthStatusText
= R
.string
.auth_fail_get_user_name
;
1330 private void updateServerStatusIconNoRegularAuth(){
1331 mServerStatusIcon
= R
.drawable
.common_error
;
1332 mServerStatusText
= R
.string
.auth_can_not_auth_against_server
;
1336 * Processes the result of the request for and access token send
1337 * to an OAuth authorization server.
1339 * @param result Result of the operation.
1341 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result
) {
1342 mWaitingForOpId
= Long
.MAX_VALUE
;
1343 dismissDialog(WAIT_DIALOG_TAG
);
1345 if (result
.isSuccess()) {
1346 /// be gentle with the user
1347 IndeterminateProgressDialog dialog
=
1348 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
1349 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
1351 /// time to test the retrieved access token on the ownCloud server
1352 @SuppressWarnings("unchecked")
1353 Map
<String
, String
> tokens
= (Map
<String
, String
>)(result
.getData().get(0));
1354 mAuthToken
= tokens
.get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
1355 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mAuthToken
);
1357 /// validate token accessing to root folder / getting session
1358 OwnCloudCredentials credentials
= OwnCloudCredentialsFactory
.newBearerCredentials(
1360 accessRootFolder(credentials
);
1363 updateAuthStatusIconAndText(result
);
1365 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1371 * Processes the result of the access check performed to try the user credentials.
1373 * Creates a new account through the AccountManager.
1375 * @param result Result of the operation.
1378 public void onAuthenticatorTaskCallback(RemoteOperationResult result
) {
1379 mWaitingForOpId
= Long
.MAX_VALUE
;
1380 dismissDialog(WAIT_DIALOG_TAG
);
1382 if (result
.isSuccess()) {
1383 Log_OC
.d(TAG
, "Successful access - time to save the account");
1385 boolean success
= false
;
1387 if (mAction
== ACTION_CREATE
) {
1388 success
= createAccount(result
);
1392 updateAccountAuthentication();
1395 } catch (AccountNotFoundException e
) {
1396 Log_OC
.e(TAG
, "Account " + mAccount
+ " was removed!", e
);
1397 Toast
.makeText(this, R
.string
.auth_account_does_not_exist
,
1398 Toast
.LENGTH_SHORT
).show();
1407 } else if (result
.isServerFail() || result
.isException()) {
1408 /// server errors or exceptions in authorization take to requiring a new check of
1410 mServerIsChecked
= true
;
1411 mServerIsValid
= false
;
1412 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
1414 // update status icon and text
1415 updateServerStatusIconAndText(result
);
1417 mAuthStatusIcon
= 0;
1418 mAuthStatusText
= 0;
1421 // update input controls state
1422 showRefreshButton(true
);
1423 mOkButton
.setEnabled(false
);
1425 // very special case (TODO: move to a common place for all the remote operations)
1426 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1427 showUntrustedCertDialog(result
);
1430 } else { // authorization fail due to client side - probably wrong credentials
1431 updateAuthStatusIconAndText(result
);
1433 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1441 * Updates the authentication token.
1443 * Sets the proper response so that the AccountAuthenticator that started this activity
1444 * saves a new authorization token for mAccount.
1446 * Kills the session kept by OwnCloudClientManager so that a new one will created with
1447 * the new credentials when needed.
1449 private void updateAccountAuthentication() throws AccountNotFoundException
{
1451 Bundle response
= new Bundle();
1452 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1453 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
1455 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
1456 equals(mAuthTokenType
)) {
1457 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1458 // the next line is necessary, notifications are calling directly to the
1459 // AuthenticatorActivity to update, without AccountManager intervention
1460 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1462 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1463 equals(mAuthTokenType
)) {
1465 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1466 // the next line is necessary; by now, notifications are calling directly to the
1467 // AuthenticatorActivity to update, without AccountManager intervention
1468 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1471 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
1472 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
1474 setAccountAuthenticatorResult(response
);
1480 * Creates a new account through the Account Authenticator that started this activity.
1482 * This makes the account permanent.
1484 * TODO Decide how to name the OAuth accounts
1486 private boolean createAccount(RemoteOperationResult authResult
) {
1487 /// create and save new ownCloud account
1488 boolean isOAuth
= AccountTypeUtils
.
1489 getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
);
1490 boolean isSaml
= AccountTypeUtils
.
1491 getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
);
1493 String lastPermanentLocation
= authResult
.getLastPermanentLocation();
1494 if (lastPermanentLocation
!= null
) {
1495 mServerInfo
.mBaseUrl
= AccountUtils
.trimWebdavSuffix(lastPermanentLocation
);
1498 Uri uri
= Uri
.parse(mServerInfo
.mBaseUrl
);
1499 String username
= mUsernameInput
.getText().toString().trim();
1501 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1503 String accountName
= com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.
1504 buildAccountName(uri
, username
);
1505 Account newAccount
= new Account(accountName
, MainApp
.getAccountType());
1506 if (AccountUtils
.exists(newAccount
, getApplicationContext())) {
1507 // fail - not a new account, but an existing one; disallow
1508 RemoteOperationResult result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_NEW
);
1509 updateAuthStatusIconAndText(result
);
1511 Log_OC
.d(TAG
, result
.getLogMessage());
1515 mAccount
= newAccount
;
1517 if (isOAuth
|| isSaml
) {
1518 // with external authorizations, the password is never input in the app
1519 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
);
1521 mAccountMgr
.addAccountExplicitly(
1522 mAccount
, mPasswordInput
.getText().toString(), null
1526 // include account version with the new account
1527 mAccountMgr
.setUserData(
1529 Constants
.KEY_OC_ACCOUNT_VERSION
,
1530 Integer
.toString(AccountUtils
.ACCOUNT_VERSION
)
1533 /// add the new account as default in preferences, if there is none already
1534 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1535 if (defaultAccount
== null
) {
1536 SharedPreferences
.Editor editor
= PreferenceManager
1537 .getDefaultSharedPreferences(this).edit();
1538 editor
.putString("select_oc_account", accountName
);
1542 /// prepare result to return to the Authenticator
1543 // TODO check again what the Authenticator makes with it; probably has the same
1544 // effect as addAccountExplicitly, but it's not well done
1545 final Intent intent
= new Intent();
1546 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, MainApp
.getAccountType());
1547 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1548 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1549 if (isOAuth
|| isSaml
) {
1550 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1552 /// add user data to the new account; TODO probably can be done in the last parameter
1553 // addAccountExplicitly, or in KEY_USERDATA
1554 mAccountMgr
.setUserData(
1555 mAccount
, Constants
.KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion()
1557 mAccountMgr
.setUserData(
1558 mAccount
, Constants
.KEY_OC_BASE_URL
, mServerInfo
.mBaseUrl
1562 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
, "TRUE");
1563 } else if (isOAuth
) {
1564 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
, "TRUE");
1567 setAccountAuthenticatorResult(intent
.getExtras());
1568 setResult(RESULT_OK
, intent
);
1576 * Starts and activity to open the 'new account' page in the ownCloud web site
1578 * @param view 'Account register' button
1580 public void onRegisterClick(View view
) {
1581 Intent register
= new Intent(
1582 Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.welcome_link_url
))
1584 setResult(RESULT_CANCELED
);
1585 startActivity(register
);
1590 * Updates the content and visibility state of the icon and text associated
1591 * to the last check on the ownCloud server.
1594 private void showServerStatus() {
1595 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1596 mServerStatusView
.setVisibility(View
.INVISIBLE
);
1599 mServerStatusView
.setText(mServerStatusText
);
1600 mServerStatusView
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1601 mServerStatusView
.setVisibility(View
.VISIBLE
);
1608 * Updates the content and visibility state of the icon and text associated
1609 * to the interactions with the OAuth authorization server.
1611 private void showAuthStatus() {
1612 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1613 mAuthStatusView
.setVisibility(View
.INVISIBLE
);
1616 mAuthStatusView
.setText(mAuthStatusText
);
1617 mAuthStatusView
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1618 mAuthStatusView
.setVisibility(View
.VISIBLE
);
1623 private void showRefreshButton (boolean show
) {
1625 mRefreshButton
.setVisibility(View
.VISIBLE
);
1627 mRefreshButton
.setVisibility(View
.GONE
);
1632 * Called when the eye icon in the password field is clicked.
1634 * Toggles the visibility of the password in the field.
1636 public void onViewPasswordClick() {
1637 int selectionStart
= mPasswordInput
.getSelectionStart();
1638 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1639 if (isPasswordVisible()) {
1644 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1649 * Called when the checkbox for OAuth authorization is clicked.
1651 * Hides or shows the input fields for user & password.
1653 * @param view 'View password' 'button'
1655 public void onCheckClick(View view
) {
1656 CheckBox oAuth2Check
= (CheckBox
)view
;
1657 if (oAuth2Check
.isChecked()) {
1658 mAuthTokenType
= OAUTH_TOKEN_TYPE
;
1660 mAuthTokenType
= BASIC_TOKEN_TYPE
;
1662 updateAuthenticationPreFragmentVisibility();
1667 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1669 * Used to trigger the authentication check when the user presses 'enter' after writing the
1670 * password, or to throw the server test when the only field on screen is the URL input field.
1673 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1674 if (actionId
== EditorInfo
.IME_ACTION_DONE
&& inputField
!= null
&&
1675 inputField
.equals(mPasswordInput
)) {
1676 if (mOkButton
.isEnabled()) {
1677 mOkButton
.performClick();
1680 } else if (actionId
== EditorInfo
.IME_ACTION_NEXT
&& inputField
!= null
&&
1681 inputField
.equals(mHostUrlInput
)) {
1682 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1683 equals(mAuthTokenType
)) {
1687 return false
; // always return false to grant that the software keyboard is hidden anyway
1691 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1693 private int fuzz
= 75;
1699 public boolean onTouch(View view
, MotionEvent event
) {
1700 Drawable rightDrawable
= null
;
1701 if (view
instanceof TextView
) {
1702 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1703 if (drawables
.length
> 2) {
1704 rightDrawable
= drawables
[2];
1707 if (rightDrawable
!= null
) {
1708 final int x
= (int) event
.getX();
1709 final int y
= (int) event
.getY();
1710 final Rect bounds
= rightDrawable
.getBounds();
1711 if ( x
>= (view
.getRight() - bounds
.width() - fuzz
) &&
1712 x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
) &&
1713 y
>= (view
.getPaddingTop() - fuzz
) &&
1714 y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1716 return onDrawableTouch(event
);
1722 public abstract boolean onDrawableTouch(final MotionEvent event
);
1726 private void getRemoteUserNameOperation(String sessionCookie
) {
1728 Intent getUserNameIntent
= new Intent();
1729 getUserNameIntent
.setAction(OperationsService
.ACTION_GET_USER_NAME
);
1730 getUserNameIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
1731 getUserNameIntent
.putExtra(OperationsService
.EXTRA_COOKIE
, sessionCookie
);
1733 if (mOperationsServiceBinder
!= null
) {
1734 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getUserNameIntent
);
1740 public void onSsoFinished(String sessionCookie
) {
1741 if (sessionCookie
!= null
&& sessionCookie
.length() > 0) {
1742 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1743 mAuthToken
= sessionCookie
;
1744 getRemoteUserNameOperation(sessionCookie
);
1745 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1746 if (fd
!= null
&& fd
instanceof DialogFragment
) {
1747 Dialog d
= ((DialogFragment
)fd
).getDialog();
1748 if (d
!= null
&& d
.isShowing()) {
1755 Log_OC
.d(TAG
, "SSO failed");
1761 public boolean onTouchEvent(MotionEvent event
) {
1762 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1763 equals(mAuthTokenType
) &&
1764 mHostUrlInput
.hasFocus() && event
.getAction() == MotionEvent
.ACTION_DOWN
) {
1767 return super.onTouchEvent(event
);
1772 * Show untrusted cert dialog
1774 public void showUntrustedCertDialog(
1775 X509Certificate x509Certificate
, SslError error
, SslErrorHandler handler
1777 // Show a dialog with the certificate info
1778 SslUntrustedCertDialog dialog
;
1779 if (x509Certificate
== null
) {
1780 dialog
= SslUntrustedCertDialog
.newInstanceForEmptySslError(error
, handler
);
1782 dialog
= SslUntrustedCertDialog
.
1783 newInstanceForFullSslError(x509Certificate
, error
, handler
);
1785 FragmentManager fm
= getSupportFragmentManager();
1786 FragmentTransaction ft
= fm
.beginTransaction();
1787 ft
.addToBackStack(null
);
1788 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1793 * Show untrusted cert dialog
1795 private void showUntrustedCertDialog(RemoteOperationResult result
) {
1796 // Show a dialog with the certificate info
1797 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.
1798 newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1799 FragmentManager fm
= getSupportFragmentManager();
1800 FragmentTransaction ft
= fm
.beginTransaction();
1801 ft
.addToBackStack(null
);
1802 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1807 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1809 public void onSavedCertificate() {
1810 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1812 // if SAML dialog is not shown,
1813 // the SslDialog was shown due to an SSL error in the server check
1819 * Called from SslValidatorDialog when a new server certificate could not be saved
1820 * when the user requested it.
1823 public void onFailedSavingCertificate() {
1824 dismissDialog(SAML_DIALOG_TAG
);
1825 Toast
.makeText(this, R
.string
.ssl_validator_not_saved
, Toast
.LENGTH_LONG
).show();
1829 public void onCancelCertificate() {
1830 dismissDialog(SAML_DIALOG_TAG
);
1834 private void doOnResumeAndBound() {
1835 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1836 mOperationsServiceBinder
.addOperationListener(AuthenticatorActivity
.this, mHandler
);
1837 if (mWaitingForOpId
<= Integer
.MAX_VALUE
) {
1838 mOperationsServiceBinder
.dispatchResultIfFinished((int)mWaitingForOpId
, this);
1841 if (mPendingAutoCheck
) {
1847 private void dismissDialog(String dialogTag
){
1848 Fragment frag
= getSupportFragmentManager().findFragmentByTag(dialogTag
);
1849 if (frag
!= null
&& frag
instanceof DialogFragment
) {
1850 DialogFragment dialog
= (DialogFragment
) frag
;
1857 * Implements callback methods for service binding.
1859 private class OperationsServiceConnection
implements ServiceConnection
{
1862 public void onServiceConnected(ComponentName component
, IBinder service
) {
1863 if (component
.equals(
1864 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1866 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
1868 doOnResumeAndBound();
1875 public void onServiceDisconnected(ComponentName component
) {
1876 if (component
.equals(
1877 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1879 Log_OC
.e(TAG
, "Operations service crashed");
1880 mOperationsServiceBinder
= null
;
1887 * Create and show dialog for request authentication to the user
1888 * @param webView Web view to emebd into the authentication dialog.
1889 * @param handler Object responsible for catching and recovering HTTP authentication fails.
1891 public void createAuthenticationDialog(WebView webView
, HttpAuthHandler handler
) {
1893 // Show a dialog with the certificate info
1894 CredentialsDialogFragment dialog
=
1895 CredentialsDialogFragment
.newInstanceForCredentials(webView
, handler
);
1896 FragmentManager fm
= getSupportFragmentManager();
1897 FragmentTransaction ft
= fm
.beginTransaction();
1898 ft
.addToBackStack(null
);
1899 dialog
.setCancelable(false
);
1900 dialog
.show(ft
, CREDENTIALS_DIALOG_TAG
);
1902 if (!mIsFirstAuthAttempt
) {
1904 getApplicationContext(),
1905 getText(R
.string
.saml_authentication_wrong_pass
),
1909 mIsFirstAuthAttempt
= false
;
1914 * For retrieving the clicking on authentication cancel button
1916 public void doNegativeAuthenticatioDialogClick(){
1917 mIsFirstAuthAttempt
= true
;