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