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 java
.security
.cert
.X509Certificate
;
29 import android
.accounts
.Account
;
30 import android
.accounts
.AccountManager
;
31 import android
.app
.Dialog
;
32 import android
.content
.ComponentName
;
33 import android
.content
.Context
;
34 import android
.content
.Intent
;
35 import android
.content
.ServiceConnection
;
36 import android
.content
.SharedPreferences
;
37 import android
.graphics
.Rect
;
38 import android
.graphics
.drawable
.Drawable
;
39 import android
.net
.Uri
;
40 import android
.net
.http
.SslError
;
41 import android
.os
.Bundle
;
42 import android
.os
.Handler
;
43 import android
.os
.IBinder
;
44 import android
.preference
.PreferenceManager
;
45 import android
.support
.v4
.app
.DialogFragment
;
46 import android
.support
.v4
.app
.Fragment
;
47 import android
.support
.v4
.app
.FragmentManager
;
48 import android
.support
.v4
.app
.FragmentTransaction
;
49 import android
.text
.Editable
;
50 import android
.text
.InputType
;
51 import android
.text
.TextWatcher
;
52 import android
.view
.KeyEvent
;
53 import android
.view
.MotionEvent
;
54 import android
.view
.View
;
55 import android
.view
.View
.OnFocusChangeListener
;
56 import android
.view
.View
.OnTouchListener
;
57 import android
.view
.Window
;
58 import android
.view
.inputmethod
.EditorInfo
;
59 import android
.webkit
.HttpAuthHandler
;
60 import android
.webkit
.SslErrorHandler
;
61 import android
.webkit
.WebView
;
62 import android
.widget
.Button
;
63 import android
.widget
.CheckBox
;
64 import android
.widget
.EditText
;
65 import android
.widget
.TextView
;
66 import android
.widget
.TextView
.OnEditorActionListener
;
67 import android
.widget
.Toast
;
69 import com
.owncloud
.android
.MainApp
;
70 import com
.owncloud
.android
.R
;
71 import com
.owncloud
.android
.authentication
.SsoWebViewClient
.SsoWebViewClientListener
;
72 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentials
;
73 import com
.owncloud
.android
.lib
.common
.OwnCloudCredentialsFactory
;
74 import com
.owncloud
.android
.lib
.common
.accounts
.AccountTypeUtils
;
75 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.AccountNotFoundException
;
76 import com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.Constants
;
77 import com
.owncloud
.android
.lib
.common
.network
.CertificateCombinedException
;
78 import com
.owncloud
.android
.lib
.common
.operations
.OnRemoteOperationListener
;
79 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperation
;
80 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
81 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
82 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
83 import com
.owncloud
.android
.lib
.resources
.status
.OwnCloudVersion
;
84 import com
.owncloud
.android
.lib
.resources
.users
.GetRemoteUserNameOperation
;
85 import com
.owncloud
.android
.operations
.DetectAuthenticationMethodOperation
.AuthenticationMethod
;
86 import com
.owncloud
.android
.operations
.GetServerInfoOperation
;
87 import com
.owncloud
.android
.operations
.OAuth2GetAccessToken
;
88 import com
.owncloud
.android
.services
.OperationsService
;
89 import com
.owncloud
.android
.services
.OperationsService
.OperationsServiceBinder
;
90 import com
.owncloud
.android
.ui
.dialog
.CredentialsDialogFragment
;
91 import com
.owncloud
.android
.ui
.dialog
.IndeterminateProgressDialog
;
92 import com
.owncloud
.android
.ui
.dialog
.SamlWebViewDialog
;
93 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
;
94 import com
.owncloud
.android
.ui
.dialog
.SslUntrustedCertDialog
.OnSslUntrustedCertListener
;
95 import com
.owncloud
.android
.utils
.DisplayUtils
;
98 * This Activity is used to add an ownCloud account to the App
100 public class AuthenticatorActivity
extends AccountAuthenticatorActivity
101 implements OnRemoteOperationListener
, OnFocusChangeListener
, OnEditorActionListener
,
102 SsoWebViewClientListener
, OnSslUntrustedCertListener
,
103 AuthenticatorAsyncTask
.OnAuthenticatorTaskListener
{
105 private static final String TAG
= AuthenticatorActivity
.class.getSimpleName();
107 public static final String EXTRA_ACTION
= "ACTION";
108 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
110 private static final String KEY_AUTH_TOKEN_TYPE
= "AUTH_TOKEN_TYPE";
112 private static final String KEY_HOST_URL_TEXT
= "HOST_URL_TEXT";
113 private static final String KEY_OC_VERSION
= "OC_VERSION";
114 private static final String KEY_SERVER_VALID
= "SERVER_VALID";
115 private static final String KEY_SERVER_CHECKED
= "SERVER_CHECKED";
116 private static final String KEY_SERVER_STATUS_TEXT
= "SERVER_STATUS_TEXT";
117 private static final String KEY_SERVER_STATUS_ICON
= "SERVER_STATUS_ICON";
118 private static final String KEY_IS_SSL_CONN
= "IS_SSL_CONN";
119 private static final String KEY_PASSWORD_EXPOSED
= "PASSWORD_VISIBLE";
120 private static final String KEY_AUTH_STATUS_TEXT
= "AUTH_STATUS_TEXT";
121 private static final String KEY_AUTH_STATUS_ICON
= "AUTH_STATUS_ICON";
122 private static final String KEY_SERVER_AUTH_METHOD
= "SERVER_AUTH_METHOD";
123 private static final String KEY_WAITING_FOR_OP_ID
= "WAITING_FOR_OP_ID";
124 private static final String KEY_AUTH_TOKEN
= "AUTH_TOKEN";
126 private static final String AUTH_ON
= "on";
127 private static final String AUTH_OPTIONAL
= "optional";
129 public static final byte ACTION_CREATE
= 0;
130 public static final byte ACTION_UPDATE_TOKEN
= 1; // requested by the user
131 public static final byte ACTION_UPDATE_EXPIRED_TOKEN
= 2; // detected by the app
133 private static final String UNTRUSTED_CERT_DIALOG_TAG
= "UNTRUSTED_CERT_DIALOG";
134 private static final String SAML_DIALOG_TAG
= "SAML_DIALOG";
135 private static final String WAIT_DIALOG_TAG
= "WAIT_DIALOG";
136 private static final String CREDENTIALS_DIALOG_TAG
= "CREDENTIALS_DIALOG";
137 private static final String KEY_AUTH_IS_FIRST_ATTEMPT_TAG
= "KEY_AUTH_IS_FIRST_ATTEMPT";
139 private static final String KEY_USERNAME
= "USERNAME";
140 private static final String KEY_PASSWORD
= "PASSWORD";
141 private static final String KEY_ASYNC_TASK_IN_PROGRESS
= "AUTH_IN_PROGRESS";
143 /// parameters from EXTRAs in starter Intent
144 private byte mAction
;
145 private Account mAccount
;
146 private String mAuthTokenType
;
149 /// activity-level references / state
150 private final Handler mHandler
= new Handler();
151 private ServiceConnection mOperationsServiceConnection
= null
;
152 private OperationsServiceBinder mOperationsServiceBinder
= null
;
153 private AccountManager mAccountMgr
;
154 private Uri mNewCapturedUriFromOAuth2Redirection
;
157 /// Server PRE-Fragment elements
158 private EditText mHostUrlInput
;
159 private View mRefreshButton
;
160 private TextView mServerStatusView
;
162 private TextWatcher mHostUrlInputWatcher
;
163 private int mServerStatusText
= 0, mServerStatusIcon
= 0;
165 private boolean mServerIsChecked
= false
;
166 private boolean mServerIsValid
= false
;
167 private boolean mPendingAutoCheck
= false
;
169 private GetServerInfoOperation
.ServerInfo mServerInfo
=
170 new GetServerInfoOperation
.ServerInfo();
173 /// Authentication PRE-Fragment elements
174 private CheckBox mOAuth2Check
;
175 private TextView mOAuthAuthEndpointText
;
176 private TextView mOAuthTokenEndpointText
;
177 private EditText mUsernameInput
;
178 private EditText mPasswordInput
;
179 private View mOkButton
;
180 private TextView mAuthStatusView
;
182 private int mAuthStatusText
= 0, mAuthStatusIcon
= 0;
184 private String mAuthToken
= "";
185 private AuthenticatorAsyncTask mAsyncTask
;
187 private boolean mIsFirstAuthAttempt
;
189 /// Identifier of operation in progress which result shouldn't be lost
190 private long mWaitingForOpId
= Long
.MAX_VALUE
;
192 private final String BASIC_TOKEN_TYPE
= AccountTypeUtils
.getAuthTokenTypePass(
193 MainApp
.getAccountType());
194 private final String OAUTH_TOKEN_TYPE
= AccountTypeUtils
.getAuthTokenTypeAccessToken(
195 MainApp
.getAccountType());
196 private final String SAML_TOKEN_TYPE
=
197 AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType());
203 * IMPORTANT ENTRY POINT 1: activity is shown to the user
206 protected void onCreate(Bundle savedInstanceState
) {
207 //Log_OC.wtf(TAG, "onCreate init");
208 super.onCreate(savedInstanceState
);
210 // Workaround, for fixing a problem with Android Library Suppor v7 19
211 //getWindow().requestFeature(Window.FEATURE_NO_TITLE);
212 if (getSupportActionBar() != null
) {
213 getSupportActionBar().hide();
215 getSupportActionBar().setDisplayHomeAsUpEnabled(false
);
216 getSupportActionBar().setDisplayShowHomeEnabled(false
);
217 getSupportActionBar().setDisplayShowTitleEnabled(false
);
220 mIsFirstAuthAttempt
= true
;
222 // bind to Operations Service
223 mOperationsServiceConnection
= new OperationsServiceConnection();
224 if (!bindService(new Intent(this, OperationsService
.class),
225 mOperationsServiceConnection
,
226 Context
.BIND_AUTO_CREATE
)) {
228 R
.string
.error_cant_bind_to_operations_service
,
234 /// init activity state
235 mAccountMgr
= AccountManager
.get(this);
236 mNewCapturedUriFromOAuth2Redirection
= null
;
239 mAction
= getIntent().getByteExtra(EXTRA_ACTION
, ACTION_CREATE
);
240 mAccount
= getIntent().getExtras().getParcelable(EXTRA_ACCOUNT
);
241 if (savedInstanceState
== null
) {
244 mAuthTokenType
= savedInstanceState
.getString(KEY_AUTH_TOKEN_TYPE
);
245 mWaitingForOpId
= savedInstanceState
.getLong(KEY_WAITING_FOR_OP_ID
);
246 mIsFirstAuthAttempt
= savedInstanceState
.getBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
);
249 /// load user interface
250 setContentView(R
.layout
.account_setup
);
252 /// initialize general UI elements
255 mOkButton
= findViewById(R
.id
.buttonOK
);
257 /// initialize block to be moved to single Fragment to check server and get info about it
258 initServerPreFragment(savedInstanceState
);
260 /// initialize block to be moved to single Fragment to retrieve and validate credentials
261 initAuthorizationPreFragment(savedInstanceState
);
263 //Log_OC.wtf(TAG, "onCreate end");
266 private void initAuthTokenType() {
268 getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
269 if (mAuthTokenType
== null
) {
270 if (mAccount
!= null
) {
271 boolean oAuthRequired
=
272 (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
) != null
);
273 boolean samlWebSsoRequired
= (
274 mAccountMgr
.getUserData(
275 mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
278 mAuthTokenType
= chooseAuthTokenType(oAuthRequired
, samlWebSsoRequired
);
281 boolean oAuthSupported
= AUTH_ON
.equals(getString(R
.string
.auth_method_oauth2
));
282 boolean samlWebSsoSupported
=
283 AUTH_ON
.equals(getString(R
.string
.auth_method_saml_web_sso
));
284 mAuthTokenType
= chooseAuthTokenType(oAuthSupported
, samlWebSsoSupported
);
289 private String
chooseAuthTokenType(boolean oauth
, boolean saml
) {
291 return SAML_TOKEN_TYPE
;
293 return OAUTH_TOKEN_TYPE
;
295 return BASIC_TOKEN_TYPE
;
301 * Configures elements in the user interface under direct control of the Activity.
303 private void initOverallUi() {
305 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
306 boolean isWelcomeLinkVisible
= getResources().getBoolean(R
.bool
.show_welcome_link
);
308 String instructionsMessageText
= null
;
309 if (mAction
== ACTION_UPDATE_EXPIRED_TOKEN
) {
310 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
311 .equals(mAuthTokenType
)) {
312 instructionsMessageText
= getString(R
.string
.auth_expired_oauth_token_toast
);
314 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType())
315 .equals(mAuthTokenType
)) {
316 instructionsMessageText
= getString(R
.string
.auth_expired_saml_sso_token_toast
);
319 instructionsMessageText
= getString(R
.string
.auth_expired_basic_auth_toast
);
323 /// step 2 - set properties of UI elements (text, visibility, enabled...)
324 Button welcomeLink
= (Button
) findViewById(R
.id
.welcome_link
);
325 welcomeLink
.setVisibility(isWelcomeLinkVisible ? View
.VISIBLE
: View
.GONE
);
327 String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
329 TextView instructionsView
= (TextView
) findViewById(R
.id
.instructions_message
);
330 if (instructionsMessageText
!= null
) {
331 instructionsView
.setVisibility(View
.VISIBLE
);
332 instructionsView
.setText(instructionsMessageText
);
334 instructionsView
.setVisibility(View
.GONE
);
341 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
343 private void initServerPreFragment(Bundle savedInstanceState
) {
345 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
346 boolean isUrlInputAllowed
= getResources().getBoolean(R
.bool
.show_server_url_input
);
347 if (savedInstanceState
== null
) {
348 if (mAccount
!= null
) {
349 mServerInfo
.mBaseUrl
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_BASE_URL
);
350 // TODO do next in a setter for mBaseUrl
351 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
352 String ocVersion
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_VERSION
);
353 if (ocVersion
!= null
) {
354 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
357 mServerInfo
.mBaseUrl
= getString(R
.string
.server_url
).trim();
358 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
361 mServerStatusText
= savedInstanceState
.getInt(KEY_SERVER_STATUS_TEXT
);
362 mServerStatusIcon
= savedInstanceState
.getInt(KEY_SERVER_STATUS_ICON
);
364 mServerIsValid
= savedInstanceState
.getBoolean(KEY_SERVER_VALID
);
365 mServerIsChecked
= savedInstanceState
.getBoolean(KEY_SERVER_CHECKED
);
368 mServerInfo
.mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
369 mServerInfo
.mBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
370 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
371 if (ocVersion
!= null
) {
372 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
374 mServerInfo
.mAuthMethod
= AuthenticationMethod
.valueOf(
375 savedInstanceState
.getString(KEY_SERVER_AUTH_METHOD
));
379 /// step 2 - set properties of UI elements (text, visibility, enabled...)
380 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
381 // Convert IDN to Unicode
382 mHostUrlInput
.setText(DisplayUtils
.convertIdn(mServerInfo
.mBaseUrl
, false
));
383 if (mAction
!= ACTION_CREATE
) {
384 /// lock things that should not change
385 mHostUrlInput
.setEnabled(false
);
386 mHostUrlInput
.setFocusable(false
);
388 if (isUrlInputAllowed
) {
389 mRefreshButton
= findViewById(R
.id
.embeddedRefreshButton
);
391 findViewById(R
.id
.hostUrlFrame
).setVisibility(View
.GONE
);
392 mRefreshButton
= findViewById(R
.id
.centeredRefreshButton
);
394 showRefreshButton(mServerIsChecked
&& !mServerIsValid
&&
395 mWaitingForOpId
> Integer
.MAX_VALUE
);
396 mServerStatusView
= (TextView
) findViewById(R
.id
.server_status_text
);
399 /// step 3 - bind some listeners and options
400 mHostUrlInput
.setImeOptions(EditorInfo
.IME_ACTION_NEXT
);
401 mHostUrlInput
.setOnEditorActionListener(this);
403 /// step 4 - create listeners that will be bound at onResume
404 mHostUrlInputWatcher
= new TextWatcher() {
407 public void afterTextChanged(Editable s
) {
408 if (mOkButton
.isEnabled() &&
409 !mServerInfo
.mBaseUrl
.equals(
410 normalizeUrl(s
.toString(), mServerInfo
.mIsSslConn
))) {
411 mOkButton
.setEnabled(false
);
416 public void beforeTextChanged(CharSequence s
, int start
, int count
, int after
) {
420 public void onTextChanged(CharSequence s
, int start
, int before
, int count
) {
421 if (mAuthStatusIcon
!= 0) {
422 Log_OC
.d(TAG
, "onTextChanged: hiding authentication status");
431 // TODO find out if this is really necessary, or if it can done in a different way
432 findViewById(R
.id
.scroll
).setOnTouchListener(new OnTouchListener() {
434 public boolean onTouch(View view
, MotionEvent event
) {
435 if (event
.getAction() == MotionEvent
.ACTION_DOWN
) {
437 AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(
438 MainApp
.getAccountType()
439 ).equals(mAuthTokenType
) &&
440 mHostUrlInput
.hasFocus()
450 /// step 4 - mark automatic check to be started when OperationsService is ready
451 mPendingAutoCheck
= (savedInstanceState
== null
&&
452 (mAction
!= ACTION_CREATE
|| !isUrlInputAllowed
));
458 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
460 private void initAuthorizationPreFragment(Bundle savedInstanceState
) {
462 /// step 0 - get UI elements in layout
463 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
464 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
465 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
466 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
467 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
468 mAuthStatusView
= (TextView
) findViewById(R
.id
.auth_status_text
);
470 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
471 String presetUserName
= null
;
472 boolean isPasswordExposed
= false
;
473 if (savedInstanceState
== null
) {
474 if (mAccount
!= null
) {
475 presetUserName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
479 isPasswordExposed
= savedInstanceState
.getBoolean(KEY_PASSWORD_EXPOSED
, false
);
480 mAuthStatusText
= savedInstanceState
.getInt(KEY_AUTH_STATUS_TEXT
);
481 mAuthStatusIcon
= savedInstanceState
.getInt(KEY_AUTH_STATUS_ICON
);
482 mAuthToken
= savedInstanceState
.getString(KEY_AUTH_TOKEN
);
485 /// step 2 - set properties of UI elements (text, visibility, enabled...)
486 mOAuth2Check
.setChecked(
487 AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
488 .equals(mAuthTokenType
));
489 if (presetUserName
!= null
) {
490 mUsernameInput
.setText(presetUserName
);
492 if (mAction
!= ACTION_CREATE
) {
493 mUsernameInput
.setEnabled(false
);
494 mUsernameInput
.setFocusable(false
);
496 mPasswordInput
.setText(""); // clean password to avoid social hacking
497 if (isPasswordExposed
) {
500 updateAuthenticationPreFragmentVisibility();
502 mOkButton
.setEnabled(mServerIsValid
);
505 /// step 3 - bind listeners
506 // bindings for password input field
507 mPasswordInput
.setOnFocusChangeListener(this);
508 mPasswordInput
.setImeOptions(EditorInfo
.IME_ACTION_DONE
);
509 mPasswordInput
.setOnEditorActionListener(this);
510 mPasswordInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
512 public boolean onDrawableTouch(final MotionEvent event
) {
513 if (event
.getAction() == MotionEvent
.ACTION_UP
) {
514 AuthenticatorActivity
.this.onViewPasswordClick();
524 * Changes the visibility of input elements depending on
525 * the current authorization method.
527 private void updateAuthenticationPreFragmentVisibility () {
528 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
529 equals(mAuthTokenType
)) {
530 // SAML-based web Single Sign On
531 mOAuth2Check
.setVisibility(View
.GONE
);
532 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
533 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
534 mUsernameInput
.setVisibility(View
.GONE
);
535 mPasswordInput
.setVisibility(View
.GONE
);
538 if (mAction
== ACTION_CREATE
&&
539 AUTH_OPTIONAL
.equals(getString(R
.string
.auth_method_oauth2
))) {
540 mOAuth2Check
.setVisibility(View
.VISIBLE
);
542 mOAuth2Check
.setVisibility(View
.GONE
);
545 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
546 equals(mAuthTokenType
)) {
547 // OAuth 2 authorization
549 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
550 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
551 mUsernameInput
.setVisibility(View
.GONE
);
552 mPasswordInput
.setVisibility(View
.GONE
);
555 // basic HTTP authorization
556 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
557 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
558 mUsernameInput
.setVisibility(View
.VISIBLE
);
559 mPasswordInput
.setVisibility(View
.VISIBLE
);
567 * Saves relevant state before {@link #onPause()}
569 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag,
570 * intended to defer the processing of the redirection caught in
571 * {@link #onNewIntent(Intent)} until {@link #onResume()}
573 * See {@link #onSaveInstanceState(Bundle)}
576 protected void onSaveInstanceState(Bundle outState
) {
577 //Log_OC.wtf(TAG, "onSaveInstanceState init" );
578 super.onSaveInstanceState(outState
);
581 outState
.putString(KEY_AUTH_TOKEN_TYPE
, mAuthTokenType
);
582 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mWaitingForOpId
);
584 /// Server PRE-fragment state
585 outState
.putInt(KEY_SERVER_STATUS_TEXT
, mServerStatusText
);
586 outState
.putInt(KEY_SERVER_STATUS_ICON
, mServerStatusIcon
);
587 outState
.putBoolean(KEY_SERVER_CHECKED
, mServerIsChecked
);
588 outState
.putBoolean(KEY_SERVER_VALID
, mServerIsValid
);
589 outState
.putBoolean(KEY_IS_SSL_CONN
, mServerInfo
.mIsSslConn
);
590 outState
.putString(KEY_HOST_URL_TEXT
, mServerInfo
.mBaseUrl
);
591 if (mServerInfo
.mVersion
!= null
) {
592 outState
.putString(KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion());
594 outState
.putString(KEY_SERVER_AUTH_METHOD
, mServerInfo
.mAuthMethod
.name());
596 /// Authentication PRE-fragment state
597 outState
.putBoolean(KEY_PASSWORD_EXPOSED
, isPasswordVisible());
598 outState
.putInt(KEY_AUTH_STATUS_ICON
, mAuthStatusIcon
);
599 outState
.putInt(KEY_AUTH_STATUS_TEXT
, mAuthStatusText
);
600 outState
.putString(KEY_AUTH_TOKEN
, mAuthToken
);
603 outState
.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
, mIsFirstAuthAttempt
);
605 /// AsyncTask (User and password)
606 outState
.putString(KEY_USERNAME
, mUsernameInput
.getText().toString());
607 outState
.putString(KEY_PASSWORD
, mPasswordInput
.getText().toString());
609 if (mAsyncTask
!= null
) {
610 mAsyncTask
.cancel(true
);
611 outState
.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS
, true
);
613 outState
.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS
, false
);
617 //Log_OC.wtf(TAG, "onSaveInstanceState end" );
621 public void onRestoreInstanceState(Bundle savedInstanceState
) {
622 super.onRestoreInstanceState(savedInstanceState
);
625 boolean inProgress
= savedInstanceState
.getBoolean(KEY_ASYNC_TASK_IN_PROGRESS
);
627 String username
= savedInstanceState
.getString(KEY_USERNAME
);
628 String password
= savedInstanceState
.getString(KEY_PASSWORD
);
630 OwnCloudCredentials credentials
= null
;
631 if (BASIC_TOKEN_TYPE
.equals(mAuthTokenType
)) {
632 credentials
= OwnCloudCredentialsFactory
.newBasicCredentials(username
, password
);
634 } else if (OAUTH_TOKEN_TYPE
.equals(mAuthTokenType
)) {
635 credentials
= OwnCloudCredentialsFactory
.newBearerCredentials(mAuthToken
);
638 accessRootFolder(credentials
);
643 * The redirection triggered by the OAuth authentication server as response to the
644 * GET AUTHORIZATION request is caught here.
646 * To make this possible, this activity needs to be qualified with android:launchMode =
647 * "singleTask" in the AndroidManifest.xml file.
650 protected void onNewIntent (Intent intent
) {
651 Log_OC
.d(TAG
, "onNewIntent()");
652 Uri data
= intent
.getData();
653 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
654 mNewCapturedUriFromOAuth2Redirection
= data
;
660 * The redirection triggered by the OAuth authentication server as response to the
661 * GET AUTHORIZATION, and deferred in {@link #onNewIntent(Intent)}, is processed here.
664 protected void onResume() {
667 // bound here to avoid spurious changes triggered by Android on device rotations
668 mHostUrlInput
.setOnFocusChangeListener(this);
669 mHostUrlInput
.addTextChangedListener(mHostUrlInputWatcher
);
671 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
672 getOAuth2AccessTokenFromCapturedRedirection();
675 if (mOperationsServiceBinder
!= null
) {
676 doOnResumeAndBound();
683 protected void onPause() {
684 if (mOperationsServiceBinder
!= null
) {
685 mOperationsServiceBinder
.removeOperationListener(this);
688 mHostUrlInput
.removeTextChangedListener(mHostUrlInputWatcher
);
689 mHostUrlInput
.setOnFocusChangeListener(null
);
695 protected void onDestroy() {
697 mHostUrlInputWatcher
= null
;
699 if (mOperationsServiceConnection
!= null
) {
700 unbindService(mOperationsServiceConnection
);
701 mOperationsServiceBinder
= null
;
708 * Parses the redirection with the response to the GET AUTHORIZATION request to the
709 * oAuth server and requests for the access token (GET ACCESS TOKEN)
711 private void getOAuth2AccessTokenFromCapturedRedirection() {
712 /// Parse data from OAuth redirection
713 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
714 mNewCapturedUriFromOAuth2Redirection
= null
;
716 /// Showing the dialog with instructions for the user.
717 IndeterminateProgressDialog dialog
=
718 IndeterminateProgressDialog
.newInstance(R
.string
.auth_getting_authorization
, true
);
719 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
721 /// GET ACCESS TOKEN to the oAuth server
722 Intent getServerInfoIntent
= new Intent();
723 getServerInfoIntent
.setAction(OperationsService
.ACTION_OAUTH2_GET_ACCESS_TOKEN
);
725 getServerInfoIntent
.putExtra(
726 OperationsService
.EXTRA_SERVER_URL
,
727 mOAuthTokenEndpointText
.getText().toString().trim());
729 getServerInfoIntent
.putExtra(
730 OperationsService
.EXTRA_OAUTH2_QUERY_PARAMETERS
,
733 if (mOperationsServiceBinder
!= null
) {
734 //Log_OC.wtf(TAG, "getting access token..." );
735 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
742 * Handles the change of focus on the text inputs for the server URL and the password
744 public void onFocusChange(View view
, boolean hasFocus
) {
745 if (view
.getId() == R
.id
.hostUrlInput
) {
747 onUrlInputFocusLost();
750 showRefreshButton(false
);
753 } else if (view
.getId() == R
.id
.account_password
) {
754 onPasswordFocusChanged(hasFocus
);
760 * Handles changes in focus on the text input for the server URL.
762 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
763 * other field. The operation to check the existence of the server in the entered URL is
766 * When hasFocus: user 'comes back' to write again the server URL.
768 private void onUrlInputFocusLost() {
769 if (!mServerInfo
.mBaseUrl
.equals(
770 normalizeUrl(mHostUrlInput
.getText().toString(), mServerInfo
.mIsSslConn
))) {
771 // check server again only if the user changed something in the field
774 mOkButton
.setEnabled(mServerIsValid
);
775 showRefreshButton(!mServerIsValid
);
780 private void checkOcServer() {
781 String uri
= mHostUrlInput
.getText().toString().trim();
782 mServerIsValid
= false
;
783 mServerIsChecked
= false
;
784 mOkButton
.setEnabled(false
);
785 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
786 showRefreshButton(false
);
788 if (uri
.length() != 0) {
789 // Handle internationalized domain names
790 uri
= DisplayUtils
.convertIdn(uri
, true
);
792 mServerStatusText
= R
.string
.auth_testing_connection
;
793 mServerStatusIcon
= R
.drawable
.progress_small
;
796 Intent getServerInfoIntent
= new Intent();
797 getServerInfoIntent
.setAction(OperationsService
.ACTION_GET_SERVER_INFO
);
798 getServerInfoIntent
.putExtra(
799 OperationsService
.EXTRA_SERVER_URL
,
800 normalizeUrlSuffix(uri
)
802 if (mOperationsServiceBinder
!= null
) {
803 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
805 Log_OC
.wtf(TAG
, "Server check tried with OperationService unbound!" );
809 mServerStatusText
= 0;
810 mServerStatusIcon
= 0;
817 * Handles changes in focus on the text input for the password (basic authorization).
819 * When (hasFocus), the button to toggle password visibility is shown.
821 * When (!hasFocus), the button is made invisible and the password is hidden.
823 * @param hasFocus 'True' if focus is received, 'false' if is lost
825 private void onPasswordFocusChanged(boolean hasFocus
) {
827 showViewPasswordButton();
830 hidePasswordButton();
835 private void showViewPasswordButton() {
836 int drawable
= R
.drawable
.ic_view
;
837 if (isPasswordVisible()) {
838 drawable
= R
.drawable
.ic_hide
;
840 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable
, 0);
843 private boolean isPasswordVisible() {
844 return ((mPasswordInput
.getInputType() & InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) ==
845 InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
848 private void hidePasswordButton() {
849 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
852 private void showPassword() {
853 mPasswordInput
.setInputType(
854 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
856 showViewPasswordButton();
859 private void hidePassword() {
860 mPasswordInput
.setInputType(
861 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
863 showViewPasswordButton();
867 * Checks the credentials of the user in the root of the ownCloud server
868 * before creating a new local account.
870 * For basic authorization, a check of existence of the root folder is
873 * For OAuth, starts the flow to get an access token; the credentials test
874 * is postponed until it is available.
876 * IMPORTANT ENTRY POINT 4
878 * @param view OK button
880 public void onOkClick(View view
) {
881 // this check should be unnecessary
882 if (mServerInfo
.mVersion
== null
||
883 !mServerInfo
.mVersion
.isVersionValid() ||
884 mServerInfo
.mBaseUrl
== null
||
885 mServerInfo
.mBaseUrl
.length() == 0) {
886 mServerStatusIcon
= R
.drawable
.common_error
;
887 mServerStatusText
= R
.string
.auth_wtf_reenter_URL
;
889 mOkButton
.setEnabled(false
);
893 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
894 equals(mAuthTokenType
)) {
896 startOauthorization();
897 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
898 equals(mAuthTokenType
)) {
900 startSamlBasedFederatedSingleSignOnAuthorization();
902 checkBasicAuthorization();
908 * Tests the credentials entered by the user performing a check of existence on
909 * the root folder of the ownCloud server.
911 private void checkBasicAuthorization() {
912 /// get basic credentials entered by user
913 String username
= mUsernameInput
.getText().toString();
914 String password
= mPasswordInput
.getText().toString();
916 /// be gentle with the user
917 IndeterminateProgressDialog dialog
=
918 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
919 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
921 /// validate credentials accessing the root folder
922 OwnCloudCredentials credentials
= OwnCloudCredentialsFactory
.newBasicCredentials(username
,
924 accessRootFolder(credentials
);
927 private void accessRootFolder(OwnCloudCredentials credentials
) {
928 mAsyncTask
= new AuthenticatorAsyncTask(this);
929 Object
[] params
= { mServerInfo
.mBaseUrl
, credentials
};
930 mAsyncTask
.execute(params
);
935 * Starts the OAuth 'grant type' flow to get an access token, with
936 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
938 private void startOauthorization() {
939 // be gentle with the user
940 mAuthStatusIcon
= R
.drawable
.progress_small
;
941 mAuthStatusText
= R
.string
.oauth_login_connection
;
944 // GET AUTHORIZATION request
945 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
946 Uri
.Builder uriBuilder
= uri
.buildUpon();
947 uriBuilder
.appendQueryParameter(
948 OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
)
950 uriBuilder
.appendQueryParameter(
951 OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
)
953 uriBuilder
.appendQueryParameter(
954 OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
)
956 uriBuilder
.appendQueryParameter(
957 OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
)
959 uri
= uriBuilder
.build();
960 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
961 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
967 * Starts the Web Single Sign On flow to get access to the root folder
970 private void startSamlBasedFederatedSingleSignOnAuthorization() {
971 /// be gentle with the user
972 mAuthStatusIcon
= R
.drawable
.progress_small
;
973 mAuthStatusText
= R
.string
.auth_connecting_auth_server
;
976 /// Show SAML-based SSO web dialog
977 String targetUrl
= mServerInfo
.mBaseUrl
978 + AccountUtils
.getWebdavPath(mServerInfo
.mVersion
, mAuthTokenType
);
979 SamlWebViewDialog dialog
= SamlWebViewDialog
.newInstance(targetUrl
, targetUrl
);
980 dialog
.show(getSupportFragmentManager(), SAML_DIALOG_TAG
);
984 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
986 * Dispatches the operation flow to the right method.
989 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
991 if (operation
instanceof GetServerInfoOperation
) {
992 if (operation
.hashCode() == mWaitingForOpId
) {
993 onGetServerInfoFinish(result
);
994 } // else nothing ; only the last check operation is considered;
995 // multiple can be started if the user amends a URL quickly
997 } else if (operation
instanceof OAuth2GetAccessToken
) {
998 onGetOAuthAccessTokenFinish(result
);
1000 } else if (operation
instanceof GetRemoteUserNameOperation
) {
1001 onGetUserNameFinish(result
);
1006 private void onGetUserNameFinish(RemoteOperationResult result
) {
1007 mWaitingForOpId
= Long
.MAX_VALUE
;
1008 if (result
.isSuccess()) {
1009 boolean success
= false
;
1010 String username
= (String
) result
.getData().get(0);
1012 if ( mAction
== ACTION_CREATE
) {
1013 mUsernameInput
.setText(username
);
1014 success
= createAccount(result
);
1017 if (!mUsernameInput
.getText().toString().equals(username
)) {
1018 // fail - not a new account, but an existing one; disallow
1019 result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_THE_SAME
);
1021 updateAuthStatusIconAndText(result
);
1023 Log_OC
.d(TAG
, result
.getLogMessage());
1026 updateAccountAuthentication();
1029 } catch (AccountNotFoundException e
) {
1030 Log_OC
.e(TAG
, "Account " + mAccount
+ " was removed!", e
);
1031 Toast
.makeText(this, R
.string
.auth_account_does_not_exist
,
1032 Toast
.LENGTH_SHORT
).show();
1041 updateStatusIconFailUserName();
1043 Log_OC
.e(TAG
, "Access to user name failed: " + result
.getLogMessage());
1049 * Processes the result of the server check performed when the user finishes the enter of the
1052 * @param result Result of the check.
1054 private void onGetServerInfoFinish(RemoteOperationResult result
) {
1055 /// update activity state
1056 mServerIsChecked
= true
;
1057 mWaitingForOpId
= Long
.MAX_VALUE
;
1059 // update server status, but don't show it yet
1060 updateServerStatusIconAndText(result
);
1062 if (result
.isSuccess()) {
1064 // 1. connection succeeded, and we know if it's SSL or not
1065 // 2. server is installed
1066 // 3. we got the server version
1067 // 4. we got the authentication method required by the server
1068 mServerInfo
= (GetServerInfoOperation
.ServerInfo
) (result
.getData().get(0));
1070 if (!authSupported(mServerInfo
.mAuthMethod
)) {
1072 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1073 mServerIsValid
= false
;
1076 mServerIsValid
= true
;
1080 mServerIsValid
= false
;
1084 showRefreshButton(!mServerIsValid
);
1086 mOkButton
.setEnabled(mServerIsValid
);
1088 /// very special case (TODO: move to a common place for all the remote operations)
1089 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1090 showUntrustedCertDialog(result
);
1095 private boolean authSupported(AuthenticationMethod authMethod
) {
1096 return (( BASIC_TOKEN_TYPE
.equals(mAuthTokenType
) &&
1097 AuthenticationMethod
.BASIC_HTTP_AUTH
.equals(authMethod
) ) ||
1098 ( OAUTH_TOKEN_TYPE
.equals(mAuthTokenType
) &&
1099 AuthenticationMethod
.BEARER_TOKEN
.equals(authMethod
)) ||
1100 ( SAML_TOKEN_TYPE
.equals(mAuthTokenType
) &&
1101 AuthenticationMethod
.SAML_WEB_SSO
.equals(authMethod
))
1106 // TODO remove, if possible
1107 private String
normalizeUrl(String url
, boolean sslWhenUnprefixed
) {
1108 if (url
!= null
&& url
.length() > 0) {
1110 if (!url
.toLowerCase().startsWith("http://") &&
1111 !url
.toLowerCase().startsWith("https://")) {
1112 if (sslWhenUnprefixed
) {
1113 url
= "https://" + url
;
1115 url
= "http://" + url
;
1119 url
= normalizeUrlSuffix(url
);
1121 return (url
!= null ? url
: "");
1125 private String
normalizeUrlSuffix(String url
) {
1126 if (url
.endsWith("/")) {
1127 url
= url
.substring(0, url
.length() - 1);
1129 url
= trimUrlWebdav(url
);
1134 // TODO remove, if possible
1135 private String
trimUrlWebdav(String url
){
1136 if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_4_0_AND_LATER
)){
1137 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_4_0_AND_LATER
.length());
1139 return (url
!= null ? url
: "");
1144 * Chooses the right icon and text to show to the user for the received operation result.
1146 * @param result Result of a remote operation performed in this activity
1148 private void updateServerStatusIconAndText(RemoteOperationResult result
) {
1149 mServerStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1151 switch (result
.getCode()) {
1153 mServerStatusIcon
= android
.R
.drawable
.ic_secure
;
1154 mServerStatusText
= R
.string
.auth_secure_connection
;
1159 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1160 mServerStatusText
= R
.string
.auth_connection_established
;
1161 mServerStatusIcon
= R
.drawable
.ic_ok
;
1163 mServerStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1164 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1168 case NO_NETWORK_CONNECTION
:
1169 mServerStatusIcon
= R
.drawable
.no_network
;
1170 mServerStatusText
= R
.string
.auth_no_net_conn_title
;
1173 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1174 mServerStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1176 case BAD_OC_VERSION
:
1177 mServerStatusText
= R
.string
.auth_bad_oc_version_title
;
1179 case WRONG_CONNECTION
:
1180 mServerStatusText
= R
.string
.auth_wrong_connection_title
;
1183 mServerStatusText
= R
.string
.auth_timeout_title
;
1185 case INCORRECT_ADDRESS
:
1186 mServerStatusText
= R
.string
.auth_incorrect_address_title
;
1189 mServerStatusText
= R
.string
.auth_ssl_general_error_title
;
1192 mServerStatusText
= R
.string
.auth_unauthorized
;
1194 case HOST_NOT_AVAILABLE
:
1195 mServerStatusText
= R
.string
.auth_unknown_host_title
;
1197 case INSTANCE_NOT_CONFIGURED
:
1198 mServerStatusText
= R
.string
.auth_not_configured_title
;
1200 case FILE_NOT_FOUND
:
1201 mServerStatusText
= R
.string
.auth_incorrect_path_title
;
1204 mServerStatusText
= R
.string
.auth_oauth_error
;
1206 case OAUTH2_ERROR_ACCESS_DENIED
:
1207 mServerStatusText
= R
.string
.auth_oauth_error_access_denied
;
1209 case UNHANDLED_HTTP_CODE
:
1211 mServerStatusText
= R
.string
.auth_unknown_error_title
;
1213 case OK_REDIRECT_TO_NON_SECURE_CONNECTION
:
1214 mServerStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1215 mServerStatusText
= R
.string
.auth_redirect_non_secure_connection_title
;
1218 mServerStatusText
= 0;
1219 mServerStatusIcon
= 0;
1225 * Chooses the right icon and text to show to the user for the received operation result.
1227 * @param result Result of a remote operation performed in this activity
1229 private void updateAuthStatusIconAndText(RemoteOperationResult result
) {
1230 mAuthStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1232 switch (result
.getCode()) {
1234 mAuthStatusIcon
= android
.R
.drawable
.ic_secure
;
1235 mAuthStatusText
= R
.string
.auth_secure_connection
;
1240 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1241 mAuthStatusText
= R
.string
.auth_connection_established
;
1242 mAuthStatusIcon
= R
.drawable
.ic_ok
;
1244 mAuthStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1245 mAuthStatusIcon
= android
.R
.drawable
.ic_partial_secure
;
1249 case NO_NETWORK_CONNECTION
:
1250 mAuthStatusIcon
= R
.drawable
.no_network
;
1251 mAuthStatusText
= R
.string
.auth_no_net_conn_title
;
1254 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1255 mAuthStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1257 case BAD_OC_VERSION
:
1258 mAuthStatusText
= R
.string
.auth_bad_oc_version_title
;
1260 case WRONG_CONNECTION
:
1261 mAuthStatusText
= R
.string
.auth_wrong_connection_title
;
1264 mAuthStatusText
= R
.string
.auth_timeout_title
;
1266 case INCORRECT_ADDRESS
:
1267 mAuthStatusText
= R
.string
.auth_incorrect_address_title
;
1270 mAuthStatusText
= R
.string
.auth_ssl_general_error_title
;
1273 mAuthStatusText
= R
.string
.auth_unauthorized
;
1275 case HOST_NOT_AVAILABLE
:
1276 mAuthStatusText
= R
.string
.auth_unknown_host_title
;
1278 case INSTANCE_NOT_CONFIGURED
:
1279 mAuthStatusText
= R
.string
.auth_not_configured_title
;
1281 case FILE_NOT_FOUND
:
1282 mAuthStatusText
= R
.string
.auth_incorrect_path_title
;
1285 mAuthStatusText
= R
.string
.auth_oauth_error
;
1287 case OAUTH2_ERROR_ACCESS_DENIED
:
1288 mAuthStatusText
= R
.string
.auth_oauth_error_access_denied
;
1290 case ACCOUNT_NOT_NEW
:
1291 mAuthStatusText
= R
.string
.auth_account_not_new
;
1293 case ACCOUNT_NOT_THE_SAME
:
1294 mAuthStatusText
= R
.string
.auth_account_not_the_same
;
1296 case UNHANDLED_HTTP_CODE
:
1298 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
1301 mAuthStatusText
= 0;
1302 mAuthStatusIcon
= 0;
1307 private void updateStatusIconFailUserName(){
1308 mAuthStatusIcon
= R
.drawable
.common_error
;
1309 mAuthStatusText
= R
.string
.auth_fail_get_user_name
;
1312 private void updateServerStatusIconNoRegularAuth(){
1313 mServerStatusIcon
= R
.drawable
.common_error
;
1314 mServerStatusText
= R
.string
.auth_can_not_auth_against_server
;
1318 * Processes the result of the request for and access token send
1319 * to an OAuth authorization server.
1321 * @param result Result of the operation.
1323 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result
) {
1324 mWaitingForOpId
= Long
.MAX_VALUE
;
1325 dismissDialog(WAIT_DIALOG_TAG
);
1327 if (result
.isSuccess()) {
1328 /// be gentle with the user
1329 IndeterminateProgressDialog dialog
=
1330 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
1331 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
1333 /// time to test the retrieved access token on the ownCloud server
1334 @SuppressWarnings("unchecked")
1335 Map
<String
, String
> tokens
= (Map
<String
, String
>)(result
.getData().get(0));
1336 mAuthToken
= tokens
.get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
1337 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mAuthToken
);
1339 /// validate token accessing to root folder / getting session
1340 OwnCloudCredentials credentials
= OwnCloudCredentialsFactory
.newBearerCredentials(
1342 accessRootFolder(credentials
);
1345 updateAuthStatusIconAndText(result
);
1347 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1353 * Processes the result of the access check performed to try the user credentials.
1355 * Creates a new account through the AccountManager.
1357 * @param result Result of the operation.
1360 public void onAuthenticatorTaskCallback(RemoteOperationResult result
) {
1361 mWaitingForOpId
= Long
.MAX_VALUE
;
1362 dismissDialog(WAIT_DIALOG_TAG
);
1364 if (result
.isSuccess()) {
1365 Log_OC
.d(TAG
, "Successful access - time to save the account");
1367 boolean success
= false
;
1369 if (mAction
== ACTION_CREATE
) {
1370 success
= createAccount(result
);
1374 updateAccountAuthentication();
1377 } catch (AccountNotFoundException e
) {
1378 Log_OC
.e(TAG
, "Account " + mAccount
+ " was removed!", e
);
1379 Toast
.makeText(this, R
.string
.auth_account_does_not_exist
,
1380 Toast
.LENGTH_SHORT
).show();
1389 } else if (result
.isServerFail() || result
.isException()) {
1390 /// server errors or exceptions in authorization take to requiring a new check of
1392 mServerIsChecked
= true
;
1393 mServerIsValid
= false
;
1394 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
1396 // update status icon and text
1397 updateServerStatusIconAndText(result
);
1399 mAuthStatusIcon
= 0;
1400 mAuthStatusText
= 0;
1403 // update input controls state
1404 showRefreshButton(true
);
1405 mOkButton
.setEnabled(false
);
1407 // very special case (TODO: move to a common place for all the remote operations)
1408 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1409 showUntrustedCertDialog(result
);
1412 } else { // authorization fail due to client side - probably wrong credentials
1413 updateAuthStatusIconAndText(result
);
1415 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1423 * Updates the authentication token.
1425 * Sets the proper response so that the AccountAuthenticator that started this activity
1426 * saves a new authorization token for mAccount.
1428 * Kills the session kept by OwnCloudClientManager so that a new one will created with
1429 * the new credentials when needed.
1431 private void updateAccountAuthentication() throws AccountNotFoundException
{
1433 Bundle response
= new Bundle();
1434 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1435 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
1437 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
1438 equals(mAuthTokenType
)) {
1439 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1440 // the next line is necessary, notifications are calling directly to the
1441 // AuthenticatorActivity to update, without AccountManager intervention
1442 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1444 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1445 equals(mAuthTokenType
)) {
1447 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1448 // the next line is necessary; by now, notifications are calling directly to the
1449 // AuthenticatorActivity to update, without AccountManager intervention
1450 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1453 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
1454 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
1456 setAccountAuthenticatorResult(response
);
1462 * Creates a new account through the Account Authenticator that started this activity.
1464 * This makes the account permanent.
1466 * TODO Decide how to name the OAuth accounts
1468 private boolean createAccount(RemoteOperationResult authResult
) {
1469 /// create and save new ownCloud account
1470 boolean isOAuth
= AccountTypeUtils
.
1471 getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
);
1472 boolean isSaml
= AccountTypeUtils
.
1473 getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
);
1475 String lastPermanentLocation
= authResult
.getLastPermanentLocation();
1476 if (lastPermanentLocation
!= null
) {
1477 mServerInfo
.mBaseUrl
= AccountUtils
.trimWebdavSuffix(lastPermanentLocation
);
1480 Uri uri
= Uri
.parse(mServerInfo
.mBaseUrl
);
1481 String username
= mUsernameInput
.getText().toString().trim();
1483 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1485 String accountName
= com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.
1486 buildAccountName(uri
, username
);
1487 Account newAccount
= new Account(accountName
, MainApp
.getAccountType());
1488 if (AccountUtils
.exists(newAccount
, getApplicationContext())) {
1489 // fail - not a new account, but an existing one; disallow
1490 RemoteOperationResult result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_NEW
);
1491 updateAuthStatusIconAndText(result
);
1493 Log_OC
.d(TAG
, result
.getLogMessage());
1497 mAccount
= newAccount
;
1499 if (isOAuth
|| isSaml
) {
1500 // with external authorizations, the password is never input in the app
1501 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
);
1503 mAccountMgr
.addAccountExplicitly(
1504 mAccount
, mPasswordInput
.getText().toString(), null
1508 // include account version with the new account
1509 mAccountMgr
.setUserData(
1511 Constants
.KEY_OC_ACCOUNT_VERSION
,
1512 Integer
.toString(AccountUtils
.ACCOUNT_VERSION
)
1515 /// add the new account as default in preferences, if there is none already
1516 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1517 if (defaultAccount
== null
) {
1518 SharedPreferences
.Editor editor
= PreferenceManager
1519 .getDefaultSharedPreferences(this).edit();
1520 editor
.putString("select_oc_account", accountName
);
1524 /// prepare result to return to the Authenticator
1525 // TODO check again what the Authenticator makes with it; probably has the same
1526 // effect as addAccountExplicitly, but it's not well done
1527 final Intent intent
= new Intent();
1528 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, MainApp
.getAccountType());
1529 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1530 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1531 if (isOAuth
|| isSaml
) {
1532 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1534 /// add user data to the new account; TODO probably can be done in the last parameter
1535 // addAccountExplicitly, or in KEY_USERDATA
1536 mAccountMgr
.setUserData(
1537 mAccount
, Constants
.KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion()
1539 mAccountMgr
.setUserData(
1540 mAccount
, Constants
.KEY_OC_BASE_URL
, mServerInfo
.mBaseUrl
1544 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
, "TRUE");
1545 } else if (isOAuth
) {
1546 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
, "TRUE");
1549 setAccountAuthenticatorResult(intent
.getExtras());
1550 setResult(RESULT_OK
, intent
);
1558 * Starts and activity to open the 'new account' page in the ownCloud web site
1560 * @param view 'Account register' button
1562 public void onRegisterClick(View view
) {
1563 Intent register
= new Intent(
1564 Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.welcome_link_url
))
1566 setResult(RESULT_CANCELED
);
1567 startActivity(register
);
1572 * Updates the content and visibility state of the icon and text associated
1573 * to the last check on the ownCloud server.
1576 private void showServerStatus() {
1577 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1578 mServerStatusView
.setVisibility(View
.INVISIBLE
);
1581 mServerStatusView
.setText(mServerStatusText
);
1582 mServerStatusView
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1583 mServerStatusView
.setVisibility(View
.VISIBLE
);
1590 * Updates the content and visibility state of the icon and text associated
1591 * to the interactions with the OAuth authorization server.
1593 private void showAuthStatus() {
1594 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1595 mAuthStatusView
.setVisibility(View
.INVISIBLE
);
1598 mAuthStatusView
.setText(mAuthStatusText
);
1599 mAuthStatusView
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1600 mAuthStatusView
.setVisibility(View
.VISIBLE
);
1605 private void showRefreshButton (boolean show
) {
1607 mRefreshButton
.setVisibility(View
.VISIBLE
);
1609 mRefreshButton
.setVisibility(View
.GONE
);
1614 * Called when the refresh button in the input field for ownCloud host is clicked.
1616 * Performs a new check on the URL in the input field.
1618 * @param view Refresh 'button'
1620 public void onRefreshClick(View view
) {
1626 * Called when the eye icon in the password field is clicked.
1628 * Toggles the visibility of the password in the field.
1630 public void onViewPasswordClick() {
1631 int selectionStart
= mPasswordInput
.getSelectionStart();
1632 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1633 if (isPasswordVisible()) {
1638 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1643 * Called when the checkbox for OAuth authorization is clicked.
1645 * Hides or shows the input fields for user & password.
1647 * @param view 'View password' 'button'
1649 public void onCheckClick(View view
) {
1650 CheckBox oAuth2Check
= (CheckBox
)view
;
1651 if (oAuth2Check
.isChecked()) {
1652 mAuthTokenType
= OAUTH_TOKEN_TYPE
;
1654 mAuthTokenType
= BASIC_TOKEN_TYPE
;
1656 updateAuthenticationPreFragmentVisibility();
1661 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1663 * Used to trigger the authentication check when the user presses 'enter' after writing the
1664 * password, or to throw the server test when the only field on screen is the URL input field.
1667 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1668 if (actionId
== EditorInfo
.IME_ACTION_DONE
&& inputField
!= null
&&
1669 inputField
.equals(mPasswordInput
)) {
1670 if (mOkButton
.isEnabled()) {
1671 mOkButton
.performClick();
1674 } else if (actionId
== EditorInfo
.IME_ACTION_NEXT
&& inputField
!= null
&&
1675 inputField
.equals(mHostUrlInput
)) {
1676 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1677 equals(mAuthTokenType
)) {
1681 return false
; // always return false to grant that the software keyboard is hidden anyway
1685 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1687 private int fuzz
= 75;
1693 public boolean onTouch(View view
, MotionEvent event
) {
1694 Drawable rightDrawable
= null
;
1695 if (view
instanceof TextView
) {
1696 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1697 if (drawables
.length
> 2) {
1698 rightDrawable
= drawables
[2];
1701 if (rightDrawable
!= null
) {
1702 final int x
= (int) event
.getX();
1703 final int y
= (int) event
.getY();
1704 final Rect bounds
= rightDrawable
.getBounds();
1705 if ( x
>= (view
.getRight() - bounds
.width() - fuzz
) &&
1706 x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
) &&
1707 y
>= (view
.getPaddingTop() - fuzz
) &&
1708 y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1710 return onDrawableTouch(event
);
1716 public abstract boolean onDrawableTouch(final MotionEvent event
);
1720 private void getRemoteUserNameOperation(String sessionCookie
, boolean followRedirects
) {
1722 Intent getUserNameIntent
= new Intent();
1723 getUserNameIntent
.setAction(OperationsService
.ACTION_GET_USER_NAME
);
1724 getUserNameIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
1725 getUserNameIntent
.putExtra(OperationsService
.EXTRA_COOKIE
, sessionCookie
);
1727 if (mOperationsServiceBinder
!= null
) {
1728 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getUserNameIntent
);
1734 public void onSsoFinished(String sessionCookie
) {
1735 if (sessionCookie
!= null
&& sessionCookie
.length() > 0) {
1736 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1737 mAuthToken
= sessionCookie
;
1738 getRemoteUserNameOperation(sessionCookie
, true
);
1739 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1740 if (fd
!= null
&& fd
instanceof DialogFragment
) {
1741 Dialog d
= ((DialogFragment
)fd
).getDialog();
1742 if (d
!= null
&& d
.isShowing()) {
1749 Log_OC
.d(TAG
, "SSO failed");
1755 public boolean onTouchEvent(MotionEvent event
) {
1756 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1757 equals(mAuthTokenType
) &&
1758 mHostUrlInput
.hasFocus() && event
.getAction() == MotionEvent
.ACTION_DOWN
) {
1761 return super.onTouchEvent(event
);
1766 * Show untrusted cert dialog
1768 public void showUntrustedCertDialog(
1769 X509Certificate x509Certificate
, SslError error
, SslErrorHandler handler
1771 // Show a dialog with the certificate info
1772 SslUntrustedCertDialog dialog
= null
;
1773 if (x509Certificate
== null
) {
1774 dialog
= SslUntrustedCertDialog
.newInstanceForEmptySslError(error
, handler
);
1776 dialog
= SslUntrustedCertDialog
.
1777 newInstanceForFullSslError(x509Certificate
, error
, handler
);
1779 FragmentManager fm
= getSupportFragmentManager();
1780 FragmentTransaction ft
= fm
.beginTransaction();
1781 ft
.addToBackStack(null
);
1782 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1787 * Show untrusted cert dialog
1789 private void showUntrustedCertDialog(RemoteOperationResult result
) {
1790 // Show a dialog with the certificate info
1791 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.
1792 newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1793 FragmentManager fm
= getSupportFragmentManager();
1794 FragmentTransaction ft
= fm
.beginTransaction();
1795 ft
.addToBackStack(null
);
1796 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1801 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1803 public void onSavedCertificate() {
1804 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1806 // if SAML dialog is not shown,
1807 // the SslDialog was shown due to an SSL error in the server check
1813 * Called from SslValidatorDialog when a new server certificate could not be saved
1814 * when the user requested it.
1817 public void onFailedSavingCertificate() {
1818 dismissDialog(SAML_DIALOG_TAG
);
1819 Toast
.makeText(this, R
.string
.ssl_validator_not_saved
, Toast
.LENGTH_LONG
).show();
1823 public void onCancelCertificate() {
1824 dismissDialog(SAML_DIALOG_TAG
);
1828 private void doOnResumeAndBound() {
1829 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1830 mOperationsServiceBinder
.addOperationListener(AuthenticatorActivity
.this, mHandler
);
1831 if (mWaitingForOpId
<= Integer
.MAX_VALUE
) {
1832 mOperationsServiceBinder
.dispatchResultIfFinished((int)mWaitingForOpId
, this);
1835 if (mPendingAutoCheck
) {
1841 private void dismissDialog(String dialogTag
){
1842 Fragment frag
= getSupportFragmentManager().findFragmentByTag(dialogTag
);
1843 if (frag
!= null
&& frag
instanceof DialogFragment
) {
1844 DialogFragment dialog
= (DialogFragment
) frag
;
1851 * Implements callback methods for service binding.
1853 private class OperationsServiceConnection
implements ServiceConnection
{
1856 public void onServiceConnected(ComponentName component
, IBinder service
) {
1857 if (component
.equals(
1858 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1860 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
1862 doOnResumeAndBound();
1871 public void onServiceDisconnected(ComponentName component
) {
1872 if (component
.equals(
1873 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1875 Log_OC
.e(TAG
, "Operations service crashed");
1876 mOperationsServiceBinder
= null
;
1883 * Create and show dialog for request authentication to the user
1887 public void createAuthenticationDialog(WebView webView
, HttpAuthHandler handler
) {
1889 // Show a dialog with the certificate info
1890 CredentialsDialogFragment dialog
=
1891 CredentialsDialogFragment
.newInstanceForCredentials(webView
, handler
);
1892 FragmentManager fm
= getSupportFragmentManager();
1893 FragmentTransaction ft
= fm
.beginTransaction();
1894 ft
.addToBackStack(null
);
1895 dialog
.setCancelable(false
);
1896 dialog
.show(ft
, CREDENTIALS_DIALOG_TAG
);
1898 if (!mIsFirstAuthAttempt
) {
1900 getApplicationContext(),
1901 getText(R
.string
.saml_authentication_wrong_pass
),
1905 mIsFirstAuthAttempt
= false
;
1910 * For retrieving the clicking on authentication cancel button
1912 public void doNegativeAuthenticatioDialogClick(){
1913 mIsFirstAuthAttempt
= true
;