fb55c147e9ce66c8e7aa02f70d325d11ef9e63b2
[pub/Android/ownCloud.git] / src / com / owncloud / android / authentication / AuthenticatorActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2013 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package com.owncloud.android.authentication;
20
21 import java.security.cert.X509Certificate;
22 import java.util.Map;
23
24 import android.accounts.Account;
25 import android.accounts.AccountManager;
26 import android.app.AlertDialog;
27 import android.app.Dialog;
28 import android.app.ProgressDialog;
29 import android.content.ComponentName;
30 import android.content.Context;
31 import android.content.DialogInterface;
32 import android.content.Intent;
33 import android.content.ServiceConnection;
34 import android.content.SharedPreferences;
35 import android.graphics.Rect;
36 import android.graphics.drawable.Drawable;
37 import android.net.Uri;
38 import android.net.http.SslError;
39 import android.os.Bundle;
40 import android.os.Handler;
41 import android.os.IBinder;
42 import android.preference.PreferenceManager;
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.Window;
55 import android.view.inputmethod.EditorInfo;
56 import android.webkit.SslErrorHandler;
57 import android.widget.Button;
58 import android.widget.CheckBox;
59 import android.widget.EditText;
60 import android.widget.TextView;
61 import android.widget.TextView.OnEditorActionListener;
62 import android.widget.Toast;
63
64 import com.actionbarsherlock.app.SherlockDialogFragment;
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.accounts.AccountTypeUtils;
69 import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;
70 import com.owncloud.android.operations.DetectAuthenticationMethodOperation.AuthenticationMethod;
71 import com.owncloud.android.operations.GetServerInfoOperation;
72 import com.owncloud.android.operations.OAuth2GetAccessToken;
73
74 import com.owncloud.android.lib.common.network.CertificateCombinedException;
75 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
76 import com.owncloud.android.lib.common.operations.RemoteOperation;
77 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
78 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
79 import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
80 import com.owncloud.android.lib.resources.users.GetRemoteUserNameOperation;
81
82 import com.owncloud.android.services.OperationsService;
83 import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
84 import com.owncloud.android.ui.dialog.SamlWebViewDialog;
85 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
86 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;
87 import com.owncloud.android.utils.Log_OC;
88 import com.owncloud.android.lib.resources.status.OwnCloudVersion;
89
90 /**
91 * This Activity is used to add an ownCloud account to the App
92 *
93 * @author Bartek Przybylski
94 * @author David A. Velasco
95 */
96 public class AuthenticatorActivity extends AccountAuthenticatorActivity
97 implements OnRemoteOperationListener, OnFocusChangeListener, OnEditorActionListener,
98 SsoWebViewClientListener, OnSslUntrustedCertListener {
99
100 private static final String TAG = AuthenticatorActivity.class.getSimpleName();
101
102 public static final String EXTRA_ACCOUNT = "ACCOUNT";
103 public static final String EXTRA_USER_NAME = "USER_NAME";
104 public static final String EXTRA_HOST_NAME = "HOST_NAME";
105 public static final String EXTRA_ACTION = "ACTION";
106 public static final String EXTRA_ENFORCED_UPDATE = "ENFORCE_UPDATE";
107
108 private static final String KEY_AUTH_MESSAGE_VISIBILITY = "AUTH_MESSAGE_VISIBILITY";
109 private static final String KEY_AUTH_MESSAGE_TEXT = "AUTH_MESSAGE_TEXT";
110 private static final String KEY_HOST_URL_TEXT = "HOST_URL_TEXT";
111 private static final String KEY_OC_VERSION = "OC_VERSION";
112 private static final String KEY_ACCOUNT = "ACCOUNT";
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_CHECK_IN_PROGRESS = "SERVER_CHECK_IN_PROGRESS";
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_VISIBLE = "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_REFRESH_BUTTON_ENABLED = "KEY_REFRESH_BUTTON_ENABLED";
123 //private static final String KEY_IS_SHARED_SUPPORTED = "KEY_IS_SHARE_SUPPORTED";
124 private static final String KEY_SERVER_AUTH_METHOD = "KEY_SERVER_AUTH_METHOD";
125 private static final String KEY_DETECT_AUTH_OP_ID = "KEY_DETECT_AUTH_OP_ID";
126
127
128 private static final String AUTH_ON = "on";
129 private static final String AUTH_OFF = "off";
130 private static final String AUTH_OPTIONAL = "optional";
131
132 private static final int DIALOG_LOGIN_PROGRESS = 0;
133 private static final int DIALOG_CERT_NOT_SAVED = 1;
134 private static final int DIALOG_OAUTH2_LOGIN_PROGRESS = 2;
135
136 public static final byte ACTION_CREATE = 0;
137 public static final byte ACTION_UPDATE_TOKEN = 1;
138
139 private static final String TAG_SAML_DIALOG = "samlWebViewDialog";
140
141 private String mHostBaseUrl; // TODO remove
142 private OwnCloudVersion mDiscoveredVersion; // TODO remove
143
144 private String mAuthMessageText;
145 private int mAuthMessageVisibility, mServerStatusText, mServerStatusIcon;
146 private boolean mServerIsChecked, mServerIsValid, mIsSslConn;
147 private AuthenticationMethod mServerAuthMethod = AuthenticationMethod.UNKNOWN;
148
149 private int mGetServerInfoOpId = -1;
150 private int mOauth2GetAccessTokenOpId = -1;
151
152 private int mAuthStatusText, mAuthStatusIcon;
153 private TextView mAuthStatusLayout;
154
155 private final Handler mHandler = new Handler();
156 private Thread mOperationThread;
157 private GetServerInfoOperation mServerInfoOperation;
158
159 private int mExistenceCheckOpId = -1;
160 private int mGetUserNameOpId = -1;
161
162 private Uri mNewCapturedUriFromOAuth2Redirection;
163
164 private AccountManager mAccountMgr;
165 private boolean mJustCreated;
166 private byte mAction;
167 private Account mAccount;
168
169 private TextView mAuthMessage;
170
171 private EditText mHostUrlInput;
172 private boolean mHostUrlInputEnabled;
173 private View mRefreshButton;
174
175 private String mAuthTokenType;
176
177 private EditText mUsernameInput;
178 private EditText mPasswordInput;
179
180 private CheckBox mOAuth2Check;
181
182 private TextView mOAuthAuthEndpointText;
183 private TextView mOAuthTokenEndpointText;
184
185 private SamlWebViewDialog mSamlDialog;
186
187 private View mOkButton;
188
189 private String mAuthToken;
190
191 private boolean mResumed; // Control if activity is resumed
192
193 public static String DIALOG_UNTRUSTED_CERT = "DIALOG_UNTRUSTED_CERT";
194
195 private ServiceConnection mOperationsServiceConnection = null;
196
197 private OperationsServiceBinder mOperationsServiceBinder = null;
198
199 private GetServerInfoOperation.ServerInfo mServerInfo;
200
201 /**
202 * {@inheritDoc}
203 *
204 * IMPORTANT ENTRY POINT 1: activity is shown to the user
205 */
206 @Override
207 protected void onCreate(Bundle savedInstanceState) {
208 super.onCreate(savedInstanceState);
209 getWindow().requestFeature(Window.FEATURE_NO_TITLE);
210
211 // bind to Operations Service
212 mOperationsServiceConnection = new OperationsServiceConnection();
213 if (!bindService(new Intent(this, OperationsService.class),
214 mOperationsServiceConnection,
215 Context.BIND_AUTO_CREATE)) {
216 Toast.makeText(this,
217 R.string.error_cant_bind_to_operations_service,
218 Toast.LENGTH_LONG)
219 .show();
220 finish();
221 }
222
223 /// set view and get references to view elements
224 setContentView(R.layout.account_setup);
225 mAuthMessage = (TextView) findViewById(R.id.auth_message);
226 mHostUrlInput = (EditText) findViewById(R.id.hostUrlInput);
227 mHostUrlInput.setText(getString(R.string.server_url)); // valid although R.string.server_url is an empty string
228 mUsernameInput = (EditText) findViewById(R.id.account_username);
229 mPasswordInput = (EditText) findViewById(R.id.account_password);
230 mOAuthAuthEndpointText = (TextView)findViewById(R.id.oAuthEntryPoint_1);
231 mOAuthTokenEndpointText = (TextView)findViewById(R.id.oAuthEntryPoint_2);
232 mOAuth2Check = (CheckBox) findViewById(R.id.oauth_onOff_check);
233 mOkButton = findViewById(R.id.buttonOK);
234 mAuthStatusLayout = (TextView) findViewById(R.id.auth_status_text);
235
236 /// set Host Url Input Enabled
237 mHostUrlInputEnabled = getResources().getBoolean(R.bool.show_server_url_input);
238
239 /// set visibility of link for new users
240 boolean accountRegisterVisibility = getResources().getBoolean(R.bool.show_welcome_link);
241 Button welcomeLink = (Button) findViewById(R.id.welcome_link);
242 if (welcomeLink != null) {
243 if (accountRegisterVisibility) {
244 welcomeLink.setVisibility(View.VISIBLE);
245 welcomeLink.setText(String.format(getString(R.string.auth_register), getString(R.string.app_name)));
246 } else {
247 findViewById(R.id.welcome_link).setVisibility(View.GONE);
248 }
249 }
250
251 /// initialization
252 mAccountMgr = AccountManager.get(this);
253 mNewCapturedUriFromOAuth2Redirection = null;
254 mAction = getIntent().getByteExtra(EXTRA_ACTION, ACTION_CREATE);
255 mAccount = null;
256 mHostBaseUrl = "";
257 boolean refreshButtonEnabled = false;
258
259 // URL input configuration applied
260 if (!mHostUrlInputEnabled)
261 {
262 findViewById(R.id.hostUrlFrame).setVisibility(View.GONE);
263 mRefreshButton = findViewById(R.id.centeredRefreshButton);
264
265 } else {
266 mRefreshButton = findViewById(R.id.embeddedRefreshButton);
267 }
268
269 if (savedInstanceState == null) {
270 mResumed = false;
271 /// connection state and info
272 mAuthMessageVisibility = View.GONE;
273 mServerStatusText = mServerStatusIcon = 0;
274 mServerIsValid = false;
275 mServerIsChecked = false;
276 mIsSslConn = false;
277 mAuthStatusText = mAuthStatusIcon = 0;
278
279 /// retrieve extras from intent
280 mAccount = getIntent().getExtras().getParcelable(EXTRA_ACCOUNT);
281 if (mAccount != null) {
282 String ocVersion = mAccountMgr.getUserData(mAccount, Constants.KEY_OC_VERSION);
283 if (ocVersion != null) {
284 mDiscoveredVersion = new OwnCloudVersion(ocVersion);
285 }
286 mHostBaseUrl = normalizeUrl(mAccountMgr.getUserData(mAccount, Constants.KEY_OC_BASE_URL));
287 mHostUrlInput.setText(mHostBaseUrl);
288 String userName = mAccount.name.substring(0, mAccount.name.lastIndexOf('@'));
289 mUsernameInput.setText(userName);
290
291 }
292 initAuthorizationMethod(); // checks intent and setup.xml to determine mCurrentAuthorizationMethod
293 mJustCreated = true;
294
295 if (mAction == ACTION_UPDATE_TOKEN || !mHostUrlInputEnabled) {
296 checkOcServer();
297 }
298
299 } else {
300 mResumed = true;
301 /// connection state and info
302 mAuthMessageVisibility = savedInstanceState.getInt(KEY_AUTH_MESSAGE_VISIBILITY);
303 mAuthMessageText = savedInstanceState.getString(KEY_AUTH_MESSAGE_TEXT);
304 mServerIsValid = savedInstanceState.getBoolean(KEY_SERVER_VALID);
305 mServerIsChecked = savedInstanceState.getBoolean(KEY_SERVER_CHECKED);
306 mServerStatusText = savedInstanceState.getInt(KEY_SERVER_STATUS_TEXT);
307 mServerStatusIcon = savedInstanceState.getInt(KEY_SERVER_STATUS_ICON);
308 mIsSslConn = savedInstanceState.getBoolean(KEY_IS_SSL_CONN);
309 mAuthStatusText = savedInstanceState.getInt(KEY_AUTH_STATUS_TEXT);
310 mAuthStatusIcon = savedInstanceState.getInt(KEY_AUTH_STATUS_ICON);
311 if (savedInstanceState.getBoolean(KEY_PASSWORD_VISIBLE, false)) {
312 showPassword();
313 }
314
315 /// server data
316 String ocVersion = savedInstanceState.getString(KEY_OC_VERSION);
317 if (ocVersion != null) {
318 mDiscoveredVersion = new OwnCloudVersion(ocVersion);
319 }
320 mHostBaseUrl = savedInstanceState.getString(KEY_HOST_URL_TEXT);
321
322 // account data, if updating
323 mAccount = savedInstanceState.getParcelable(KEY_ACCOUNT);
324 mAuthTokenType = savedInstanceState.getString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE);
325 if (mAuthTokenType == null) {
326 mAuthTokenType = AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());
327
328 }
329
330 // check if server check was interrupted by a configuration change
331 if (savedInstanceState.getBoolean(KEY_SERVER_CHECK_IN_PROGRESS, false)) {
332 checkOcServer();
333 }
334
335 // refresh button enabled
336 refreshButtonEnabled = savedInstanceState.getBoolean(KEY_REFRESH_BUTTON_ENABLED);
337
338
339 mServerAuthMethod = AuthenticationMethod.valueOf(
340 savedInstanceState.getString(KEY_SERVER_AUTH_METHOD));
341 mGetServerInfoOpId = savedInstanceState.getInt(KEY_DETECT_AUTH_OP_ID);
342
343 }
344
345 if (mAuthMessageVisibility== View.VISIBLE) {
346 showAuthMessage(mAuthMessageText);
347 }
348 else {
349 hideAuthMessage();
350 }
351 adaptViewAccordingToAuthenticationMethod();
352 showServerStatus();
353 showAuthStatus();
354
355 if (mAction == ACTION_UPDATE_TOKEN) {
356 /// lock things that should not change
357 mHostUrlInput.setEnabled(false);
358 mHostUrlInput.setFocusable(false);
359 mUsernameInput.setEnabled(false);
360 mUsernameInput.setFocusable(false);
361 mOAuth2Check.setVisibility(View.GONE);
362 }
363
364 showRefreshButton(mServerIsChecked && !mServerIsValid && refreshButtonEnabled);
365 mOkButton.setEnabled(mServerIsValid); // state not automatically recovered in configuration changes
366
367 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType) ||
368 !AUTH_OPTIONAL.equals(getString(R.string.auth_method_oauth2))) {
369 mOAuth2Check.setVisibility(View.GONE);
370 }
371
372 mPasswordInput.setText(""); // clean password to avoid social hacking (disadvantage: password in removed if the device is turned aside)
373
374 /// bind view elements to listeners and other friends
375 mHostUrlInput.setOnFocusChangeListener(this);
376 mHostUrlInput.setImeOptions(EditorInfo.IME_ACTION_NEXT);
377 mHostUrlInput.setOnEditorActionListener(this);
378 mHostUrlInput.addTextChangedListener(new TextWatcher() {
379
380 @Override
381 public void afterTextChanged(Editable s) {
382 if (!mHostBaseUrl.equals(normalizeUrl(mHostUrlInput.getText().toString()))) {
383 mOkButton.setEnabled(false);
384 }
385 }
386
387 @Override
388 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
389 }
390
391 @Override
392 public void onTextChanged(CharSequence s, int start, int before, int count) {
393 if (!mResumed) {
394 mAuthStatusIcon = 0;
395 mAuthStatusText = 0;
396 showAuthStatus();
397 }
398 mResumed = false;
399 }
400 });
401
402 mPasswordInput.setOnFocusChangeListener(this);
403 mPasswordInput.setImeOptions(EditorInfo.IME_ACTION_DONE);
404 mPasswordInput.setOnEditorActionListener(this);
405 mPasswordInput.setOnTouchListener(new RightDrawableOnTouchListener() {
406 @Override
407 public boolean onDrawableTouch(final MotionEvent event) {
408 if (event.getAction() == MotionEvent.ACTION_UP) {
409 AuthenticatorActivity.this.onViewPasswordClick();
410 }
411 return true;
412 }
413 });
414
415 findViewById(R.id.scroll).setOnTouchListener(new OnTouchListener() {
416 @Override
417 public boolean onTouch(View view, MotionEvent event) {
418 if (event.getAction() == MotionEvent.ACTION_DOWN) {
419 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType) &&
420 mHostUrlInput.hasFocus()) {
421 checkOcServer();
422 }
423 }
424 return false;
425 }
426 });
427
428 }
429
430
431
432 private void initAuthorizationMethod() {
433 boolean oAuthRequired = false;
434 boolean samlWebSsoRequired = false;
435
436 mAuthTokenType = getIntent().getExtras().getString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE);
437 mAccount = getIntent().getExtras().getParcelable(EXTRA_ACCOUNT);
438
439 // TODO could be a good moment to validate the received token type, if not null
440
441 if (mAuthTokenType == null) {
442 if (mAccount != null) {
443 /// same authentication method than the one used to create the account to update
444 oAuthRequired = (mAccountMgr.getUserData(mAccount, Constants.KEY_SUPPORTS_OAUTH2) != null);
445 samlWebSsoRequired = (mAccountMgr.getUserData(mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO) != null);
446
447 } else {
448 /// use the one set in setup.xml
449 oAuthRequired = AUTH_ON.equals(getString(R.string.auth_method_oauth2));
450 samlWebSsoRequired = AUTH_ON.equals(getString(R.string.auth_method_saml_web_sso));
451 }
452 if (oAuthRequired) {
453 mAuthTokenType = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType());
454 } else if (samlWebSsoRequired) {
455 mAuthTokenType = AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType());
456 } else {
457 mAuthTokenType = AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());
458 }
459 }
460
461 if (mAccount != null) {
462 String userName = mAccount.name.substring(0, mAccount.name.lastIndexOf('@'));
463 mUsernameInput.setText(userName);
464 }
465
466 mOAuth2Check.setChecked(AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType));
467
468 }
469
470 /**
471 * Saves relevant state before {@link #onPause()}
472 *
473 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag, intended to defer the
474 * processing of the redirection caught in {@link #onNewIntent(Intent)} until {@link #onResume()}
475 *
476 * See {@link #loadSavedInstanceState(Bundle)}
477 */
478 @Override
479 protected void onSaveInstanceState(Bundle outState) {
480 //Log.wtf(TAG, "onSaveInstanceState init" );
481 super.onSaveInstanceState(outState);
482
483 /// connection state and info
484 outState.putInt(KEY_AUTH_MESSAGE_VISIBILITY, mAuthMessage.getVisibility());
485 outState.putString(KEY_AUTH_MESSAGE_TEXT, mAuthMessage.getText().toString());
486 outState.putInt(KEY_SERVER_STATUS_TEXT, mServerStatusText);
487 outState.putInt(KEY_SERVER_STATUS_ICON, mServerStatusIcon);
488 outState.putBoolean(KEY_SERVER_VALID, mServerIsValid);
489 outState.putBoolean(KEY_SERVER_CHECKED, mServerIsChecked);
490 outState.putBoolean(KEY_SERVER_CHECK_IN_PROGRESS, (!mServerIsValid && mServerInfoOperation != null));
491 outState.putBoolean(KEY_IS_SSL_CONN, mIsSslConn);
492 outState.putBoolean(KEY_PASSWORD_VISIBLE, isPasswordVisible());
493 outState.putInt(KEY_AUTH_STATUS_ICON, mAuthStatusIcon);
494 outState.putInt(KEY_AUTH_STATUS_TEXT, mAuthStatusText);
495
496 /// server data
497 if (mDiscoveredVersion != null) {
498 outState.putString(KEY_OC_VERSION, mDiscoveredVersion.getVersion());
499 }
500 outState.putString(KEY_HOST_URL_TEXT, mHostBaseUrl);
501
502 /// account data, if updating
503 if (mAccount != null) {
504 outState.putParcelable(KEY_ACCOUNT, mAccount);
505 }
506 outState.putString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE, mAuthTokenType);
507
508 // refresh button enabled
509 outState.putBoolean(KEY_REFRESH_BUTTON_ENABLED, (mRefreshButton.getVisibility() == View.VISIBLE));
510
511 outState.putString(KEY_SERVER_AUTH_METHOD, mServerAuthMethod.name());
512 outState.putInt(KEY_DETECT_AUTH_OP_ID, mGetServerInfoOpId);
513 //Log.wtf(TAG, "onSaveInstanceState end" );
514 }
515
516
517 /**
518 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION request
519 * is caught here.
520 *
521 * To make this possible, this activity needs to be qualified with android:launchMode = "singleTask" in the
522 * AndroidManifest.xml file.
523 */
524 @Override
525 protected void onNewIntent (Intent intent) {
526 Log_OC.d(TAG, "onNewIntent()");
527 Uri data = intent.getData();
528 if (data != null && data.toString().startsWith(getString(R.string.oauth2_redirect_uri))) {
529 mNewCapturedUriFromOAuth2Redirection = data;
530 }
531 }
532
533
534 /**
535 * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION, and
536 * deferred in {@link #onNewIntent(Intent)}, is processed here.
537 */
538 @Override
539 protected void onResume() {
540 //Log.wtf(TAG, "onResume init" );
541 super.onResume();
542
543 if (mAction == ACTION_UPDATE_TOKEN && mJustCreated && getIntent().getBooleanExtra(EXTRA_ENFORCED_UPDATE, false)) {
544 if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType)) {
545 //Toast.makeText(this, R.string.auth_expired_oauth_token_toast, Toast.LENGTH_LONG).show();
546 showAuthMessage(getString(R.string.auth_expired_oauth_token_toast));
547 } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {
548 //Toast.makeText(this, R.string.auth_expired_saml_sso_token_toast, Toast.LENGTH_LONG).show();
549 showAuthMessage(getString(R.string.auth_expired_saml_sso_token_toast));
550 } else {
551 //Toast.makeText(this, R.string.auth_expired_basic_auth_toast, Toast.LENGTH_LONG).show();
552 showAuthMessage(getString(R.string.auth_expired_basic_auth_toast));
553 }
554 }
555
556 if (mNewCapturedUriFromOAuth2Redirection != null) {
557 getOAuth2AccessTokenFromCapturedRedirection();
558 }
559
560 mJustCreated = false;
561
562 if (mOperationsServiceBinder != null) {
563 doOnResumeAndBound();
564 }
565
566 //Log.wtf(TAG, "onResume end" );
567 }
568
569
570 @Override
571 protected void onPause() {
572 //Log.wtf(TAG, "onPause init" );
573 if (mOperationsServiceBinder != null) {
574 //Log.wtf(TAG, "unregistering to listen for operation callbacks" );
575 mOperationsServiceBinder.removeOperationListener(this);
576 }
577 super.onPause();
578 //Log.wtf(TAG, "onPause end" );
579 }
580
581 @Override
582 protected void onDestroy() {
583 if (mOperationsServiceConnection != null) {
584 unbindService(mOperationsServiceConnection);
585 mOperationsServiceBinder = null;
586 }
587 super.onDestroy();
588 }
589
590
591 /**
592 * Parses the redirection with the response to the GET AUTHORIZATION request to the
593 * oAuth server and requests for the access token (GET ACCESS TOKEN)
594 */
595 private void getOAuth2AccessTokenFromCapturedRedirection() {
596 /// Parse data from OAuth redirection
597 String queryParameters = mNewCapturedUriFromOAuth2Redirection.getQuery();
598 mNewCapturedUriFromOAuth2Redirection = null;
599
600 /// Showing the dialog with instructions for the user.
601 showDialog(DIALOG_OAUTH2_LOGIN_PROGRESS);
602
603 /// GET ACCESS TOKEN to the oAuth server
604 Intent getServerInfoIntent = new Intent();
605 getServerInfoIntent.setAction(OperationsService.ACTION_OAUTH2_GET_ACCESS_TOKEN);
606
607 getServerInfoIntent.putExtra(
608 OperationsService.EXTRA_SERVER_URL,
609 mOAuthTokenEndpointText.getText().toString().trim());
610
611 getServerInfoIntent.putExtra(
612 OperationsService.EXTRA_OAUTH2_QUERY_PARAMETERS,
613 queryParameters);
614
615 if (mOperationsServiceBinder != null) {
616 //Log.wtf(TAG, "getting access token..." );
617 mOauth2GetAccessTokenOpId = mOperationsServiceBinder.newOperation(getServerInfoIntent);
618 }
619
620 /*
621 RemoteOperation operation = new OAuth2GetAccessToken( getString(R.string.oauth2_client_id),
622 getString(R.string.oauth2_redirect_uri),
623 getString(R.string.oauth2_grant_type),
624 queryParameters);
625 //OwnCloudClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(getString(R.string.oauth2_url_endpoint_access)), getApplicationContext());
626 OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(mOAuthTokenEndpointText.getText().toString().trim()), getApplicationContext(), true);
627 operation.execute(client, this, mHandler);
628 */
629
630 }
631
632
633
634 /**
635 * Handles the change of focus on the text inputs for the server URL and the password
636 */
637 public void onFocusChange(View view, boolean hasFocus) {
638 if (view.getId() == R.id.hostUrlInput) {
639 if (!hasFocus) {
640 onUrlInputFocusLost((TextView) view);
641 }
642 else {
643 showRefreshButton(false);
644 }
645
646 } else if (view.getId() == R.id.account_password) {
647 onPasswordFocusChanged((TextView) view, hasFocus);
648 }
649 }
650
651
652 /**
653 * Handles changes in focus on the text input for the server URL.
654 *
655 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
656 * other field. The operation to check the existence of the server in the entered URL is
657 * started.
658 *
659 * When hasFocus: user 'comes back' to write again the server URL.
660 *
661 * @param hostInput TextView with the URL input field receiving the change of focus.
662 */
663 private void onUrlInputFocusLost(TextView hostInput) {
664 if (!mHostBaseUrl.equals(normalizeUrl(mHostUrlInput.getText().toString()))) {
665 checkOcServer();
666 } else {
667 mOkButton.setEnabled(mServerIsValid);
668 showRefreshButton(!mServerIsValid);
669 }
670 }
671
672
673 private void checkOcServer() {
674 String uri = mHostUrlInput.getText().toString().trim();
675
676 if (!mHostUrlInputEnabled){
677 uri = getString(R.string.server_url).trim();
678 }
679
680 mServerIsValid = false;
681 mServerIsChecked = false;
682 mOkButton.setEnabled(false);
683 mDiscoveredVersion = null;
684 mServerAuthMethod = AuthenticationMethod.UNKNOWN;
685 showRefreshButton(false);
686
687 if (uri.length() != 0) {
688 mServerStatusText = R.string.auth_testing_connection;
689 mServerStatusIcon = R.drawable.progress_small;
690 showServerStatus();
691
692 Intent getServerInfoIntent = new Intent();
693 getServerInfoIntent.setAction(OperationsService.ACTION_GET_SERVER_INFO);
694 getServerInfoIntent.putExtra(OperationsService.EXTRA_SERVER_URL, uri);
695 getServerInfoIntent.putExtra(OperationsService.EXTRA_AUTH_TOKEN_TYPE, mAuthTokenType);
696 if (mOperationsServiceBinder != null) {
697 //Log.wtf(TAG, "checking server..." );
698 mGetServerInfoOpId = mOperationsServiceBinder.newOperation(getServerInfoIntent);
699 }
700
701 } else {
702 mServerStatusText = 0;
703 mServerStatusIcon = 0;
704 showServerStatus();
705 }
706 }
707
708
709 /**
710 * Handles changes in focus on the text input for the password (basic authorization).
711 *
712 * When (hasFocus), the button to toggle password visibility is shown.
713 *
714 * When (!hasFocus), the button is made invisible and the password is hidden.
715 *
716 * @param passwordInput TextView with the password input field receiving the change of focus.
717 * @param hasFocus 'True' if focus is received, 'false' if is lost
718 */
719 private void onPasswordFocusChanged(TextView passwordInput, boolean hasFocus) {
720 if (hasFocus) {
721 showViewPasswordButton();
722 } else {
723 hidePassword();
724 hidePasswordButton();
725 }
726 }
727
728
729 private void showViewPasswordButton() {
730 //int drawable = android.R.drawable.ic_menu_view;
731 int drawable = R.drawable.ic_view;
732 if (isPasswordVisible()) {
733 //drawable = android.R.drawable.ic_secure;
734 drawable = R.drawable.ic_hide;
735 }
736 mPasswordInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable, 0);
737 }
738
739 private boolean isPasswordVisible() {
740 return ((mPasswordInput.getInputType() & InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
741 }
742
743 private void hidePasswordButton() {
744 mPasswordInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
745 }
746
747 private void showPassword() {
748 mPasswordInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
749 showViewPasswordButton();
750 }
751
752 private void hidePassword() {
753 mPasswordInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
754 showViewPasswordButton();
755 }
756
757
758 /**
759 * Cancels the authenticator activity
760 *
761 * IMPORTANT ENTRY POINT 3: Never underestimate the importance of cancellation
762 *
763 * This method is bound in the layout/acceoun_setup.xml resource file.
764 *
765 * @param view Cancel button
766 */
767 public void onCancelClick(View view) {
768 setResult(RESULT_CANCELED); // TODO review how is this related to AccountAuthenticator (debugging)
769 finish();
770 }
771
772
773
774 /**
775 * Checks the credentials of the user in the root of the ownCloud server
776 * before creating a new local account.
777 *
778 * For basic authorization, a check of existence of the root folder is
779 * performed.
780 *
781 * For OAuth, starts the flow to get an access token; the credentials test
782 * is postponed until it is available.
783 *
784 * IMPORTANT ENTRY POINT 4
785 *
786 * @param view OK button
787 */
788 public void onOkClick(View view) {
789 // this check should be unnecessary
790 if (mDiscoveredVersion == null || !mDiscoveredVersion.isVersionValid() || mHostBaseUrl == null || mHostBaseUrl.length() == 0) {
791 mServerStatusIcon = R.drawable.common_error;
792 mServerStatusText = R.string.auth_wtf_reenter_URL;
793 showServerStatus();
794 mOkButton.setEnabled(false);
795 Log_OC.wtf(TAG, "The user was allowed to click 'connect' to an unchecked server!!");
796 return;
797 }
798
799 if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType)) {
800 startOauthorization();
801 } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {
802 startSamlBasedFederatedSingleSignOnAuthorization();
803 } else {
804 checkBasicAuthorization();
805 }
806 }
807
808
809 /**
810 * Tests the credentials entered by the user performing a check of existence on
811 * the root folder of the ownCloud server.
812 */
813 private void checkBasicAuthorization() {
814 /// get the path to the root folder through WebDAV from the version server
815 String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, mAuthTokenType);
816
817 /// get basic credentials entered by user
818 String username = mUsernameInput.getText().toString();
819 String password = mPasswordInput.getText().toString();
820
821 /// be gentle with the user
822 showDialog(DIALOG_LOGIN_PROGRESS);
823
824 /// test credentials accessing the root folder
825 String remotePath ="";
826 boolean successIfAbsent = false;
827 boolean followRedirects = true;
828 startExistenceCheckRemoteOperation(remotePath, this, successIfAbsent, webdav_path, username, password, followRedirects);
829
830 }
831
832 private void startExistenceCheckRemoteOperation(String remotePath, Context context, boolean successIfAbsent, String webdav_path,
833 String username, String password, boolean followRedirects) {
834
835 Intent existenceCheckIntent = new Intent();
836 existenceCheckIntent.setAction(OperationsService.ACTION_EXISTENCE_CHECK);
837 existenceCheckIntent.putExtra(OperationsService.EXTRA_SERVER_URL, mHostBaseUrl);
838 existenceCheckIntent.putExtra(OperationsService.EXTRA_REMOTE_PATH, remotePath);
839 existenceCheckIntent.putExtra(OperationsService.EXTRA_SUCCESS_IF_ABSENT, successIfAbsent);
840 existenceCheckIntent.putExtra(OperationsService.EXTRA_WEBDAV_PATH, webdav_path);
841 existenceCheckIntent.putExtra(OperationsService.EXTRA_USERNAME, username);
842 existenceCheckIntent.putExtra(OperationsService.EXTRA_PASSWORD, password);
843 existenceCheckIntent.putExtra(OperationsService.EXTRA_AUTH_TOKEN, mAuthToken);
844 existenceCheckIntent.putExtra(OperationsService.EXTRA_FOLLOW_REDIRECTS, followRedirects);
845
846 if (mOperationsServiceBinder != null) {
847 Log_OC.wtf(TAG, "starting existenceCheckRemoteOperation..." );
848 mExistenceCheckOpId = mOperationsServiceBinder.newOperation(existenceCheckIntent);
849 }
850 }
851
852 /**
853 * Starts the OAuth 'grant type' flow to get an access token, with
854 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
855 */
856 private void startOauthorization() {
857 // be gentle with the user
858 mAuthStatusIcon = R.drawable.progress_small;
859 mAuthStatusText = R.string.oauth_login_connection;
860 showAuthStatus();
861
862 // GET AUTHORIZATION request
863 //Uri uri = Uri.parse(getString(R.string.oauth2_url_endpoint_auth));
864 Uri uri = Uri.parse(mOAuthAuthEndpointText.getText().toString().trim());
865 Uri.Builder uriBuilder = uri.buildUpon();
866 uriBuilder.appendQueryParameter(OAuth2Constants.KEY_RESPONSE_TYPE, getString(R.string.oauth2_response_type));
867 uriBuilder.appendQueryParameter(OAuth2Constants.KEY_REDIRECT_URI, getString(R.string.oauth2_redirect_uri));
868 uriBuilder.appendQueryParameter(OAuth2Constants.KEY_CLIENT_ID, getString(R.string.oauth2_client_id));
869 uriBuilder.appendQueryParameter(OAuth2Constants.KEY_SCOPE, getString(R.string.oauth2_scope));
870 //uriBuilder.appendQueryParameter(OAuth2Constants.KEY_STATE, whateverwewant);
871 uri = uriBuilder.build();
872 Log_OC.d(TAG, "Starting browser to view " + uri.toString());
873 Intent i = new Intent(Intent.ACTION_VIEW, uri);
874 startActivity(i);
875 }
876
877
878 /**
879 * Starts the Web Single Sign On flow to get access to the root folder
880 * in the server.
881 */
882 private void startSamlBasedFederatedSingleSignOnAuthorization() {
883 // be gentle with the user
884 mAuthStatusIcon = R.drawable.progress_small;
885 mAuthStatusText = R.string.auth_connecting_auth_server;
886 showAuthStatus();
887 showDialog(DIALOG_LOGIN_PROGRESS);
888
889 /// get the path to the root folder through WebDAV from the version server
890 String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, mAuthTokenType);
891
892 /// test credentials accessing the root folder
893 String remotePath ="";
894 boolean successIfAbsent = false;
895 boolean followRedirections = false;
896 startExistenceCheckRemoteOperation(remotePath, this, successIfAbsent, webdav_path, "", "", followRedirections);
897
898 }
899
900 /**
901 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
902 *
903 * Dispatches the operation flow to the right method.
904 */
905 @Override
906 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
907
908 if (operation instanceof GetServerInfoOperation) {
909 if (operation.hashCode() == mGetServerInfoOpId) {
910 onGetServerInfoFinish(result);
911 } // else nothing ; only the last check operation is considered;
912 // multiple can be started if the user amends a URL quickly
913
914 } else if (operation instanceof OAuth2GetAccessToken) {
915 onGetOAuthAccessTokenFinish(result);
916
917 } else if (operation instanceof ExistenceCheckRemoteOperation) {
918 Log_OC.wtf(TAG, "received detection response through callback" );
919 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {
920 onSamlBasedFederatedSingleSignOnAuthorizationStart(result);
921
922 } else {
923 onAuthorizationCheckFinish(result);
924 }
925 } else if (operation instanceof GetRemoteUserNameOperation) {
926 onGetUserNameFinish(result);
927 }
928
929 }
930
931 private void onGetUserNameFinish(RemoteOperationResult result) {
932 mGetUserNameOpId = -1;
933 if (result.isSuccess()) {
934 boolean success = false;
935 String username = (String) result.getData().get(0);
936
937 if ( mAction == ACTION_CREATE) {
938 mUsernameInput.setText(username);
939 success = createAccount();
940 } else {
941
942 if (!mUsernameInput.getText().toString().equals(username)) {
943 // fail - not a new account, but an existing one; disallow
944 result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_THE_SAME);
945 updateAuthStatusIconAndText(result);
946 showAuthStatus();
947 Log_OC.d(TAG, result.getLogMessage());
948 } else {
949 updateToken();
950 success = true;
951 }
952 }
953
954 if (success)
955 finish();
956 } else {
957 updateStatusIconFailUserName();
958 showAuthStatus();
959 Log_OC.e(TAG, "Access to user name failed: " + result.getLogMessage());
960 }
961
962 }
963
964 private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperationResult result) {
965 mExistenceCheckOpId = -1;
966 try {
967 dismissDialog(DIALOG_LOGIN_PROGRESS);
968 } catch (IllegalArgumentException e) {
969 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
970 }
971
972 //if (result.isTemporalRedirection() && result.isIdPRedirection()) {
973 if (result.isIdPRedirection()) {
974 String url = result.getRedirectedLocation();
975 String targetUrl = mHostBaseUrl + AccountUtils.getWebdavPath(mDiscoveredVersion, mAuthTokenType);
976
977 // Show dialog
978 mSamlDialog = SamlWebViewDialog.newInstance(url, targetUrl);
979 mSamlDialog.show(getSupportFragmentManager(), TAG_SAML_DIALOG);
980
981 mAuthStatusIcon = 0;
982 mAuthStatusText = 0;
983
984 } else {
985 mAuthStatusIcon = R.drawable.common_error;
986 mAuthStatusText = R.string.auth_unsupported_auth_method;
987
988 }
989 showAuthStatus();
990 }
991
992
993 /**
994 * Processes the result of the server check performed when the user finishes the enter of the
995 * server URL.
996 *
997 * @param operation Server check performed.
998 * @param result Result of the check.
999 */
1000 private void onGetServerInfoFinish(RemoteOperationResult result) {
1001 /// update activity state
1002 mServerIsChecked = true;
1003 mIsSslConn = (result.getCode() == ResultCode.OK_SSL);
1004 mServerInfoOperation = null;
1005 mGetServerInfoOpId = -1;
1006
1007 // update server status, but don't show it yet
1008 updateServerStatusIconAndText(result);
1009
1010 if (result.isSuccess()) {
1011 /// SUCCESS means:
1012 // 1. connection succeeded, and we know if it's SSL or not
1013 // 2. server is installed
1014 // 3. we got the server version
1015 // 4. we got the authentication method required by the server
1016 mServerInfo = (GetServerInfoOperation.ServerInfo) (result.getData().get(0));
1017 mDiscoveredVersion = mServerInfo.mVersion;
1018 mHostBaseUrl = mServerInfo.mBaseUrl;
1019 mServerAuthMethod = mServerInfo.mAuthMethod;
1020
1021 if (!authSupported(mServerAuthMethod)) {
1022
1023 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1024 mServerIsValid = false;
1025
1026 } else {
1027 mServerIsValid = true;
1028 }
1029
1030 } else {
1031 mServerIsValid = false;
1032 }
1033
1034 // refresh UI
1035 showRefreshButton(!mServerIsValid);
1036 showServerStatus();
1037 mOkButton.setEnabled(mServerIsValid);
1038
1039 /// very special case (TODO: move to a common place for all the remote operations)
1040 if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
1041 showUntrustedCertDialog(result);
1042 }
1043 }
1044
1045
1046 private boolean authSupported(AuthenticationMethod authMethod) {
1047 String basic = AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());
1048 String oAuth = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType());
1049 String saml = AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType());
1050
1051 return (( mAuthTokenType.equals(basic) &&
1052 authMethod.equals(AuthenticationMethod.BASIC_HTTP_AUTH) ) ||
1053 ( mAuthTokenType.equals(oAuth) &&
1054 authMethod.equals(AuthenticationMethod.BEARER_TOKEN)) ||
1055 ( mAuthTokenType.equals(saml) &&
1056 authMethod.equals(AuthenticationMethod.SAML_WEB_SSO))
1057 );
1058 }
1059
1060
1061 // TODO remove, if possible
1062 private String normalizeUrl(String url) {
1063 if (url != null && url.length() > 0) {
1064 url = url.trim();
1065 if (!url.toLowerCase().startsWith("http://") &&
1066 !url.toLowerCase().startsWith("https://")) {
1067 if (mIsSslConn) {
1068 url = "https://" + url;
1069 } else {
1070 url = "http://" + url;
1071 }
1072 }
1073
1074 url = trimUrlWebdav(url);
1075
1076 if (url.endsWith("/")) {
1077 url = url.substring(0, url.length() - 1);
1078 }
1079
1080 }
1081 return (url != null ? url : "");
1082 }
1083
1084
1085 // TODO remove, if possible
1086 private String trimUrlWebdav(String url){
1087 if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0)){
1088 url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0.length());
1089 } else if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_2_0)){
1090 url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_2_0.length());
1091 } else if (url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_1_2)){
1092 url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_1_2.length());
1093 }
1094 return (url != null ? url : "");
1095 }
1096
1097
1098 /**
1099 * Chooses the right icon and text to show to the user for the received operation result.
1100 *
1101 * @param result Result of a remote operation performed in this activity
1102 */
1103 private void updateServerStatusIconAndText(RemoteOperationResult result) {
1104 mServerStatusIcon = R.drawable.common_error; // the most common case in the switch below
1105
1106 switch (result.getCode()) {
1107 case OK_SSL:
1108 mServerStatusIcon = android.R.drawable.ic_secure;
1109 mServerStatusText = R.string.auth_secure_connection;
1110 break;
1111
1112 case OK_NO_SSL:
1113 case OK:
1114 if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1115 mServerStatusText = R.string.auth_connection_established;
1116 mServerStatusIcon = R.drawable.ic_ok;
1117 } else {
1118 mServerStatusText = R.string.auth_nossl_plain_ok_title;
1119 mServerStatusIcon = android.R.drawable.ic_partial_secure;
1120 }
1121 break;
1122
1123 case NO_NETWORK_CONNECTION:
1124 mServerStatusIcon = R.drawable.no_network;
1125 mServerStatusText = R.string.auth_no_net_conn_title;
1126 break;
1127
1128 case SSL_RECOVERABLE_PEER_UNVERIFIED:
1129 mServerStatusText = R.string.auth_ssl_unverified_server_title;
1130 break;
1131 case BAD_OC_VERSION:
1132 mServerStatusText = R.string.auth_bad_oc_version_title;
1133 break;
1134 case WRONG_CONNECTION:
1135 mServerStatusText = R.string.auth_wrong_connection_title;
1136 break;
1137 case TIMEOUT:
1138 mServerStatusText = R.string.auth_timeout_title;
1139 break;
1140 case INCORRECT_ADDRESS:
1141 mServerStatusText = R.string.auth_incorrect_address_title;
1142 break;
1143 case SSL_ERROR:
1144 mServerStatusText = R.string.auth_ssl_general_error_title;
1145 break;
1146 case UNAUTHORIZED:
1147 mServerStatusText = R.string.auth_unauthorized;
1148 break;
1149 case HOST_NOT_AVAILABLE:
1150 mServerStatusText = R.string.auth_unknown_host_title;
1151 break;
1152 case INSTANCE_NOT_CONFIGURED:
1153 mServerStatusText = R.string.auth_not_configured_title;
1154 break;
1155 case FILE_NOT_FOUND:
1156 mServerStatusText = R.string.auth_incorrect_path_title;
1157 break;
1158 case OAUTH2_ERROR:
1159 mServerStatusText = R.string.auth_oauth_error;
1160 break;
1161 case OAUTH2_ERROR_ACCESS_DENIED:
1162 mServerStatusText = R.string.auth_oauth_error_access_denied;
1163 break;
1164 case UNHANDLED_HTTP_CODE:
1165 case UNKNOWN_ERROR:
1166 mServerStatusText = R.string.auth_unknown_error_title;
1167 break;
1168 default:
1169 mServerStatusText = 0;
1170 mServerStatusIcon = 0;
1171 }
1172 }
1173
1174
1175 /**
1176 * Chooses the right icon and text to show to the user for the received operation result.
1177 *
1178 * @param result Result of a remote operation performed in this activity
1179 */
1180 private void updateAuthStatusIconAndText(RemoteOperationResult result) {
1181 mAuthStatusIcon = R.drawable.common_error; // the most common case in the switch below
1182
1183 switch (result.getCode()) {
1184 case OK_SSL:
1185 mAuthStatusIcon = android.R.drawable.ic_secure;
1186 mAuthStatusText = R.string.auth_secure_connection;
1187 break;
1188
1189 case OK_NO_SSL:
1190 case OK:
1191 if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1192 mAuthStatusText = R.string.auth_connection_established;
1193 mAuthStatusIcon = R.drawable.ic_ok;
1194 } else {
1195 mAuthStatusText = R.string.auth_nossl_plain_ok_title;
1196 mAuthStatusIcon = android.R.drawable.ic_partial_secure;
1197 }
1198 break;
1199
1200 case NO_NETWORK_CONNECTION:
1201 mAuthStatusIcon = R.drawable.no_network;
1202 mAuthStatusText = R.string.auth_no_net_conn_title;
1203 break;
1204
1205 case SSL_RECOVERABLE_PEER_UNVERIFIED:
1206 mAuthStatusText = R.string.auth_ssl_unverified_server_title;
1207 break;
1208 case BAD_OC_VERSION:
1209 mAuthStatusText = R.string.auth_bad_oc_version_title;
1210 break;
1211 case WRONG_CONNECTION:
1212 mAuthStatusText = R.string.auth_wrong_connection_title;
1213 break;
1214 case TIMEOUT:
1215 mAuthStatusText = R.string.auth_timeout_title;
1216 break;
1217 case INCORRECT_ADDRESS:
1218 mAuthStatusText = R.string.auth_incorrect_address_title;
1219 break;
1220 case SSL_ERROR:
1221 mAuthStatusText = R.string.auth_ssl_general_error_title;
1222 break;
1223 case UNAUTHORIZED:
1224 mAuthStatusText = R.string.auth_unauthorized;
1225 break;
1226 case HOST_NOT_AVAILABLE:
1227 mAuthStatusText = R.string.auth_unknown_host_title;
1228 break;
1229 case INSTANCE_NOT_CONFIGURED:
1230 mAuthStatusText = R.string.auth_not_configured_title;
1231 break;
1232 case FILE_NOT_FOUND:
1233 mAuthStatusText = R.string.auth_incorrect_path_title;
1234 break;
1235 case OAUTH2_ERROR:
1236 mAuthStatusText = R.string.auth_oauth_error;
1237 break;
1238 case OAUTH2_ERROR_ACCESS_DENIED:
1239 mAuthStatusText = R.string.auth_oauth_error_access_denied;
1240 break;
1241 case ACCOUNT_NOT_NEW:
1242 mAuthStatusText = R.string.auth_account_not_new;
1243 break;
1244 case ACCOUNT_NOT_THE_SAME:
1245 mAuthStatusText = R.string.auth_account_not_the_same;
1246 break;
1247 case UNHANDLED_HTTP_CODE:
1248 case UNKNOWN_ERROR:
1249 mAuthStatusText = R.string.auth_unknown_error_title;
1250 break;
1251 default:
1252 mAuthStatusText = 0;
1253 mAuthStatusIcon = 0;
1254 }
1255 }
1256
1257
1258 private void updateStatusIconFailUserName(){
1259 mAuthStatusIcon = R.drawable.common_error;
1260 mAuthStatusText = R.string.auth_fail_get_user_name;
1261 }
1262
1263 private void updateServerStatusIconNoRegularAuth(){
1264 mServerStatusIcon = R.drawable.common_error;
1265 mServerStatusText = R.string.auth_can_not_auth_against_server;
1266 }
1267
1268 /**
1269 * Processes the result of the request for and access token send
1270 * to an OAuth authorization server.
1271 *
1272 * @param result Result of the operation.
1273 */
1274 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result) {
1275 mOauth2GetAccessTokenOpId = -1;
1276 try {
1277 dismissDialog(DIALOG_OAUTH2_LOGIN_PROGRESS);
1278 } catch (IllegalArgumentException e) {
1279 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
1280 }
1281
1282 String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, mAuthTokenType);
1283 if (result.isSuccess() && webdav_path != null) {
1284 /// be gentle with the user
1285 showDialog(DIALOG_LOGIN_PROGRESS);
1286
1287 /// time to test the retrieved access token on the ownCloud server
1288 @SuppressWarnings("unchecked")
1289 Map<String, String> tokens = (Map<String, String>)(result.getData().get(0));
1290 mAuthToken = tokens.get(OAuth2Constants.KEY_ACCESS_TOKEN);
1291 //mAuthToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Constants.KEY_ACCESS_TOKEN);
1292 Log_OC.d(TAG, "Got ACCESS TOKEN: " + mAuthToken);
1293
1294 String remotePath ="";
1295 boolean successIfAbsent = false;
1296 boolean followRedirects = true;
1297 startExistenceCheckRemoteOperation(remotePath, this, successIfAbsent, webdav_path, "", "", followRedirects);
1298
1299 } else {
1300 updateAuthStatusIconAndText(result);
1301 showAuthStatus();
1302 Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
1303 }
1304 }
1305
1306
1307 /**
1308 * Processes the result of the access check performed to try the user credentials.
1309 *
1310 * Creates a new account through the AccountManager.
1311 *
1312 * @param operation Access check performed.
1313 * @param result Result of the operation.
1314 */
1315 private void onAuthorizationCheckFinish(RemoteOperationResult result) {
1316 mExistenceCheckOpId = -1;
1317 try {
1318 dismissDialog(DIALOG_LOGIN_PROGRESS);
1319 } catch (IllegalArgumentException e) {
1320 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
1321 }
1322
1323 if (result.isSuccess()) {
1324 Log_OC.d(TAG, "Successful access - time to save the account");
1325
1326 boolean success = false;
1327 if (mAction == ACTION_CREATE) {
1328 success = createAccount();
1329
1330 } else {
1331 updateToken();
1332 success = true;
1333 }
1334
1335 if (success) {
1336 finish();
1337 }
1338
1339 } else if (result.isServerFail() || result.isException()) {
1340 /// if server fail or exception in authorization, the UI is updated as when a server check failed
1341 mServerIsChecked = true;
1342 mServerIsValid = false;
1343 mIsSslConn = false;
1344 mServerInfoOperation = null;
1345 mDiscoveredVersion = null;
1346 mHostBaseUrl = normalizeUrl(mHostUrlInput.getText().toString());
1347
1348 // update status icon and text
1349 updateServerStatusIconAndText(result);
1350 showServerStatus();
1351 mAuthStatusIcon = 0;
1352 mAuthStatusText = 0;
1353 showAuthStatus();
1354
1355 // update input controls state
1356 showRefreshButton(true);
1357 mOkButton.setEnabled(false);
1358
1359 // very special case (TODO: move to a common place for all the remote operations) (dangerous here?)
1360 if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
1361 showUntrustedCertDialog(result);
1362 }
1363
1364 } else { // authorization fail due to client side - probably wrong credentials
1365 updateAuthStatusIconAndText(result);
1366 showAuthStatus();
1367 Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
1368 }
1369 }
1370
1371
1372
1373
1374 /**
1375 * Sets the proper response to get that the Account Authenticator that started this activity saves
1376 * a new authorization token for mAccount.
1377 */
1378 private void updateToken() {
1379 Bundle response = new Bundle();
1380 response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
1381 response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);
1382
1383 if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType)) {
1384 response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
1385 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1386 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
1387
1388 } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {
1389
1390 response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
1391 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1392 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
1393
1394 } else {
1395 response.putString(AccountManager.KEY_AUTHTOKEN, mPasswordInput.getText().toString());
1396 mAccountMgr.setPassword(mAccount, mPasswordInput.getText().toString());
1397 }
1398 setAccountAuthenticatorResult(response);
1399
1400 }
1401
1402
1403 /**
1404 * Creates a new account through the Account Authenticator that started this activity.
1405 *
1406 * This makes the account permanent.
1407 *
1408 * TODO Decide how to name the OAuth accounts
1409 */
1410 private boolean createAccount() {
1411 /// create and save new ownCloud account
1412 boolean isOAuth = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType);
1413 boolean isSaml = AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType);
1414
1415 Uri uri = Uri.parse(mHostBaseUrl);
1416 String username = mUsernameInput.getText().toString().trim();
1417 if (isOAuth) {
1418 username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();
1419 }
1420 String accountName = username + "@" + uri.getHost();
1421 if (uri.getPort() >= 0) {
1422 accountName += ":" + uri.getPort();
1423 }
1424 mAccount = new Account(accountName, MainApp.getAccountType());
1425 if (AccountUtils.exists(mAccount, getApplicationContext())) {
1426 // fail - not a new account, but an existing one; disallow
1427 RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW);
1428 updateAuthStatusIconAndText(result);
1429 showAuthStatus();
1430 Log_OC.d(TAG, result.getLogMessage());
1431 return false;
1432
1433 } else {
1434
1435 if (isOAuth || isSaml) {
1436 mAccountMgr.addAccountExplicitly(mAccount, "", null); // with external authorizations, the password is never input in the app
1437 } else {
1438 mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);
1439 }
1440
1441 /// add the new account as default in preferences, if there is none already
1442 Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
1443 if (defaultAccount == null) {
1444 SharedPreferences.Editor editor = PreferenceManager
1445 .getDefaultSharedPreferences(this).edit();
1446 editor.putString("select_oc_account", accountName);
1447 editor.commit();
1448 }
1449
1450 /// prepare result to return to the Authenticator
1451 // TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done
1452 final Intent intent = new Intent();
1453 intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, MainApp.getAccountType());
1454 intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
1455 /*if (!isOAuth)
1456 intent.putExtra(AccountManager.KEY_AUTHTOKEN, MainApp.getAccountType()); */
1457 intent.putExtra(AccountManager.KEY_USERDATA, username);
1458 if (isOAuth || isSaml) {
1459 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
1460 }
1461 /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
1462 mAccountMgr.setUserData(mAccount, Constants.KEY_OC_VERSION, mDiscoveredVersion.getVersion());
1463 mAccountMgr.setUserData(mAccount, Constants.KEY_OC_BASE_URL, mHostBaseUrl);
1464
1465 if (isSaml) {
1466 mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE");
1467 } else if (isOAuth) {
1468 mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_OAUTH2, "TRUE");
1469 }
1470
1471 setAccountAuthenticatorResult(intent.getExtras());
1472 setResult(RESULT_OK, intent);
1473
1474 return true;
1475 }
1476 }
1477
1478
1479 /**
1480 * {@inheritDoc}
1481 *
1482 * Necessary to update the contents of the SSL Dialog
1483 *
1484 * TODO move to some common place for all possible untrusted SSL failures
1485 */
1486 @Override
1487 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
1488 switch (id) {
1489 case DIALOG_LOGIN_PROGRESS:
1490 case DIALOG_CERT_NOT_SAVED:
1491 case DIALOG_OAUTH2_LOGIN_PROGRESS:
1492 break;
1493 default:
1494 Log_OC.e(TAG, "Incorrect dialog called with id = " + id);
1495 }
1496 }
1497
1498
1499 /**
1500 * {@inheritDoc}
1501 */
1502 @Override
1503 protected Dialog onCreateDialog(int id) {
1504 Dialog dialog = null;
1505 switch (id) {
1506 case DIALOG_LOGIN_PROGRESS: {
1507 /// simple progress dialog
1508 ProgressDialog working_dialog = new ProgressDialog(this);
1509 working_dialog.setMessage(getResources().getString(R.string.auth_trying_to_login));
1510 working_dialog.setIndeterminate(true);
1511 working_dialog.setCancelable(true);
1512 working_dialog
1513 .setOnCancelListener(new DialogInterface.OnCancelListener() {
1514 @Override
1515 public void onCancel(DialogInterface dialog) {
1516 /// TODO study if this is enough
1517 Log_OC.i(TAG, "Login canceled");
1518 if (mOperationThread != null) {
1519 mOperationThread.interrupt();
1520 finish();
1521 }
1522 }
1523 });
1524 dialog = working_dialog;
1525 break;
1526 }
1527 case DIALOG_OAUTH2_LOGIN_PROGRESS: {
1528 ProgressDialog working_dialog = new ProgressDialog(this);
1529 working_dialog.setMessage(String.format("Getting authorization"));
1530 working_dialog.setIndeterminate(true);
1531 working_dialog.setCancelable(true);
1532 working_dialog
1533 .setOnCancelListener(new DialogInterface.OnCancelListener() {
1534 @Override
1535 public void onCancel(DialogInterface dialog) {
1536 Log_OC.i(TAG, "Login canceled");
1537 finish();
1538 }
1539 });
1540 dialog = working_dialog;
1541 break;
1542 }
1543 case DIALOG_CERT_NOT_SAVED: {
1544 AlertDialog.Builder builder = new AlertDialog.Builder(this);
1545 builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
1546 builder.setCancelable(false);
1547 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
1548 @Override
1549 public void onClick(DialogInterface dialog, int which) {
1550 dialog.dismiss();
1551 };
1552 });
1553 dialog = builder.create();
1554 break;
1555 }
1556 default:
1557 Log_OC.e(TAG, "Incorrect dialog called with id = " + id);
1558 }
1559 return dialog;
1560 }
1561
1562
1563 /**
1564 * Starts and activity to open the 'new account' page in the ownCloud web site
1565 *
1566 * @param view 'Account register' button
1567 */
1568 public void onRegisterClick(View view) {
1569 Intent register = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.welcome_link_url)));
1570 setResult(RESULT_CANCELED);
1571 startActivity(register);
1572 }
1573
1574
1575 /**
1576 * Updates the content and visibility state of the icon and text associated
1577 * to the last check on the ownCloud server.
1578 */
1579 private void showServerStatus() {
1580 TextView tv = (TextView) findViewById(R.id.server_status_text);
1581
1582 if (mServerStatusIcon == 0 && mServerStatusText == 0) {
1583 tv.setVisibility(View.INVISIBLE);
1584
1585 } else {
1586 tv.setText(mServerStatusText);
1587 tv.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon, 0, 0, 0);
1588 tv.setVisibility(View.VISIBLE);
1589 }
1590
1591 }
1592
1593
1594 /**
1595 * Updates the content and visibility state of the icon and text associated
1596 * to the interactions with the OAuth authorization server.
1597 */
1598 private void showAuthStatus() {
1599 if (mAuthStatusIcon == 0 && mAuthStatusText == 0) {
1600 mAuthStatusLayout.setVisibility(View.INVISIBLE);
1601
1602 } else {
1603 mAuthStatusLayout.setText(mAuthStatusText);
1604 mAuthStatusLayout.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon, 0, 0, 0);
1605 mAuthStatusLayout.setVisibility(View.VISIBLE);
1606 }
1607 }
1608
1609
1610 private void showRefreshButton (boolean show) {
1611 if (show) {
1612 mRefreshButton.setVisibility(View.VISIBLE);
1613 } else {
1614 mRefreshButton.setVisibility(View.GONE);
1615 }
1616 }
1617
1618 /**
1619 * Called when the refresh button in the input field for ownCloud host is clicked.
1620 *
1621 * Performs a new check on the URL in the input field.
1622 *
1623 * @param view Refresh 'button'
1624 */
1625 public void onRefreshClick(View view) {
1626 checkOcServer();
1627 }
1628
1629
1630 /**
1631 * Called when the eye icon in the password field is clicked.
1632 *
1633 * Toggles the visibility of the password in the field.
1634 */
1635 public void onViewPasswordClick() {
1636 int selectionStart = mPasswordInput.getSelectionStart();
1637 int selectionEnd = mPasswordInput.getSelectionEnd();
1638 if (isPasswordVisible()) {
1639 hidePassword();
1640 } else {
1641 showPassword();
1642 }
1643 mPasswordInput.setSelection(selectionStart, selectionEnd);
1644 }
1645
1646
1647 /**
1648 * Called when the checkbox for OAuth authorization is clicked.
1649 *
1650 * Hides or shows the input fields for user & password.
1651 *
1652 * @param view 'View password' 'button'
1653 */
1654 public void onCheckClick(View view) {
1655 CheckBox oAuth2Check = (CheckBox)view;
1656 if (oAuth2Check.isChecked()) {
1657 mAuthTokenType = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType());
1658 } else {
1659 mAuthTokenType = AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());
1660 }
1661 adaptViewAccordingToAuthenticationMethod();
1662 }
1663
1664
1665 /**
1666 * Changes the visibility of input elements depending on
1667 * the current authorization method.
1668 */
1669 private void adaptViewAccordingToAuthenticationMethod () {
1670 if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType)) {
1671 // OAuth 2 authorization
1672 mOAuthAuthEndpointText.setVisibility(View.VISIBLE);
1673 mOAuthTokenEndpointText.setVisibility(View.VISIBLE);
1674 mUsernameInput.setVisibility(View.GONE);
1675 mPasswordInput.setVisibility(View.GONE);
1676
1677 } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {
1678 // SAML-based web Single Sign On
1679 mOAuthAuthEndpointText.setVisibility(View.GONE);
1680 mOAuthTokenEndpointText.setVisibility(View.GONE);
1681 mUsernameInput.setVisibility(View.GONE);
1682 mPasswordInput.setVisibility(View.GONE);
1683 } else {
1684 // basic HTTP authorization
1685 mOAuthAuthEndpointText.setVisibility(View.GONE);
1686 mOAuthTokenEndpointText.setVisibility(View.GONE);
1687 mUsernameInput.setVisibility(View.VISIBLE);
1688 mPasswordInput.setVisibility(View.VISIBLE);
1689 }
1690 }
1691
1692 /**
1693 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1694 *
1695 * Used to trigger the authentication check when the user presses 'enter' after writing the password,
1696 * or to throw the server test when the only field on screen is the URL input field.
1697 */
1698 @Override
1699 public boolean onEditorAction(TextView inputField, int actionId, KeyEvent event) {
1700 if (actionId == EditorInfo.IME_ACTION_DONE && inputField != null && inputField.equals(mPasswordInput)) {
1701 if (mOkButton.isEnabled()) {
1702 mOkButton.performClick();
1703 }
1704
1705 } else if (actionId == EditorInfo.IME_ACTION_NEXT && inputField != null && inputField.equals(mHostUrlInput)) {
1706 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {
1707 checkOcServer();
1708 }
1709 }
1710 return false; // always return false to grant that the software keyboard is hidden anyway
1711 }
1712
1713
1714 private abstract static class RightDrawableOnTouchListener implements OnTouchListener {
1715
1716 private int fuzz = 75;
1717
1718 /**
1719 * {@inheritDoc}
1720 */
1721 @Override
1722 public boolean onTouch(View view, MotionEvent event) {
1723 Drawable rightDrawable = null;
1724 if (view instanceof TextView) {
1725 Drawable[] drawables = ((TextView)view).getCompoundDrawables();
1726 if (drawables.length > 2) {
1727 rightDrawable = drawables[2];
1728 }
1729 }
1730 if (rightDrawable != null) {
1731 final int x = (int) event.getX();
1732 final int y = (int) event.getY();
1733 final Rect bounds = rightDrawable.getBounds();
1734 if (x >= (view.getRight() - bounds.width() - fuzz) && x <= (view.getRight() - view.getPaddingRight() + fuzz)
1735 && y >= (view.getPaddingTop() - fuzz) && y <= (view.getHeight() - view.getPaddingBottom()) + fuzz) {
1736
1737 return onDrawableTouch(event);
1738 }
1739 }
1740 return false;
1741 }
1742
1743 public abstract boolean onDrawableTouch(final MotionEvent event);
1744 }
1745
1746
1747 public void onSamlDialogSuccess(String sessionCookie) {
1748 mAuthToken = sessionCookie;
1749
1750 if (sessionCookie != null && sessionCookie.length() > 0) {
1751 mAuthToken = sessionCookie;
1752
1753 // GetRemoteUserNameOperation getUserOperation = new GetRemoteUserNameOperation();
1754 // OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(mHostBaseUrl), getApplicationContext(), true);
1755 // client.setSsoSessionCookie(mAuthToken);
1756 // getUserOperation.execute(client, this, mHandler);
1757 boolean followRedirects = true;
1758 getRemoteUserNameOperation(sessionCookie, followRedirects);
1759 }
1760 }
1761
1762 private void getRemoteUserNameOperation(String sessionCookie, boolean followRedirects) {
1763
1764 Intent getUserNameIntent = new Intent();
1765 getUserNameIntent.setAction(OperationsService.ACTION_GET_USER_NAME);
1766 getUserNameIntent.putExtra(OperationsService.EXTRA_SERVER_URL, mHostBaseUrl);
1767 getUserNameIntent.putExtra(OperationsService.EXTRA_COOKIE, sessionCookie);
1768 getUserNameIntent.putExtra(OperationsService.EXTRA_FOLLOW_REDIRECTS, followRedirects);
1769
1770 if (mOperationsServiceBinder != null) {
1771 Log_OC.wtf(TAG, "starting getRemoteUserNameOperation..." );
1772 mGetUserNameOpId = mOperationsServiceBinder.newOperation(getUserNameIntent);
1773 }
1774 }
1775
1776
1777 @Override
1778 public void onSsoFinished(String sessionCookies) {
1779 //Toast.makeText(this, "got cookies: " + sessionCookie, Toast.LENGTH_LONG).show();
1780
1781 if (sessionCookies != null && sessionCookies.length() > 0) {
1782 Log_OC.d(TAG, "Successful SSO - time to save the account");
1783 onSamlDialogSuccess(sessionCookies);
1784 Fragment fd = getSupportFragmentManager().findFragmentByTag(TAG_SAML_DIALOG);
1785 if (fd != null && fd instanceof SherlockDialogFragment) {
1786 Dialog d = ((SherlockDialogFragment)fd).getDialog();
1787 if (d != null && d.isShowing()) {
1788 d.dismiss();
1789 }
1790 }
1791
1792 } else {
1793 // TODO - show fail
1794 Log_OC.d(TAG, "SSO failed");
1795 }
1796
1797 }
1798
1799 /** Show auth_message
1800 *
1801 * @param message
1802 */
1803 private void showAuthMessage(String message) {
1804 mAuthMessage.setVisibility(View.VISIBLE);
1805 mAuthMessage.setText(message);
1806 }
1807
1808 private void hideAuthMessage() {
1809 mAuthMessage.setVisibility(View.GONE);
1810 }
1811
1812 @Override
1813 public boolean onTouchEvent(MotionEvent event) {
1814 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType) &&
1815 mHostUrlInput.hasFocus() && event.getAction() == MotionEvent.ACTION_DOWN) {
1816 checkOcServer();
1817 }
1818 return super.onTouchEvent(event);
1819 }
1820
1821
1822 /**
1823 * Show untrusted cert dialog
1824 */
1825 public void showUntrustedCertDialog(X509Certificate x509Certificate, SslError error, SslErrorHandler handler) {
1826 // Show a dialog with the certificate info
1827 SslUntrustedCertDialog dialog = null;
1828 if (x509Certificate == null) {
1829 dialog = SslUntrustedCertDialog.newInstanceForEmptySslError(error, handler);
1830 } else {
1831 dialog = SslUntrustedCertDialog.newInstanceForFullSslError(x509Certificate, error, handler);
1832 }
1833 FragmentManager fm = getSupportFragmentManager();
1834 FragmentTransaction ft = fm.beginTransaction();
1835 ft.addToBackStack(null);
1836 dialog.show(ft, DIALOG_UNTRUSTED_CERT);
1837 }
1838
1839 /**
1840 * Show untrusted cert dialog
1841 */
1842 public void showUntrustedCertDialog(RemoteOperationResult result) {
1843 // Show a dialog with the certificate info
1844 SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError((CertificateCombinedException)result.getException());
1845 FragmentManager fm = getSupportFragmentManager();
1846 FragmentTransaction ft = fm.beginTransaction();
1847 ft.addToBackStack(null);
1848 dialog.show(ft, DIALOG_UNTRUSTED_CERT);
1849
1850 }
1851
1852 /**
1853 * Dismiss untrusted cert dialog
1854 */
1855 public void dismissUntrustedCertDialog(){
1856 /*Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_UNTRUSTED_CERT);
1857 if (frag != null) {
1858 SslErrorViewAdapter dialog = (SslErrorViewAdapter) frag;
1859 dialog.dismiss();
1860 }
1861 */
1862 }
1863
1864 /**
1865 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1866 */
1867 public void onSavedCertificate() {
1868 Fragment fd = getSupportFragmentManager().findFragmentByTag(TAG_SAML_DIALOG);
1869 if (fd == null) {
1870 // if SAML dialog is not shown, the SslDialog was shown due to an SSL error in the server check
1871 checkOcServer();
1872 }
1873 }
1874
1875 /**
1876 * Called from SslValidatorDialog when a new server certificate could not be saved
1877 * when the user requested it.
1878 */
1879 @Override
1880 public void onFailedSavingCertificate() {
1881 showDialog(DIALOG_CERT_NOT_SAVED);
1882 cancelWebView();
1883 }
1884
1885 @Override
1886 public void onCancelCertificate() {
1887 cancelWebView();
1888 }
1889
1890
1891 public void cancelWebView() {
1892 Fragment fd = getSupportFragmentManager().findFragmentByTag(TAG_SAML_DIALOG);
1893 if (fd != null && fd instanceof SherlockDialogFragment) {
1894 Dialog d = ((SherlockDialogFragment)fd).getDialog();
1895 if (d != null && d.isShowing()) {
1896 d.dismiss();
1897 }
1898 }
1899
1900 }
1901
1902
1903 private void doOnResumeAndBound() {
1904 //Log.wtf(TAG, "registering to listen for operation callbacks" );
1905 mOperationsServiceBinder.addOperationListener(AuthenticatorActivity.this, mHandler);
1906
1907 if (mGetServerInfoOpId != -1) {
1908 RemoteOperationResult result =
1909 mOperationsServiceBinder.getOperationResultIfFinished(mGetServerInfoOpId);
1910 if (result != null) {
1911 //Log_OC.wtf(TAG, "found result of operation finished while rotating");
1912 onGetServerInfoFinish(result);
1913 }
1914
1915 } else if (mOauth2GetAccessTokenOpId != -1) {
1916 RemoteOperationResult result =
1917 mOperationsServiceBinder.getOperationResultIfFinished(
1918 mOauth2GetAccessTokenOpId);
1919 if (result != null) {
1920 //Log_OC.wtf(TAG, "found result of operation finished while rotating");
1921 onGetOAuthAccessTokenFinish(result);
1922 }
1923
1924 } else if (mExistenceCheckOpId != -1) {
1925 RemoteOperationResult result =
1926 mOperationsServiceBinder.getOperationResultIfFinished(mExistenceCheckOpId);
1927 if (result != null) {
1928 //Log_OC.wtf(TAG, "found result of operation finished while rotating");
1929 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(
1930 MainApp.getAccountType()).equals(mAuthTokenType)) {
1931 onSamlBasedFederatedSingleSignOnAuthorizationStart(result);
1932
1933 } else {
1934 onAuthorizationCheckFinish(result);
1935 }
1936 }
1937 }if (mGetUserNameOpId != -1) {
1938 RemoteOperationResult result =
1939 mOperationsServiceBinder.getOperationResultIfFinished(mGetUserNameOpId);
1940 if (result != null) {
1941 //Log_OC.wtf(TAG, "found result of operation finished while rotating");
1942 onGetUserNameFinish(result);
1943 }
1944
1945 }
1946
1947 }
1948
1949 /**
1950 * Implements callback methods for service binding.
1951 */
1952 private class OperationsServiceConnection implements ServiceConnection {
1953
1954 @Override
1955 public void onServiceConnected(ComponentName component, IBinder service) {
1956 if (component.equals(new ComponentName(AuthenticatorActivity.this, OperationsService.class))) {
1957 //Log_OC.wtf(TAG, "Operations service connected");
1958 mOperationsServiceBinder = (OperationsServiceBinder) service;
1959
1960 doOnResumeAndBound();
1961
1962 } else {
1963 return;
1964 }
1965
1966 }
1967
1968 @Override
1969 public void onServiceDisconnected(ComponentName component) {
1970 if (component.equals(new ComponentName(AuthenticatorActivity.this, OperationsService.class))) {
1971 Log_OC.e(TAG, "Operations service crashed");
1972 mOperationsServiceBinder = null;
1973 }
1974 }
1975
1976 }
1977
1978 }