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