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