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