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