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