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
);
256 /// initialize block to be moved to single Fragment to check server and get info about it
257 initServerPreFragment(savedInstanceState
);
259 /// initialize block to be moved to single Fragment to retrieve and validate credentials
260 initAuthorizationPreFragment(savedInstanceState
);
262 //Log_OC.wtf(TAG, "onCreate end");
265 private void initAuthTokenType() {
267 getIntent().getExtras().getString(AccountAuthenticator
.KEY_AUTH_TOKEN_TYPE
);
268 if (mAuthTokenType
== null
) {
269 if (mAccount
!= null
) {
270 boolean oAuthRequired
=
271 (mAccountMgr
.getUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
) != null
);
272 boolean samlWebSsoRequired
= (
273 mAccountMgr
.getUserData(
274 mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
277 mAuthTokenType
= chooseAuthTokenType(oAuthRequired
, samlWebSsoRequired
);
280 boolean oAuthSupported
= AUTH_ON
.equals(getString(R
.string
.auth_method_oauth2
));
281 boolean samlWebSsoSupported
=
282 AUTH_ON
.equals(getString(R
.string
.auth_method_saml_web_sso
));
283 mAuthTokenType
= chooseAuthTokenType(oAuthSupported
, samlWebSsoSupported
);
288 private String
chooseAuthTokenType(boolean oauth
, boolean saml
) {
290 return SAML_TOKEN_TYPE
;
292 return OAUTH_TOKEN_TYPE
;
294 return BASIC_TOKEN_TYPE
;
300 * Configures elements in the user interface under direct control of the Activity.
302 private void initOverallUi() {
304 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
305 boolean isWelcomeLinkVisible
= getResources().getBoolean(R
.bool
.show_welcome_link
);
307 String instructionsMessageText
= null
;
308 if (mAction
== ACTION_UPDATE_EXPIRED_TOKEN
) {
309 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
310 .equals(mAuthTokenType
)) {
311 instructionsMessageText
= getString(R
.string
.auth_expired_oauth_token_toast
);
313 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType())
314 .equals(mAuthTokenType
)) {
315 instructionsMessageText
= getString(R
.string
.auth_expired_saml_sso_token_toast
);
318 instructionsMessageText
= getString(R
.string
.auth_expired_basic_auth_toast
);
322 /// step 2 - set properties of UI elements (text, visibility, enabled...)
323 Button welcomeLink
= (Button
) findViewById(R
.id
.welcome_link
);
324 welcomeLink
.setVisibility(isWelcomeLinkVisible ? View
.VISIBLE
: View
.GONE
);
326 String
.format(getString(R
.string
.auth_register
), getString(R
.string
.app_name
)));
328 TextView instructionsView
= (TextView
) findViewById(R
.id
.instructions_message
);
329 if (instructionsMessageText
!= null
) {
330 instructionsView
.setVisibility(View
.VISIBLE
);
331 instructionsView
.setText(instructionsMessageText
);
333 instructionsView
.setVisibility(View
.GONE
);
340 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
342 private void initServerPreFragment(Bundle savedInstanceState
) {
344 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
345 boolean isUrlInputAllowed
= getResources().getBoolean(R
.bool
.show_server_url_input
);
346 if (savedInstanceState
== null
) {
347 if (mAccount
!= null
) {
348 mServerInfo
.mBaseUrl
= mAccountMgr
.getUserData(mAccount
, Constants
.KEY_OC_BASE_URL
);
349 // TODO do next in a setter for mBaseUrl
350 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
351 mServerInfo
.mVersion
= AccountUtils
.getServerVersion(mAccount
);
353 mServerInfo
.mBaseUrl
= getString(R
.string
.server_url
).trim();
354 mServerInfo
.mIsSslConn
= mServerInfo
.mBaseUrl
.startsWith("https://");
357 mServerStatusText
= savedInstanceState
.getInt(KEY_SERVER_STATUS_TEXT
);
358 mServerStatusIcon
= savedInstanceState
.getInt(KEY_SERVER_STATUS_ICON
);
360 mServerIsValid
= savedInstanceState
.getBoolean(KEY_SERVER_VALID
);
361 mServerIsChecked
= savedInstanceState
.getBoolean(KEY_SERVER_CHECKED
);
364 mServerInfo
.mIsSslConn
= savedInstanceState
.getBoolean(KEY_IS_SSL_CONN
);
365 mServerInfo
.mBaseUrl
= savedInstanceState
.getString(KEY_HOST_URL_TEXT
);
366 String ocVersion
= savedInstanceState
.getString(KEY_OC_VERSION
);
367 if (ocVersion
!= null
) {
368 mServerInfo
.mVersion
= new OwnCloudVersion(ocVersion
);
370 mServerInfo
.mAuthMethod
= AuthenticationMethod
.valueOf(
371 savedInstanceState
.getString(KEY_SERVER_AUTH_METHOD
));
375 /// step 2 - set properties of UI elements (text, visibility, enabled...)
376 mHostUrlInput
= (EditText
) findViewById(R
.id
.hostUrlInput
);
377 // Convert IDN to Unicode
378 mHostUrlInput
.setText(DisplayUtils
.convertIdn(mServerInfo
.mBaseUrl
, false
));
379 if (mAction
!= ACTION_CREATE
) {
380 /// lock things that should not change
381 mHostUrlInput
.setEnabled(false
);
382 mHostUrlInput
.setFocusable(false
);
384 if (isUrlInputAllowed
) {
385 mRefreshButton
= findViewById(R
.id
.embeddedRefreshButton
);
387 findViewById(R
.id
.hostUrlFrame
).setVisibility(View
.GONE
);
388 mRefreshButton
= findViewById(R
.id
.centeredRefreshButton
);
390 showRefreshButton(mServerIsChecked
&& !mServerIsValid
&&
391 mWaitingForOpId
> Integer
.MAX_VALUE
);
392 mServerStatusView
= (TextView
) findViewById(R
.id
.server_status_text
);
395 /// step 3 - bind some listeners and options
396 mHostUrlInput
.setImeOptions(EditorInfo
.IME_ACTION_NEXT
);
397 mHostUrlInput
.setOnEditorActionListener(this);
399 /// step 4 - create listeners that will be bound at onResume
400 mHostUrlInputWatcher
= new TextWatcher() {
403 public void afterTextChanged(Editable s
) {
404 if (mOkButton
.isEnabled() &&
405 !mServerInfo
.mBaseUrl
.equals(
406 normalizeUrl(s
.toString(), mServerInfo
.mIsSslConn
))) {
407 mOkButton
.setEnabled(false
);
412 public void beforeTextChanged(CharSequence s
, int start
, int count
, int after
) {
416 public void onTextChanged(CharSequence s
, int start
, int before
, int count
) {
417 if (mAuthStatusIcon
!= 0) {
418 Log_OC
.d(TAG
, "onTextChanged: hiding authentication status");
427 // TODO find out if this is really necessary, or if it can done in a different way
428 findViewById(R
.id
.scroll
).setOnTouchListener(new OnTouchListener() {
430 public boolean onTouch(View view
, MotionEvent event
) {
431 if (event
.getAction() == MotionEvent
.ACTION_DOWN
) {
433 AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(
434 MainApp
.getAccountType()
435 ).equals(mAuthTokenType
) &&
436 mHostUrlInput
.hasFocus()
446 /// step 4 - mark automatic check to be started when OperationsService is ready
447 mPendingAutoCheck
= (savedInstanceState
== null
&&
448 (mAction
!= ACTION_CREATE
|| !isUrlInputAllowed
));
454 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
456 private void initAuthorizationPreFragment(Bundle savedInstanceState
) {
458 /// step 0 - get UI elements in layout
459 mOAuth2Check
= (CheckBox
) findViewById(R
.id
.oauth_onOff_check
);
460 mOAuthAuthEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_1
);
461 mOAuthTokenEndpointText
= (TextView
)findViewById(R
.id
.oAuthEntryPoint_2
);
462 mUsernameInput
= (EditText
) findViewById(R
.id
.account_username
);
463 mPasswordInput
= (EditText
) findViewById(R
.id
.account_password
);
464 mAuthStatusView
= (TextView
) findViewById(R
.id
.auth_status_text
);
466 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
467 String presetUserName
= null
;
468 boolean isPasswordExposed
= false
;
469 if (savedInstanceState
== null
) {
470 if (mAccount
!= null
) {
471 presetUserName
= mAccount
.name
.substring(0, mAccount
.name
.lastIndexOf('@'));
475 isPasswordExposed
= savedInstanceState
.getBoolean(KEY_PASSWORD_EXPOSED
, false
);
476 mAuthStatusText
= savedInstanceState
.getInt(KEY_AUTH_STATUS_TEXT
);
477 mAuthStatusIcon
= savedInstanceState
.getInt(KEY_AUTH_STATUS_ICON
);
478 mAuthToken
= savedInstanceState
.getString(KEY_AUTH_TOKEN
);
481 /// step 2 - set properties of UI elements (text, visibility, enabled...)
482 mOAuth2Check
.setChecked(
483 AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType())
484 .equals(mAuthTokenType
));
485 if (presetUserName
!= null
) {
486 mUsernameInput
.setText(presetUserName
);
488 if (mAction
!= ACTION_CREATE
) {
489 mUsernameInput
.setEnabled(false
);
490 mUsernameInput
.setFocusable(false
);
492 mPasswordInput
.setText(""); // clean password to avoid social hacking
493 if (isPasswordExposed
) {
496 updateAuthenticationPreFragmentVisibility();
498 mOkButton
.setEnabled(mServerIsValid
);
501 /// step 3 - bind listeners
502 // bindings for password input field
503 mPasswordInput
.setOnFocusChangeListener(this);
504 mPasswordInput
.setImeOptions(EditorInfo
.IME_ACTION_DONE
);
505 mPasswordInput
.setOnEditorActionListener(this);
506 mPasswordInput
.setOnTouchListener(new RightDrawableOnTouchListener() {
508 public boolean onDrawableTouch(final MotionEvent event
) {
509 if (event
.getAction() == MotionEvent
.ACTION_UP
) {
510 AuthenticatorActivity
.this.onViewPasswordClick();
520 * Changes the visibility of input elements depending on
521 * the current authorization method.
523 private void updateAuthenticationPreFragmentVisibility () {
524 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
525 equals(mAuthTokenType
)) {
526 // SAML-based web Single Sign On
527 mOAuth2Check
.setVisibility(View
.GONE
);
528 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
529 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
530 mUsernameInput
.setVisibility(View
.GONE
);
531 mPasswordInput
.setVisibility(View
.GONE
);
534 if (mAction
== ACTION_CREATE
&&
535 AUTH_OPTIONAL
.equals(getString(R
.string
.auth_method_oauth2
))) {
536 mOAuth2Check
.setVisibility(View
.VISIBLE
);
538 mOAuth2Check
.setVisibility(View
.GONE
);
541 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
542 equals(mAuthTokenType
)) {
543 // OAuth 2 authorization
545 mOAuthAuthEndpointText
.setVisibility(View
.VISIBLE
);
546 mOAuthTokenEndpointText
.setVisibility(View
.VISIBLE
);
547 mUsernameInput
.setVisibility(View
.GONE
);
548 mPasswordInput
.setVisibility(View
.GONE
);
551 // basic HTTP authorization
552 mOAuthAuthEndpointText
.setVisibility(View
.GONE
);
553 mOAuthTokenEndpointText
.setVisibility(View
.GONE
);
554 mUsernameInput
.setVisibility(View
.VISIBLE
);
555 mPasswordInput
.setVisibility(View
.VISIBLE
);
563 * Saves relevant state before {@link #onPause()}
565 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag,
566 * intended to defer the processing of the redirection caught in
567 * {@link #onNewIntent(Intent)} until {@link #onResume()}
569 * See {@link super#onSaveInstanceState(Bundle)}
572 protected void onSaveInstanceState(Bundle outState
) {
573 //Log_OC.wtf(TAG, "onSaveInstanceState init" );
574 super.onSaveInstanceState(outState
);
577 outState
.putString(KEY_AUTH_TOKEN_TYPE
, mAuthTokenType
);
578 outState
.putLong(KEY_WAITING_FOR_OP_ID
, mWaitingForOpId
);
580 /// Server PRE-fragment state
581 outState
.putInt(KEY_SERVER_STATUS_TEXT
, mServerStatusText
);
582 outState
.putInt(KEY_SERVER_STATUS_ICON
, mServerStatusIcon
);
583 outState
.putBoolean(KEY_SERVER_CHECKED
, mServerIsChecked
);
584 outState
.putBoolean(KEY_SERVER_VALID
, mServerIsValid
);
585 outState
.putBoolean(KEY_IS_SSL_CONN
, mServerInfo
.mIsSslConn
);
586 outState
.putString(KEY_HOST_URL_TEXT
, mServerInfo
.mBaseUrl
);
587 if (mServerInfo
.mVersion
!= null
) {
588 outState
.putString(KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion());
590 outState
.putString(KEY_SERVER_AUTH_METHOD
, mServerInfo
.mAuthMethod
.name());
592 /// Authentication PRE-fragment state
593 outState
.putBoolean(KEY_PASSWORD_EXPOSED
, isPasswordVisible());
594 outState
.putInt(KEY_AUTH_STATUS_ICON
, mAuthStatusIcon
);
595 outState
.putInt(KEY_AUTH_STATUS_TEXT
, mAuthStatusText
);
596 outState
.putString(KEY_AUTH_TOKEN
, mAuthToken
);
599 outState
.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG
, mIsFirstAuthAttempt
);
601 /// AsyncTask (User and password)
602 outState
.putString(KEY_USERNAME
, mUsernameInput
.getText().toString());
603 outState
.putString(KEY_PASSWORD
, mPasswordInput
.getText().toString());
605 if (mAsyncTask
!= null
) {
606 mAsyncTask
.cancel(true
);
607 outState
.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS
, true
);
609 outState
.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS
, false
);
613 //Log_OC.wtf(TAG, "onSaveInstanceState end" );
617 public void onRestoreInstanceState(Bundle savedInstanceState
) {
618 super.onRestoreInstanceState(savedInstanceState
);
621 boolean inProgress
= savedInstanceState
.getBoolean(KEY_ASYNC_TASK_IN_PROGRESS
);
623 String username
= savedInstanceState
.getString(KEY_USERNAME
);
624 String password
= savedInstanceState
.getString(KEY_PASSWORD
);
626 OwnCloudCredentials credentials
= null
;
627 if (BASIC_TOKEN_TYPE
.equals(mAuthTokenType
)) {
628 credentials
= OwnCloudCredentialsFactory
.newBasicCredentials(username
, password
);
630 } else if (OAUTH_TOKEN_TYPE
.equals(mAuthTokenType
)) {
631 credentials
= OwnCloudCredentialsFactory
.newBearerCredentials(mAuthToken
);
634 accessRootFolder(credentials
);
639 * The redirection triggered by the OAuth authentication server as response to the
640 * GET AUTHORIZATION request is caught here.
642 * To make this possible, this activity needs to be qualified with android:launchMode =
643 * "singleTask" in the AndroidManifest.xml file.
646 protected void onNewIntent (Intent intent
) {
647 Log_OC
.d(TAG
, "onNewIntent()");
648 Uri data
= intent
.getData();
649 if (data
!= null
&& data
.toString().startsWith(getString(R
.string
.oauth2_redirect_uri
))) {
650 mNewCapturedUriFromOAuth2Redirection
= data
;
656 * The redirection triggered by the OAuth authentication server as response to the
657 * GET AUTHORIZATION, and deferred in {@link #onNewIntent(Intent)}, is processed here.
660 protected void onResume() {
663 // bound here to avoid spurious changes triggered by Android on device rotations
664 mHostUrlInput
.setOnFocusChangeListener(this);
665 mHostUrlInput
.addTextChangedListener(mHostUrlInputWatcher
);
667 if (mNewCapturedUriFromOAuth2Redirection
!= null
) {
668 getOAuth2AccessTokenFromCapturedRedirection();
671 if (mOperationsServiceBinder
!= null
) {
672 doOnResumeAndBound();
679 protected void onPause() {
680 if (mOperationsServiceBinder
!= null
) {
681 mOperationsServiceBinder
.removeOperationListener(this);
684 mHostUrlInput
.removeTextChangedListener(mHostUrlInputWatcher
);
685 mHostUrlInput
.setOnFocusChangeListener(null
);
691 protected void onDestroy() {
693 mHostUrlInputWatcher
= null
;
695 if (mOperationsServiceConnection
!= null
) {
696 unbindService(mOperationsServiceConnection
);
697 mOperationsServiceBinder
= null
;
704 * Parses the redirection with the response to the GET AUTHORIZATION request to the
705 * oAuth server and requests for the access token (GET ACCESS TOKEN)
707 private void getOAuth2AccessTokenFromCapturedRedirection() {
708 /// Parse data from OAuth redirection
709 String queryParameters
= mNewCapturedUriFromOAuth2Redirection
.getQuery();
710 mNewCapturedUriFromOAuth2Redirection
= null
;
712 /// Showing the dialog with instructions for the user.
713 IndeterminateProgressDialog dialog
=
714 IndeterminateProgressDialog
.newInstance(R
.string
.auth_getting_authorization
, true
);
715 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
717 /// GET ACCESS TOKEN to the oAuth server
718 Intent getServerInfoIntent
= new Intent();
719 getServerInfoIntent
.setAction(OperationsService
.ACTION_OAUTH2_GET_ACCESS_TOKEN
);
721 getServerInfoIntent
.putExtra(
722 OperationsService
.EXTRA_SERVER_URL
,
723 mOAuthTokenEndpointText
.getText().toString().trim());
725 getServerInfoIntent
.putExtra(
726 OperationsService
.EXTRA_OAUTH2_QUERY_PARAMETERS
,
729 if (mOperationsServiceBinder
!= null
) {
730 //Log_OC.wtf(TAG, "getting access token..." );
731 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
738 * Handles the change of focus on the text inputs for the server URL and the password
740 public void onFocusChange(View view
, boolean hasFocus
) {
741 if (view
.getId() == R
.id
.hostUrlInput
) {
743 onUrlInputFocusLost();
746 showRefreshButton(false
);
749 } else if (view
.getId() == R
.id
.account_password
) {
750 onPasswordFocusChanged(hasFocus
);
756 * Handles changes in focus on the text input for the server URL.
758 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
759 * other field. The operation to check the existence of the server in the entered URL is
762 * When hasFocus: user 'comes back' to write again the server URL.
764 private void onUrlInputFocusLost() {
765 if (!mServerInfo
.mBaseUrl
.equals(
766 normalizeUrl(mHostUrlInput
.getText().toString(), mServerInfo
.mIsSslConn
))) {
767 // check server again only if the user changed something in the field
770 mOkButton
.setEnabled(mServerIsValid
);
771 showRefreshButton(!mServerIsValid
);
776 private void checkOcServer() {
777 String uri
= mHostUrlInput
.getText().toString().trim();
778 mServerIsValid
= false
;
779 mServerIsChecked
= false
;
780 mOkButton
.setEnabled(false
);
781 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
782 showRefreshButton(false
);
784 if (uri
.length() != 0) {
785 // Handle internationalized domain names
786 uri
= DisplayUtils
.convertIdn(uri
, true
);
788 mServerStatusText
= R
.string
.auth_testing_connection
;
789 mServerStatusIcon
= R
.drawable
.progress_small
;
792 Intent getServerInfoIntent
= new Intent();
793 getServerInfoIntent
.setAction(OperationsService
.ACTION_GET_SERVER_INFO
);
794 getServerInfoIntent
.putExtra(
795 OperationsService
.EXTRA_SERVER_URL
,
796 normalizeUrlSuffix(uri
)
798 if (mOperationsServiceBinder
!= null
) {
799 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getServerInfoIntent
);
801 Log_OC
.wtf(TAG
, "Server check tried with OperationService unbound!" );
805 mServerStatusText
= 0;
806 mServerStatusIcon
= 0;
813 * Handles changes in focus on the text input for the password (basic authorization).
815 * When (hasFocus), the button to toggle password visibility is shown.
817 * When (!hasFocus), the button is made invisible and the password is hidden.
819 * @param hasFocus 'True' if focus is received, 'false' if is lost
821 private void onPasswordFocusChanged(boolean hasFocus
) {
823 showViewPasswordButton();
826 hidePasswordButton();
831 private void showViewPasswordButton() {
832 int drawable
= R
.drawable
.ic_view
;
833 if (isPasswordVisible()) {
834 drawable
= R
.drawable
.ic_hide
;
836 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable
, 0);
839 private boolean isPasswordVisible() {
840 return ((mPasswordInput
.getInputType() & InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
) ==
841 InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);
844 private void hidePasswordButton() {
845 mPasswordInput
.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
848 private void showPassword() {
849 mPasswordInput
.setInputType(
850 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
852 showViewPasswordButton();
855 private void hidePassword() {
856 mPasswordInput
.setInputType(
857 InputType
.TYPE_CLASS_TEXT
| InputType
.TYPE_TEXT_VARIATION_PASSWORD
859 showViewPasswordButton();
863 * Checks the credentials of the user in the root of the ownCloud server
864 * before creating a new local account.
866 * For basic authorization, a check of existence of the root folder is
869 * For OAuth, starts the flow to get an access token; the credentials test
870 * is postponed until it is available.
872 * IMPORTANT ENTRY POINT 4
874 * @param view OK button
876 public void onOkClick(View view
) {
877 // this check should be unnecessary
878 if (mServerInfo
.mVersion
== null
||
879 !mServerInfo
.mVersion
.isVersionValid() ||
880 mServerInfo
.mBaseUrl
== null
||
881 mServerInfo
.mBaseUrl
.length() == 0) {
882 mServerStatusIcon
= R
.drawable
.common_error
;
883 mServerStatusText
= R
.string
.auth_wtf_reenter_URL
;
885 mOkButton
.setEnabled(false
);
889 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
890 equals(mAuthTokenType
)) {
892 startOauthorization();
893 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
894 equals(mAuthTokenType
)) {
896 startSamlBasedFederatedSingleSignOnAuthorization();
898 checkBasicAuthorization();
904 * Tests the credentials entered by the user performing a check of existence on
905 * the root folder of the ownCloud server.
907 private void checkBasicAuthorization() {
908 /// get basic credentials entered by user
909 String username
= mUsernameInput
.getText().toString();
910 String password
= mPasswordInput
.getText().toString();
912 /// be gentle with the user
913 IndeterminateProgressDialog dialog
=
914 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
915 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
917 /// validate credentials accessing the root folder
918 OwnCloudCredentials credentials
= OwnCloudCredentialsFactory
.newBasicCredentials(username
,
920 accessRootFolder(credentials
);
923 private void accessRootFolder(OwnCloudCredentials credentials
) {
924 mAsyncTask
= new AuthenticatorAsyncTask(this);
925 Object
[] params
= { mServerInfo
.mBaseUrl
, credentials
};
926 mAsyncTask
.execute(params
);
931 * Starts the OAuth 'grant type' flow to get an access token, with
932 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
934 private void startOauthorization() {
935 // be gentle with the user
936 mAuthStatusIcon
= R
.drawable
.progress_small
;
937 mAuthStatusText
= R
.string
.oauth_login_connection
;
940 // GET AUTHORIZATION request
941 Uri uri
= Uri
.parse(mOAuthAuthEndpointText
.getText().toString().trim());
942 Uri
.Builder uriBuilder
= uri
.buildUpon();
943 uriBuilder
.appendQueryParameter(
944 OAuth2Constants
.KEY_RESPONSE_TYPE
, getString(R
.string
.oauth2_response_type
)
946 uriBuilder
.appendQueryParameter(
947 OAuth2Constants
.KEY_REDIRECT_URI
, getString(R
.string
.oauth2_redirect_uri
)
949 uriBuilder
.appendQueryParameter(
950 OAuth2Constants
.KEY_CLIENT_ID
, getString(R
.string
.oauth2_client_id
)
952 uriBuilder
.appendQueryParameter(
953 OAuth2Constants
.KEY_SCOPE
, getString(R
.string
.oauth2_scope
)
955 uri
= uriBuilder
.build();
956 Log_OC
.d(TAG
, "Starting browser to view " + uri
.toString());
957 Intent i
= new Intent(Intent
.ACTION_VIEW
, uri
);
963 * Starts the Web Single Sign On flow to get access to the root folder
966 private void startSamlBasedFederatedSingleSignOnAuthorization() {
967 /// be gentle with the user
968 mAuthStatusIcon
= R
.drawable
.progress_small
;
969 mAuthStatusText
= R
.string
.auth_connecting_auth_server
;
972 /// Show SAML-based SSO web dialog
973 String targetUrl
= mServerInfo
.mBaseUrl
974 + AccountUtils
.getWebdavPath(mServerInfo
.mVersion
, mAuthTokenType
);
975 SamlWebViewDialog dialog
= SamlWebViewDialog
.newInstance(targetUrl
, targetUrl
);
976 dialog
.show(getSupportFragmentManager(), SAML_DIALOG_TAG
);
980 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
982 * Dispatches the operation flow to the right method.
985 public void onRemoteOperationFinish(RemoteOperation operation
, RemoteOperationResult result
) {
987 if (operation
instanceof GetServerInfoOperation
) {
988 if (operation
.hashCode() == mWaitingForOpId
) {
989 onGetServerInfoFinish(result
);
990 } // else nothing ; only the last check operation is considered;
991 // multiple can be started if the user amends a URL quickly
993 } else if (operation
instanceof OAuth2GetAccessToken
) {
994 onGetOAuthAccessTokenFinish(result
);
996 } else if (operation
instanceof GetRemoteUserNameOperation
) {
997 onGetUserNameFinish(result
);
1002 private void onGetUserNameFinish(RemoteOperationResult result
) {
1003 mWaitingForOpId
= Long
.MAX_VALUE
;
1004 if (result
.isSuccess()) {
1005 boolean success
= false
;
1006 String username
= (String
) result
.getData().get(0);
1008 if ( mAction
== ACTION_CREATE
) {
1009 mUsernameInput
.setText(username
);
1010 success
= createAccount(result
);
1013 if (!mUsernameInput
.getText().toString().equals(username
)) {
1014 // fail - not a new account, but an existing one; disallow
1015 result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_THE_SAME
);
1017 updateAuthStatusIconAndText(result
);
1019 Log_OC
.d(TAG
, result
.getLogMessage());
1022 updateAccountAuthentication();
1025 } catch (AccountNotFoundException e
) {
1026 Log_OC
.e(TAG
, "Account " + mAccount
+ " was removed!", e
);
1027 Toast
.makeText(this, R
.string
.auth_account_does_not_exist
,
1028 Toast
.LENGTH_SHORT
).show();
1037 updateStatusIconFailUserName();
1039 Log_OC
.e(TAG
, "Access to user name failed: " + result
.getLogMessage());
1045 * Processes the result of the server check performed when the user finishes the enter of the
1048 * @param result Result of the check.
1050 private void onGetServerInfoFinish(RemoteOperationResult result
) {
1051 /// update activity state
1052 mServerIsChecked
= true
;
1053 mWaitingForOpId
= Long
.MAX_VALUE
;
1055 // update server status, but don't show it yet
1056 updateServerStatusIconAndText(result
);
1058 if (result
.isSuccess()) {
1060 // 1. connection succeeded, and we know if it's SSL or not
1061 // 2. server is installed
1062 // 3. we got the server version
1063 // 4. we got the authentication method required by the server
1064 mServerInfo
= (GetServerInfoOperation
.ServerInfo
) (result
.getData().get(0));
1066 if (!authSupported(mServerInfo
.mAuthMethod
)) {
1068 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1069 mServerIsValid
= false
;
1072 mServerIsValid
= true
;
1076 mServerIsValid
= false
;
1080 showRefreshButton(!mServerIsValid
);
1082 mOkButton
.setEnabled(mServerIsValid
);
1084 /// very special case (TODO: move to a common place for all the remote operations)
1085 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1086 showUntrustedCertDialog(result
);
1091 private boolean authSupported(AuthenticationMethod authMethod
) {
1092 return (( BASIC_TOKEN_TYPE
.equals(mAuthTokenType
) &&
1093 AuthenticationMethod
.BASIC_HTTP_AUTH
.equals(authMethod
) ) ||
1094 ( OAUTH_TOKEN_TYPE
.equals(mAuthTokenType
) &&
1095 AuthenticationMethod
.BEARER_TOKEN
.equals(authMethod
)) ||
1096 ( SAML_TOKEN_TYPE
.equals(mAuthTokenType
) &&
1097 AuthenticationMethod
.SAML_WEB_SSO
.equals(authMethod
))
1102 // TODO remove, if possible
1103 private String
normalizeUrl(String url
, boolean sslWhenUnprefixed
) {
1104 if (url
!= null
&& url
.length() > 0) {
1106 if (!url
.toLowerCase().startsWith("http://") &&
1107 !url
.toLowerCase().startsWith("https://")) {
1108 if (sslWhenUnprefixed
) {
1109 url
= "https://" + url
;
1111 url
= "http://" + url
;
1115 url
= normalizeUrlSuffix(url
);
1117 return (url
!= null ? url
: "");
1121 private String
normalizeUrlSuffix(String url
) {
1122 if (url
.endsWith("/")) {
1123 url
= url
.substring(0, url
.length() - 1);
1125 url
= trimUrlWebdav(url
);
1130 // TODO remove, if possible
1131 private String
trimUrlWebdav(String url
){
1132 if(url
.toLowerCase().endsWith(AccountUtils
.WEBDAV_PATH_4_0_AND_LATER
)){
1133 url
= url
.substring(0, url
.length() - AccountUtils
.WEBDAV_PATH_4_0_AND_LATER
.length());
1140 * Chooses the right icon and text to show to the user for the received operation result.
1142 * @param result Result of a remote operation performed in this activity
1144 private void updateServerStatusIconAndText(RemoteOperationResult result
) {
1145 mServerStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1147 switch (result
.getCode()) {
1149 mServerStatusIcon
= R
.drawable
.ic_lock
;
1150 mServerStatusText
= R
.string
.auth_secure_connection
;
1155 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1156 mServerStatusText
= R
.string
.auth_connection_established
;
1157 mServerStatusIcon
= R
.drawable
.ic_ok
;
1159 mServerStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1160 mServerStatusIcon
= R
.drawable
.ic_lock_open
;
1164 case NO_NETWORK_CONNECTION
:
1165 mServerStatusIcon
= R
.drawable
.no_network
;
1166 mServerStatusText
= R
.string
.auth_no_net_conn_title
;
1169 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1170 mServerStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1172 case BAD_OC_VERSION
:
1173 mServerStatusText
= R
.string
.auth_bad_oc_version_title
;
1175 case WRONG_CONNECTION
:
1176 mServerStatusText
= R
.string
.auth_wrong_connection_title
;
1179 mServerStatusText
= R
.string
.auth_timeout_title
;
1181 case INCORRECT_ADDRESS
:
1182 mServerStatusText
= R
.string
.auth_incorrect_address_title
;
1185 mServerStatusText
= R
.string
.auth_ssl_general_error_title
;
1188 mServerStatusText
= R
.string
.auth_unauthorized
;
1190 case HOST_NOT_AVAILABLE
:
1191 mServerStatusText
= R
.string
.auth_unknown_host_title
;
1193 case INSTANCE_NOT_CONFIGURED
:
1194 mServerStatusText
= R
.string
.auth_not_configured_title
;
1196 case FILE_NOT_FOUND
:
1197 mServerStatusText
= R
.string
.auth_incorrect_path_title
;
1200 mServerStatusText
= R
.string
.auth_oauth_error
;
1202 case OAUTH2_ERROR_ACCESS_DENIED
:
1203 mServerStatusText
= R
.string
.auth_oauth_error_access_denied
;
1205 case UNHANDLED_HTTP_CODE
:
1207 mServerStatusText
= R
.string
.auth_unknown_error_title
;
1209 case OK_REDIRECT_TO_NON_SECURE_CONNECTION
:
1210 mServerStatusIcon
= R
.drawable
.ic_lock_open
;
1211 mServerStatusText
= R
.string
.auth_redirect_non_secure_connection_title
;
1214 mServerStatusText
= 0;
1215 mServerStatusIcon
= 0;
1221 * Chooses the right icon and text to show to the user for the received operation result.
1223 * @param result Result of a remote operation performed in this activity
1225 private void updateAuthStatusIconAndText(RemoteOperationResult result
) {
1226 mAuthStatusIcon
= R
.drawable
.common_error
; // the most common case in the switch below
1228 switch (result
.getCode()) {
1230 mAuthStatusIcon
= R
.drawable
.ic_lock
;
1231 mAuthStatusText
= R
.string
.auth_secure_connection
;
1236 if (mHostUrlInput
.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1237 mAuthStatusText
= R
.string
.auth_connection_established
;
1238 mAuthStatusIcon
= R
.drawable
.ic_ok
;
1240 mAuthStatusText
= R
.string
.auth_nossl_plain_ok_title
;
1241 mAuthStatusIcon
= R
.drawable
.ic_lock_open
;
1245 case NO_NETWORK_CONNECTION
:
1246 mAuthStatusIcon
= R
.drawable
.no_network
;
1247 mAuthStatusText
= R
.string
.auth_no_net_conn_title
;
1250 case SSL_RECOVERABLE_PEER_UNVERIFIED
:
1251 mAuthStatusText
= R
.string
.auth_ssl_unverified_server_title
;
1253 case BAD_OC_VERSION
:
1254 mAuthStatusText
= R
.string
.auth_bad_oc_version_title
;
1256 case WRONG_CONNECTION
:
1257 mAuthStatusText
= R
.string
.auth_wrong_connection_title
;
1260 mAuthStatusText
= R
.string
.auth_timeout_title
;
1262 case INCORRECT_ADDRESS
:
1263 mAuthStatusText
= R
.string
.auth_incorrect_address_title
;
1266 mAuthStatusText
= R
.string
.auth_ssl_general_error_title
;
1269 mAuthStatusText
= R
.string
.auth_unauthorized
;
1271 case HOST_NOT_AVAILABLE
:
1272 mAuthStatusText
= R
.string
.auth_unknown_host_title
;
1274 case INSTANCE_NOT_CONFIGURED
:
1275 mAuthStatusText
= R
.string
.auth_not_configured_title
;
1277 case FILE_NOT_FOUND
:
1278 mAuthStatusText
= R
.string
.auth_incorrect_path_title
;
1281 mAuthStatusText
= R
.string
.auth_oauth_error
;
1283 case OAUTH2_ERROR_ACCESS_DENIED
:
1284 mAuthStatusText
= R
.string
.auth_oauth_error_access_denied
;
1286 case ACCOUNT_NOT_NEW
:
1287 mAuthStatusText
= R
.string
.auth_account_not_new
;
1289 case ACCOUNT_NOT_THE_SAME
:
1290 mAuthStatusText
= R
.string
.auth_account_not_the_same
;
1292 case UNHANDLED_HTTP_CODE
:
1294 mAuthStatusText
= R
.string
.auth_unknown_error_title
;
1297 mAuthStatusText
= 0;
1298 mAuthStatusIcon
= 0;
1303 private void updateStatusIconFailUserName(){
1304 mAuthStatusIcon
= R
.drawable
.common_error
;
1305 mAuthStatusText
= R
.string
.auth_fail_get_user_name
;
1308 private void updateServerStatusIconNoRegularAuth(){
1309 mServerStatusIcon
= R
.drawable
.common_error
;
1310 mServerStatusText
= R
.string
.auth_can_not_auth_against_server
;
1314 * Processes the result of the request for and access token send
1315 * to an OAuth authorization server.
1317 * @param result Result of the operation.
1319 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result
) {
1320 mWaitingForOpId
= Long
.MAX_VALUE
;
1321 dismissDialog(WAIT_DIALOG_TAG
);
1323 if (result
.isSuccess()) {
1324 /// be gentle with the user
1325 IndeterminateProgressDialog dialog
=
1326 IndeterminateProgressDialog
.newInstance(R
.string
.auth_trying_to_login
, true
);
1327 dialog
.show(getSupportFragmentManager(), WAIT_DIALOG_TAG
);
1329 /// time to test the retrieved access token on the ownCloud server
1330 @SuppressWarnings("unchecked")
1331 Map
<String
, String
> tokens
= (Map
<String
, String
>)(result
.getData().get(0));
1332 mAuthToken
= tokens
.get(OAuth2Constants
.KEY_ACCESS_TOKEN
);
1333 Log_OC
.d(TAG
, "Got ACCESS TOKEN: " + mAuthToken
);
1335 /// validate token accessing to root folder / getting session
1336 OwnCloudCredentials credentials
= OwnCloudCredentialsFactory
.newBearerCredentials(
1338 accessRootFolder(credentials
);
1341 updateAuthStatusIconAndText(result
);
1343 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1349 * Processes the result of the access check performed to try the user credentials.
1351 * Creates a new account through the AccountManager.
1353 * @param result Result of the operation.
1356 public void onAuthenticatorTaskCallback(RemoteOperationResult result
) {
1357 mWaitingForOpId
= Long
.MAX_VALUE
;
1358 dismissDialog(WAIT_DIALOG_TAG
);
1360 if (result
.isSuccess()) {
1361 Log_OC
.d(TAG
, "Successful access - time to save the account");
1363 boolean success
= false
;
1365 if (mAction
== ACTION_CREATE
) {
1366 success
= createAccount(result
);
1370 updateAccountAuthentication();
1373 } catch (AccountNotFoundException e
) {
1374 Log_OC
.e(TAG
, "Account " + mAccount
+ " was removed!", e
);
1375 Toast
.makeText(this, R
.string
.auth_account_does_not_exist
,
1376 Toast
.LENGTH_SHORT
).show();
1385 } else if (result
.isServerFail() || result
.isException()) {
1386 /// server errors or exceptions in authorization take to requiring a new check of
1388 mServerIsChecked
= true
;
1389 mServerIsValid
= false
;
1390 mServerInfo
= new GetServerInfoOperation
.ServerInfo();
1392 // update status icon and text
1393 updateServerStatusIconAndText(result
);
1395 mAuthStatusIcon
= 0;
1396 mAuthStatusText
= 0;
1399 // update input controls state
1400 showRefreshButton(true
);
1401 mOkButton
.setEnabled(false
);
1403 // very special case (TODO: move to a common place for all the remote operations)
1404 if (result
.getCode() == ResultCode
.SSL_RECOVERABLE_PEER_UNVERIFIED
) {
1405 showUntrustedCertDialog(result
);
1408 } else { // authorization fail due to client side - probably wrong credentials
1409 updateAuthStatusIconAndText(result
);
1411 Log_OC
.d(TAG
, "Access failed: " + result
.getLogMessage());
1419 * Updates the authentication token.
1421 * Sets the proper response so that the AccountAuthenticator that started this activity
1422 * saves a new authorization token for mAccount.
1424 * Kills the session kept by OwnCloudClientManager so that a new one will created with
1425 * the new credentials when needed.
1427 private void updateAccountAuthentication() throws AccountNotFoundException
{
1429 Bundle response
= new Bundle();
1430 response
.putString(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1431 response
.putString(AccountManager
.KEY_ACCOUNT_TYPE
, mAccount
.type
);
1433 if (AccountTypeUtils
.getAuthTokenTypeAccessToken(MainApp
.getAccountType()).
1434 equals(mAuthTokenType
)) {
1435 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1436 // the next line is necessary, notifications are calling directly to the
1437 // AuthenticatorActivity to update, without AccountManager intervention
1438 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1440 } else if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1441 equals(mAuthTokenType
)) {
1443 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mAuthToken
);
1444 // the next line is necessary; by now, notifications are calling directly to the
1445 // AuthenticatorActivity to update, without AccountManager intervention
1446 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1449 response
.putString(AccountManager
.KEY_AUTHTOKEN
, mPasswordInput
.getText().toString());
1450 mAccountMgr
.setPassword(mAccount
, mPasswordInput
.getText().toString());
1452 setAccountAuthenticatorResult(response
);
1458 * Creates a new account through the Account Authenticator that started this activity.
1460 * This makes the account permanent.
1462 * TODO Decide how to name the OAuth accounts
1464 private boolean createAccount(RemoteOperationResult authResult
) {
1465 /// create and save new ownCloud account
1466 boolean isOAuth
= AccountTypeUtils
.
1467 getAuthTokenTypeAccessToken(MainApp
.getAccountType()).equals(mAuthTokenType
);
1468 boolean isSaml
= AccountTypeUtils
.
1469 getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).equals(mAuthTokenType
);
1471 String lastPermanentLocation
= authResult
.getLastPermanentLocation();
1472 if (lastPermanentLocation
!= null
) {
1473 mServerInfo
.mBaseUrl
= AccountUtils
.trimWebdavSuffix(lastPermanentLocation
);
1476 Uri uri
= Uri
.parse(mServerInfo
.mBaseUrl
);
1477 String username
= mUsernameInput
.getText().toString().trim();
1479 username
= "OAuth_user" + (new java
.util
.Random(System
.currentTimeMillis())).nextLong();
1481 String accountName
= com
.owncloud
.android
.lib
.common
.accounts
.AccountUtils
.
1482 buildAccountName(uri
, username
);
1483 Account newAccount
= new Account(accountName
, MainApp
.getAccountType());
1484 if (AccountUtils
.exists(newAccount
, getApplicationContext())) {
1485 // fail - not a new account, but an existing one; disallow
1486 RemoteOperationResult result
= new RemoteOperationResult(ResultCode
.ACCOUNT_NOT_NEW
);
1487 updateAuthStatusIconAndText(result
);
1489 Log_OC
.d(TAG
, result
.getLogMessage());
1493 mAccount
= newAccount
;
1495 if (isOAuth
|| isSaml
) {
1496 // with external authorizations, the password is never input in the app
1497 mAccountMgr
.addAccountExplicitly(mAccount
, "", null
);
1499 mAccountMgr
.addAccountExplicitly(
1500 mAccount
, mPasswordInput
.getText().toString(), null
1504 // include account version with the new account
1505 mAccountMgr
.setUserData(
1507 Constants
.KEY_OC_ACCOUNT_VERSION
,
1508 Integer
.toString(AccountUtils
.ACCOUNT_VERSION
)
1511 /// add the new account as default in preferences, if there is none already
1512 Account defaultAccount
= AccountUtils
.getCurrentOwnCloudAccount(this);
1513 if (defaultAccount
== null
) {
1514 SharedPreferences
.Editor editor
= PreferenceManager
1515 .getDefaultSharedPreferences(this).edit();
1516 editor
.putString("select_oc_account", accountName
);
1520 /// prepare result to return to the Authenticator
1521 // TODO check again what the Authenticator makes with it; probably has the same
1522 // effect as addAccountExplicitly, but it's not well done
1523 final Intent intent
= new Intent();
1524 intent
.putExtra(AccountManager
.KEY_ACCOUNT_TYPE
, MainApp
.getAccountType());
1525 intent
.putExtra(AccountManager
.KEY_ACCOUNT_NAME
, mAccount
.name
);
1526 intent
.putExtra(AccountManager
.KEY_USERDATA
, username
);
1527 if (isOAuth
|| isSaml
) {
1528 mAccountMgr
.setAuthToken(mAccount
, mAuthTokenType
, mAuthToken
);
1530 /// add user data to the new account; TODO probably can be done in the last parameter
1531 // addAccountExplicitly, or in KEY_USERDATA
1532 mAccountMgr
.setUserData(
1533 mAccount
, Constants
.KEY_OC_VERSION
, mServerInfo
.mVersion
.getVersion()
1535 mAccountMgr
.setUserData(
1536 mAccount
, Constants
.KEY_OC_BASE_URL
, mServerInfo
.mBaseUrl
1540 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_SAML_WEB_SSO
, "TRUE");
1541 } else if (isOAuth
) {
1542 mAccountMgr
.setUserData(mAccount
, Constants
.KEY_SUPPORTS_OAUTH2
, "TRUE");
1545 setAccountAuthenticatorResult(intent
.getExtras());
1546 setResult(RESULT_OK
, intent
);
1554 * Starts and activity to open the 'new account' page in the ownCloud web site
1556 * @param view 'Account register' button
1558 public void onRegisterClick(View view
) {
1559 Intent register
= new Intent(
1560 Intent
.ACTION_VIEW
, Uri
.parse(getString(R
.string
.welcome_link_url
))
1562 setResult(RESULT_CANCELED
);
1563 startActivity(register
);
1568 * Updates the content and visibility state of the icon and text associated
1569 * to the last check on the ownCloud server.
1572 private void showServerStatus() {
1573 if (mServerStatusIcon
== 0 && mServerStatusText
== 0) {
1574 mServerStatusView
.setVisibility(View
.INVISIBLE
);
1577 mServerStatusView
.setText(mServerStatusText
);
1578 mServerStatusView
.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon
, 0, 0, 0);
1579 mServerStatusView
.setVisibility(View
.VISIBLE
);
1586 * Updates the content and visibility state of the icon and text associated
1587 * to the interactions with the OAuth authorization server.
1589 private void showAuthStatus() {
1590 if (mAuthStatusIcon
== 0 && mAuthStatusText
== 0) {
1591 mAuthStatusView
.setVisibility(View
.INVISIBLE
);
1594 mAuthStatusView
.setText(mAuthStatusText
);
1595 mAuthStatusView
.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon
, 0, 0, 0);
1596 mAuthStatusView
.setVisibility(View
.VISIBLE
);
1601 private void showRefreshButton (boolean show
) {
1603 mRefreshButton
.setVisibility(View
.VISIBLE
);
1605 mRefreshButton
.setVisibility(View
.GONE
);
1610 * Called when the refresh button in the input field for ownCloud host is clicked.
1612 * Performs a new check on the URL in the input field.
1614 * @param view Refresh 'button'
1616 public void onRefreshClick(View view
) {
1622 * Called when the eye icon in the password field is clicked.
1624 * Toggles the visibility of the password in the field.
1626 public void onViewPasswordClick() {
1627 int selectionStart
= mPasswordInput
.getSelectionStart();
1628 int selectionEnd
= mPasswordInput
.getSelectionEnd();
1629 if (isPasswordVisible()) {
1634 mPasswordInput
.setSelection(selectionStart
, selectionEnd
);
1639 * Called when the checkbox for OAuth authorization is clicked.
1641 * Hides or shows the input fields for user & password.
1643 * @param view 'View password' 'button'
1645 public void onCheckClick(View view
) {
1646 CheckBox oAuth2Check
= (CheckBox
)view
;
1647 if (oAuth2Check
.isChecked()) {
1648 mAuthTokenType
= OAUTH_TOKEN_TYPE
;
1650 mAuthTokenType
= BASIC_TOKEN_TYPE
;
1652 updateAuthenticationPreFragmentVisibility();
1657 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1659 * Used to trigger the authentication check when the user presses 'enter' after writing the
1660 * password, or to throw the server test when the only field on screen is the URL input field.
1663 public boolean onEditorAction(TextView inputField
, int actionId
, KeyEvent event
) {
1664 if (actionId
== EditorInfo
.IME_ACTION_DONE
&& inputField
!= null
&&
1665 inputField
.equals(mPasswordInput
)) {
1666 if (mOkButton
.isEnabled()) {
1667 mOkButton
.performClick();
1670 } else if (actionId
== EditorInfo
.IME_ACTION_NEXT
&& inputField
!= null
&&
1671 inputField
.equals(mHostUrlInput
)) {
1672 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1673 equals(mAuthTokenType
)) {
1677 return false
; // always return false to grant that the software keyboard is hidden anyway
1681 private abstract static class RightDrawableOnTouchListener
implements OnTouchListener
{
1683 private int fuzz
= 75;
1689 public boolean onTouch(View view
, MotionEvent event
) {
1690 Drawable rightDrawable
= null
;
1691 if (view
instanceof TextView
) {
1692 Drawable
[] drawables
= ((TextView
)view
).getCompoundDrawables();
1693 if (drawables
.length
> 2) {
1694 rightDrawable
= drawables
[2];
1697 if (rightDrawable
!= null
) {
1698 final int x
= (int) event
.getX();
1699 final int y
= (int) event
.getY();
1700 final Rect bounds
= rightDrawable
.getBounds();
1701 if ( x
>= (view
.getRight() - bounds
.width() - fuzz
) &&
1702 x
<= (view
.getRight() - view
.getPaddingRight() + fuzz
) &&
1703 y
>= (view
.getPaddingTop() - fuzz
) &&
1704 y
<= (view
.getHeight() - view
.getPaddingBottom()) + fuzz
) {
1706 return onDrawableTouch(event
);
1712 public abstract boolean onDrawableTouch(final MotionEvent event
);
1716 private void getRemoteUserNameOperation(String sessionCookie
) {
1718 Intent getUserNameIntent
= new Intent();
1719 getUserNameIntent
.setAction(OperationsService
.ACTION_GET_USER_NAME
);
1720 getUserNameIntent
.putExtra(OperationsService
.EXTRA_SERVER_URL
, mServerInfo
.mBaseUrl
);
1721 getUserNameIntent
.putExtra(OperationsService
.EXTRA_COOKIE
, sessionCookie
);
1723 if (mOperationsServiceBinder
!= null
) {
1724 mWaitingForOpId
= mOperationsServiceBinder
.queueNewOperation(getUserNameIntent
);
1730 public void onSsoFinished(String sessionCookie
) {
1731 if (sessionCookie
!= null
&& sessionCookie
.length() > 0) {
1732 Log_OC
.d(TAG
, "Successful SSO - time to save the account");
1733 mAuthToken
= sessionCookie
;
1734 getRemoteUserNameOperation(sessionCookie
);
1735 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1736 if (fd
!= null
&& fd
instanceof DialogFragment
) {
1737 Dialog d
= ((DialogFragment
)fd
).getDialog();
1738 if (d
!= null
&& d
.isShowing()) {
1745 Log_OC
.d(TAG
, "SSO failed");
1751 public boolean onTouchEvent(MotionEvent event
) {
1752 if (AccountTypeUtils
.getAuthTokenTypeSamlSessionCookie(MainApp
.getAccountType()).
1753 equals(mAuthTokenType
) &&
1754 mHostUrlInput
.hasFocus() && event
.getAction() == MotionEvent
.ACTION_DOWN
) {
1757 return super.onTouchEvent(event
);
1762 * Show untrusted cert dialog
1764 public void showUntrustedCertDialog(
1765 X509Certificate x509Certificate
, SslError error
, SslErrorHandler handler
1767 // Show a dialog with the certificate info
1768 SslUntrustedCertDialog dialog
;
1769 if (x509Certificate
== null
) {
1770 dialog
= SslUntrustedCertDialog
.newInstanceForEmptySslError(error
, handler
);
1772 dialog
= SslUntrustedCertDialog
.
1773 newInstanceForFullSslError(x509Certificate
, error
, handler
);
1775 FragmentManager fm
= getSupportFragmentManager();
1776 FragmentTransaction ft
= fm
.beginTransaction();
1777 ft
.addToBackStack(null
);
1778 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1783 * Show untrusted cert dialog
1785 private void showUntrustedCertDialog(RemoteOperationResult result
) {
1786 // Show a dialog with the certificate info
1787 SslUntrustedCertDialog dialog
= SslUntrustedCertDialog
.
1788 newInstanceForFullSslError((CertificateCombinedException
)result
.getException());
1789 FragmentManager fm
= getSupportFragmentManager();
1790 FragmentTransaction ft
= fm
.beginTransaction();
1791 ft
.addToBackStack(null
);
1792 dialog
.show(ft
, UNTRUSTED_CERT_DIALOG_TAG
);
1797 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1799 public void onSavedCertificate() {
1800 Fragment fd
= getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG
);
1802 // if SAML dialog is not shown,
1803 // the SslDialog was shown due to an SSL error in the server check
1809 * Called from SslValidatorDialog when a new server certificate could not be saved
1810 * when the user requested it.
1813 public void onFailedSavingCertificate() {
1814 dismissDialog(SAML_DIALOG_TAG
);
1815 Toast
.makeText(this, R
.string
.ssl_validator_not_saved
, Toast
.LENGTH_LONG
).show();
1819 public void onCancelCertificate() {
1820 dismissDialog(SAML_DIALOG_TAG
);
1824 private void doOnResumeAndBound() {
1825 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1826 mOperationsServiceBinder
.addOperationListener(AuthenticatorActivity
.this, mHandler
);
1827 if (mWaitingForOpId
<= Integer
.MAX_VALUE
) {
1828 mOperationsServiceBinder
.dispatchResultIfFinished((int)mWaitingForOpId
, this);
1831 if (mPendingAutoCheck
) {
1837 private void dismissDialog(String dialogTag
){
1838 Fragment frag
= getSupportFragmentManager().findFragmentByTag(dialogTag
);
1839 if (frag
!= null
&& frag
instanceof DialogFragment
) {
1840 DialogFragment dialog
= (DialogFragment
) frag
;
1847 * Implements callback methods for service binding.
1849 private class OperationsServiceConnection
implements ServiceConnection
{
1852 public void onServiceConnected(ComponentName component
, IBinder service
) {
1853 if (component
.equals(
1854 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1856 mOperationsServiceBinder
= (OperationsServiceBinder
) service
;
1858 doOnResumeAndBound();
1865 public void onServiceDisconnected(ComponentName component
) {
1866 if (component
.equals(
1867 new ComponentName(AuthenticatorActivity
.this, OperationsService
.class)
1869 Log_OC
.e(TAG
, "Operations service crashed");
1870 mOperationsServiceBinder
= null
;
1877 * Create and show dialog for request authentication to the user
1878 * @param webView Web view to emebd into the authentication dialog.
1879 * @param handler Object responsible for catching and recovering HTTP authentication fails.
1881 public void createAuthenticationDialog(WebView webView
, HttpAuthHandler handler
) {
1883 // Show a dialog with the certificate info
1884 CredentialsDialogFragment dialog
=
1885 CredentialsDialogFragment
.newInstanceForCredentials(webView
, handler
);
1886 FragmentManager fm
= getSupportFragmentManager();
1887 FragmentTransaction ft
= fm
.beginTransaction();
1888 ft
.addToBackStack(null
);
1889 dialog
.setCancelable(false
);
1890 dialog
.show(ft
, CREDENTIALS_DIALOG_TAG
);
1892 if (!mIsFirstAuthAttempt
) {
1894 getApplicationContext(),
1895 getText(R
.string
.saml_authentication_wrong_pass
),
1899 mIsFirstAuthAttempt
= false
;
1904 * For retrieving the clicking on authentication cancel button
1906 public void doNegativeAuthenticatioDialogClick(){
1907 mIsFirstAuthAttempt
= true
;