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