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