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