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