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