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