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