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