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