37ff49123f9b51539419ebc279e0096e36082451
[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 ACCOUNT_NOT_THE_SAME:
1025 mAuthStatusText = R.string.auth_account_not_the_same;
1026 break;
1027 case UNHANDLED_HTTP_CODE:
1028 case UNKNOWN_ERROR:
1029 mAuthStatusText = R.string.auth_unknown_error_title;
1030 break;
1031 default:
1032 mAuthStatusText = 0;
1033 mAuthStatusIcon = 0;
1034 }
1035 }
1036
1037
1038 /**
1039 * Processes the result of the request for and access token send
1040 * to an OAuth authorization server.
1041 *
1042 * @param operation Operation performed requesting the access token.
1043 * @param result Result of the operation.
1044 */
1045 private void onGetOAuthAccessTokenFinish(OAuth2GetAccessToken operation, RemoteOperationResult result) {
1046 try {
1047 dismissDialog(DIALOG_OAUTH2_LOGIN_PROGRESS);
1048 } catch (IllegalArgumentException e) {
1049 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
1050 }
1051
1052 String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, mCurrentAuthTokenType);
1053 if (result.isSuccess() && webdav_path != null) {
1054 /// be gentle with the user
1055 showDialog(DIALOG_LOGIN_PROGRESS);
1056
1057 /// time to test the retrieved access token on the ownCloud server
1058 mAuthToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Constants.KEY_ACCESS_TOKEN);
1059 Log_OC.d(TAG, "Got ACCESS TOKEN: " + mAuthToken);
1060 mAuthCheckOperation = new ExistenceCheckOperation("", this, false);
1061 WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this, true);
1062 client.setBearerCredentials(mAuthToken);
1063 mAuthCheckOperation.execute(client, this, mHandler);
1064
1065 } else {
1066 updateAuthStatusIconAndText(result);
1067 showAuthStatus();
1068 Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
1069 }
1070 }
1071
1072
1073 /**
1074 * Processes the result of the access check performed to try the user credentials.
1075 *
1076 * Creates a new account through the AccountManager.
1077 *
1078 * @param operation Access check performed.
1079 * @param result Result of the operation.
1080 */
1081 private void onAuthorizationCheckFinish(ExistenceCheckOperation operation, RemoteOperationResult result) {
1082 try {
1083 dismissDialog(DIALOG_LOGIN_PROGRESS);
1084 } catch (IllegalArgumentException e) {
1085 // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens
1086 }
1087
1088 if (result.isSuccess()) {
1089 Log_OC.d(TAG, "Successful access - time to save the account");
1090
1091 boolean success = false;
1092 if (mAction == ACTION_CREATE) {
1093 success = createAccount();
1094
1095 } else {
1096 success = updateToken();
1097 }
1098
1099 if (success) {
1100 finish();
1101 }
1102
1103 } else if (result.isServerFail() || result.isException()) {
1104 /// if server fail or exception in authorization, the UI is updated as when a server check failed
1105 mServerIsChecked = true;
1106 mServerIsValid = false;
1107 mIsSslConn = false;
1108 mOcServerChkOperation = null;
1109 mDiscoveredVersion = null;
1110 mHostBaseUrl = normalizeUrl(mHostUrlInput.getText().toString());
1111
1112 // update status icon and text
1113 updateServerStatusIconAndText(result);
1114 showServerStatus();
1115 mAuthStatusIcon = 0;
1116 mAuthStatusText = 0;
1117 showAuthStatus();
1118
1119 // update input controls state
1120 showRefreshButton();
1121 mOkButton.setEnabled(false);
1122
1123 // very special case (TODO: move to a common place for all the remote operations) (dangerous here?)
1124 if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
1125 mLastSslUntrustedServerResult = result;
1126 showDialog(DIALOG_SSL_VALIDATOR);
1127 }
1128
1129 } else { // authorization fail due to client side - probably wrong credentials
1130 updateAuthStatusIconAndText(result);
1131 showAuthStatus();
1132 Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
1133 }
1134 }
1135
1136
1137 /**
1138 * Sets the proper response to get that the Account Authenticator that started this activity saves
1139 * a new authorization token for mAccount.
1140 */
1141 private boolean updateToken() {
1142 Bundle response = new Bundle();
1143 response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
1144 response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);
1145
1146 if (AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mCurrentAuthTokenType)) {
1147 response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
1148 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1149 mAccountMgr.setAuthToken(mAccount, mCurrentAuthTokenType, mAuthToken);
1150
1151 } else if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mCurrentAuthTokenType)) {
1152 String username = getUserNameForSamlSso();
1153 if (!mUsernameInput.getText().toString().equals(username)) {
1154 // fail - not a new account, but an existing one; disallow
1155 RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_THE_SAME);
1156 updateAuthStatusIconAndText(result);
1157 showAuthStatus();
1158 Log_OC.d(TAG, result.getLogMessage());
1159
1160 return false;
1161 }
1162
1163 response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
1164 // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
1165 mAccountMgr.setAuthToken(mAccount, mCurrentAuthTokenType, mAuthToken);
1166 Log_OC.e(TAG, "saving auth token: " + mAuthToken);
1167
1168 } else {
1169 response.putString(AccountManager.KEY_AUTHTOKEN, mPasswordInput.getText().toString());
1170 mAccountMgr.setPassword(mAccount, mPasswordInput.getText().toString());
1171 }
1172 setAccountAuthenticatorResult(response);
1173
1174 return true;
1175 }
1176
1177
1178 /**
1179 * Creates a new account through the Account Authenticator that started this activity.
1180 *
1181 * This makes the account permanent.
1182 *
1183 * TODO Decide how to name the OAuth accounts
1184 */
1185 private boolean createAccount() {
1186 /// create and save new ownCloud account
1187 boolean isOAuth = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mCurrentAuthTokenType);
1188 boolean isSaml = AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mCurrentAuthTokenType);
1189
1190 Uri uri = Uri.parse(mHostBaseUrl);
1191 String username = mUsernameInput.getText().toString().trim();
1192 if (isSaml) {
1193 username = getUserNameForSamlSso();
1194
1195 } else if (isOAuth) {
1196 username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();
1197 }
1198 String accountName = username + "@" + uri.getHost();
1199 if (uri.getPort() >= 0) {
1200 accountName += ":" + uri.getPort();
1201 }
1202 mAccount = new Account(accountName, AccountAuthenticator.ACCOUNT_TYPE);
1203 if (AccountUtils.exists(mAccount, getApplicationContext())) {
1204 // fail - not a new account, but an existing one; disallow
1205 RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW);
1206 updateAuthStatusIconAndText(result);
1207 showAuthStatus();
1208 Log_OC.d(TAG, result.getLogMessage());
1209 return false;
1210
1211 } else {
1212
1213 if (isOAuth || isSaml) {
1214 mAccountMgr.addAccountExplicitly(mAccount, "", null); // with external authorizations, the password is never input in the app
1215 } else {
1216 mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);
1217 }
1218
1219 /// add the new account as default in preferences, if there is none already
1220 Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
1221 if (defaultAccount == null) {
1222 SharedPreferences.Editor editor = PreferenceManager
1223 .getDefaultSharedPreferences(this).edit();
1224 editor.putString("select_oc_account", accountName);
1225 editor.commit();
1226 }
1227
1228 /// prepare result to return to the Authenticator
1229 // TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done
1230 final Intent intent = new Intent();
1231 intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, AccountAuthenticator.ACCOUNT_TYPE);
1232 intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
1233 /*if (!isOAuth)
1234 intent.putExtra(AccountManager.KEY_AUTHTOKEN, AccountAuthenticator.ACCOUNT_TYPE); */
1235 intent.putExtra(AccountManager.KEY_USERDATA, username);
1236 if (isOAuth || isSaml) {
1237 mAccountMgr.setAuthToken(mAccount, mCurrentAuthTokenType, mAuthToken);
1238 Log_OC.e(TAG, "saving auth token: " + mAuthToken);
1239 }
1240 /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
1241 mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION, mDiscoveredVersion.toString());
1242 mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL, mHostBaseUrl);
1243 if (isSaml) {
1244 mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE");
1245 } else if (isOAuth) {
1246 mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_OAUTH2, "TRUE");
1247 }
1248
1249 setAccountAuthenticatorResult(intent.getExtras());
1250 setResult(RESULT_OK, intent);
1251
1252 /// immediately request for the synchronization of the new account
1253 Bundle bundle = new Bundle();
1254 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
1255 ContentResolver.requestSync(mAccount, AccountAuthenticator.AUTHORITY, bundle);
1256 syncAccount();
1257 // Bundle bundle = new Bundle();
1258 // bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
1259 // ContentResolver.requestSync(mAccount, AccountAuthenticator.AUTHORITY, bundle);
1260 return true;
1261 }
1262 }
1263
1264
1265 private String getUserNameForSamlSso() {
1266 if (mAuthToken != null) {
1267 String [] cookies = mAuthToken.split(";");
1268 for (int i=0; i<cookies.length; i++) {
1269 if (cookies[i].startsWith(KEY_OC_USERNAME_EQUALS )) {
1270 String value = Uri.decode(cookies[i].substring(KEY_OC_USERNAME_EQUALS.length()));
1271 return value;
1272 }
1273 }
1274 }
1275 return "";
1276 }
1277
1278
1279 /**
1280 * {@inheritDoc}
1281 *
1282 * Necessary to update the contents of the SSL Dialog
1283 *
1284 * TODO move to some common place for all possible untrusted SSL failures
1285 */
1286 @Override
1287 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
1288 switch (id) {
1289 case DIALOG_LOGIN_PROGRESS:
1290 case DIALOG_CERT_NOT_SAVED:
1291 case DIALOG_OAUTH2_LOGIN_PROGRESS:
1292 break;
1293 case DIALOG_SSL_VALIDATOR: {
1294 ((SslValidatorDialog)dialog).updateResult(mLastSslUntrustedServerResult);
1295 break;
1296 }
1297 default:
1298 Log_OC.e(TAG, "Incorrect dialog called with id = " + id);
1299 }
1300 }
1301
1302
1303 /**
1304 * {@inheritDoc}
1305 */
1306 @Override
1307 protected Dialog onCreateDialog(int id) {
1308 Dialog dialog = null;
1309 switch (id) {
1310 case DIALOG_LOGIN_PROGRESS: {
1311 /// simple progress dialog
1312 ProgressDialog working_dialog = new ProgressDialog(this);
1313 working_dialog.setMessage(getResources().getString(R.string.auth_trying_to_login));
1314 working_dialog.setIndeterminate(true);
1315 working_dialog.setCancelable(true);
1316 working_dialog
1317 .setOnCancelListener(new DialogInterface.OnCancelListener() {
1318 @Override
1319 public void onCancel(DialogInterface dialog) {
1320 /// TODO study if this is enough
1321 Log_OC.i(TAG, "Login canceled");
1322 if (mOperationThread != null) {
1323 mOperationThread.interrupt();
1324 finish();
1325 }
1326 }
1327 });
1328 dialog = working_dialog;
1329 break;
1330 }
1331 case DIALOG_OAUTH2_LOGIN_PROGRESS: {
1332 ProgressDialog working_dialog = new ProgressDialog(this);
1333 working_dialog.setMessage(String.format("Getting authorization"));
1334 working_dialog.setIndeterminate(true);
1335 working_dialog.setCancelable(true);
1336 working_dialog
1337 .setOnCancelListener(new DialogInterface.OnCancelListener() {
1338 @Override
1339 public void onCancel(DialogInterface dialog) {
1340 Log_OC.i(TAG, "Login canceled");
1341 finish();
1342 }
1343 });
1344 dialog = working_dialog;
1345 break;
1346 }
1347 case DIALOG_SSL_VALIDATOR: {
1348 /// TODO start to use new dialog interface, at least for this (it is a FragmentDialog already)
1349 dialog = SslValidatorDialog.newInstance(this, mLastSslUntrustedServerResult, this);
1350 break;
1351 }
1352 case DIALOG_CERT_NOT_SAVED: {
1353 AlertDialog.Builder builder = new AlertDialog.Builder(this);
1354 builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
1355 builder.setCancelable(false);
1356 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
1357 @Override
1358 public void onClick(DialogInterface dialog, int which) {
1359 dialog.dismiss();
1360 };
1361 });
1362 dialog = builder.create();
1363 break;
1364 }
1365 default:
1366 Log_OC.e(TAG, "Incorrect dialog called with id = " + id);
1367 }
1368 return dialog;
1369 }
1370
1371
1372 /**
1373 * Starts and activity to open the 'new account' page in the ownCloud web site
1374 *
1375 * @param view 'Account register' button
1376 */
1377 public void onRegisterClick(View view) {
1378 Intent register = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.url_account_register)));
1379 setResult(RESULT_CANCELED);
1380 startActivity(register);
1381 }
1382
1383
1384 /**
1385 * Updates the content and visibility state of the icon and text associated
1386 * to the last check on the ownCloud server.
1387 */
1388 private void showServerStatus() {
1389 TextView tv = (TextView) findViewById(R.id.server_status_text);
1390
1391 if (mServerStatusIcon == 0 && mServerStatusText == 0) {
1392 tv.setVisibility(View.INVISIBLE);
1393
1394 } else {
1395 tv.setText(mServerStatusText);
1396 tv.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon, 0, 0, 0);
1397 tv.setVisibility(View.VISIBLE);
1398 }
1399
1400 }
1401
1402
1403 /**
1404 * Updates the content and visibility state of the icon and text associated
1405 * to the interactions with the OAuth authorization server.
1406 */
1407 private void showAuthStatus() {
1408 if (mAuthStatusIcon == 0 && mAuthStatusText == 0) {
1409 mAuthStatusLayout.setVisibility(View.INVISIBLE);
1410
1411 } else {
1412 mAuthStatusLayout.setText(mAuthStatusText);
1413 mAuthStatusLayout.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon, 0, 0, 0);
1414 mAuthStatusLayout.setVisibility(View.VISIBLE);
1415 }
1416 }
1417
1418
1419 private void showRefreshButton() {
1420 mRefreshButton.setVisibility(View.VISIBLE);
1421 }
1422
1423 private void hideRefreshButton() {
1424 mRefreshButton.setVisibility(View.GONE);
1425 }
1426
1427 /**
1428 * Called when the refresh button in the input field for ownCloud host is clicked.
1429 *
1430 * Performs a new check on the URL in the input field.
1431 *
1432 * @param view Refresh 'button'
1433 */
1434 public void onRefreshClick(View view) {
1435 checkOcServer();
1436 }
1437
1438
1439 /**
1440 * Called when the eye icon in the password field is clicked.
1441 *
1442 * Toggles the visibility of the password in the field.
1443 */
1444 public void onViewPasswordClick() {
1445 int selectionStart = mPasswordInput.getSelectionStart();
1446 int selectionEnd = mPasswordInput.getSelectionEnd();
1447 if (isPasswordVisible()) {
1448 hidePassword();
1449 } else {
1450 showPassword();
1451 }
1452 mPasswordInput.setSelection(selectionStart, selectionEnd);
1453 }
1454
1455
1456 /**
1457 * Called when the checkbox for OAuth authorization is clicked.
1458 *
1459 * Hides or shows the input fields for user & password.
1460 *
1461 * @param view 'View password' 'button'
1462 */
1463 public void onCheckClick(View view) {
1464 CheckBox oAuth2Check = (CheckBox)view;
1465 if (oAuth2Check.isChecked()) {
1466 mCurrentAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN;
1467 } else {
1468 mCurrentAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD;
1469 }
1470 adaptViewAccordingToAuthenticationMethod();
1471 }
1472
1473
1474 /**
1475 * Changes the visibility of input elements depending on
1476 * the current authorization method.
1477 */
1478 private void adaptViewAccordingToAuthenticationMethod () {
1479 if (AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mCurrentAuthTokenType)) {
1480 // OAuth 2 authorization
1481 mOAuthAuthEndpointText.setVisibility(View.VISIBLE);
1482 mOAuthTokenEndpointText.setVisibility(View.VISIBLE);
1483 mUsernameInput.setVisibility(View.GONE);
1484 mPasswordInput.setVisibility(View.GONE);
1485
1486 } else if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mCurrentAuthTokenType)) {
1487 // SAML-based web Single Sign On
1488 mOAuthAuthEndpointText.setVisibility(View.GONE);
1489 mOAuthTokenEndpointText.setVisibility(View.GONE);
1490 mUsernameInput.setVisibility(View.GONE);
1491 mPasswordInput.setVisibility(View.GONE);
1492 } else {
1493 // basic HTTP authorization
1494 mOAuthAuthEndpointText.setVisibility(View.GONE);
1495 mOAuthTokenEndpointText.setVisibility(View.GONE);
1496 mUsernameInput.setVisibility(View.VISIBLE);
1497 mPasswordInput.setVisibility(View.VISIBLE);
1498 }
1499 }
1500
1501 /**
1502 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1503 */
1504 public void onSavedCertificate() {
1505 checkOcServer();
1506 }
1507
1508 /**
1509 * Called from SslValidatorDialog when a new server certificate could not be saved
1510 * when the user requested it.
1511 */
1512 @Override
1513 public void onFailedSavingCertificate() {
1514 showDialog(DIALOG_CERT_NOT_SAVED);
1515 }
1516
1517
1518 /**
1519 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1520 *
1521 * Used to trigger the authentication check when the user presses 'enter' after writing the password,
1522 * or to throw the server test when the only field on screen is the URL input field.
1523 */
1524 @Override
1525 public boolean onEditorAction(TextView inputField, int actionId, KeyEvent event) {
1526 if (actionId == EditorInfo.IME_ACTION_DONE && inputField != null && inputField.equals(mPasswordInput)) {
1527 if (mOkButton.isEnabled()) {
1528 mOkButton.performClick();
1529 }
1530
1531 } else if (actionId == EditorInfo.IME_ACTION_NEXT && inputField != null && inputField.equals(mHostUrlInput)) {
1532 if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mCurrentAuthTokenType)) {
1533 checkOcServer();
1534 }
1535 }
1536 return false; // always return false to grant that the software keyboard is hidden anyway
1537 }
1538
1539
1540 private abstract static class RightDrawableOnTouchListener implements OnTouchListener {
1541
1542 private int fuzz = 75;
1543
1544 /**
1545 * {@inheritDoc}
1546 */
1547 @Override
1548 public boolean onTouch(View view, MotionEvent event) {
1549 Drawable rightDrawable = null;
1550 if (view instanceof TextView) {
1551 Drawable[] drawables = ((TextView)view).getCompoundDrawables();
1552 if (drawables.length > 2) {
1553 rightDrawable = drawables[2];
1554 }
1555 }
1556 if (rightDrawable != null) {
1557 final int x = (int) event.getX();
1558 final int y = (int) event.getY();
1559 final Rect bounds = rightDrawable.getBounds();
1560 if (x >= (view.getRight() - bounds.width() - fuzz) && x <= (view.getRight() - view.getPaddingRight() + fuzz)
1561 && y >= (view.getPaddingTop() - fuzz) && y <= (view.getHeight() - view.getPaddingBottom()) + fuzz) {
1562
1563 return onDrawableTouch(event);
1564 }
1565 }
1566 return false;
1567 }
1568
1569 public abstract boolean onDrawableTouch(final MotionEvent event);
1570 }
1571
1572
1573 public void onSamlDialogSuccess(String sessionCookie){
1574 mAuthToken = sessionCookie;
1575
1576 if (sessionCookie != null && sessionCookie.length() > 0) {
1577 Log_OC.d(TAG, "Successful SSO - time to save the account");
1578 mAuthToken = sessionCookie;
1579 boolean success = false;
1580 if (mAction == ACTION_CREATE) {
1581 success = createAccount();
1582
1583 } else {
1584 success = updateToken();
1585 }
1586 if (success) {
1587 finish();
1588 }
1589 }
1590
1591 }
1592
1593
1594 @Override
1595 public void onSsoFinished(String sessionCookies) {
1596 //Toast.makeText(this, "got cookies: " + sessionCookie, Toast.LENGTH_LONG).show();
1597
1598 if (sessionCookies != null && sessionCookies.length() > 0) {
1599 Log_OC.d(TAG, "Successful SSO - time to save the account");
1600 onSamlDialogSuccess(sessionCookies);
1601 Fragment fd = getSupportFragmentManager().findFragmentByTag(TAG_SAML_DIALOG);
1602 if (fd != null && fd instanceof SherlockDialogFragment) {
1603 Dialog d = ((SherlockDialogFragment)fd).getDialog();
1604 if (d != null && d.isShowing()) {
1605 d.dismiss();
1606 }
1607 }
1608
1609 } else {
1610 // TODO - show fail
1611 Log_OC.d(TAG, "SSO failed");
1612 }
1613 }
1614
1615
1616 /** Show auth_message
1617 *
1618 * @param message
1619 */
1620 private void showAuthMessage(String message) {
1621 mAuthMessage.setVisibility(View.VISIBLE);
1622 mAuthMessage.setText(message);
1623 }
1624
1625 private void hideAuthMessage() {
1626 mAuthMessage.setVisibility(View.GONE);
1627 }
1628
1629
1630 private void syncAccount(){
1631 /// immediately request for the synchronization of the new account
1632 Bundle bundle = new Bundle();
1633 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
1634 ContentResolver.requestSync(mAccount, AccountAuthenticator.AUTHORITY, bundle);
1635 }
1636 }