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