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