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