Strip away index.php/apps/files to allow copy pasting from the server
[pub/Android/ownCloud.git] / src / com / owncloud / android / authentication / AuthenticatorActivity.java
1 /**
2 * ownCloud Android client application
3 *
4 * @author Bartek Przybylski
5 * @author David A. Velasco
6 * @author masensio
7 * Copyright (C) 2012 Bartek Przybylski
8 * Copyright (C) 2015 ownCloud Inc.
9 *
10 * This program is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2,
12 * as published by the Free Software Foundation.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 *
22 */
23
24 package com.owncloud.android.authentication;
25
26 import android.accounts.Account;
27 import android.accounts.AccountManager;
28 import android.app.Dialog;
29 import android.content.ComponentName;
30 import android.content.Context;
31 import android.content.Intent;
32 import android.content.ServiceConnection;
33 import android.content.SharedPreferences;
34 import android.graphics.Rect;
35 import android.graphics.drawable.Drawable;
36 import android.net.Uri;
37 import android.net.http.SslError;
38 import android.os.Bundle;
39 import android.os.Handler;
40 import android.os.IBinder;
41 import android.preference.PreferenceManager;
42 import android.support.v4.app.DialogFragment;
43 import android.support.v4.app.Fragment;
44 import android.support.v4.app.FragmentManager;
45 import android.support.v4.app.FragmentTransaction;
46 import android.text.Editable;
47 import android.text.InputType;
48 import android.text.TextWatcher;
49 import android.view.KeyEvent;
50 import android.view.MotionEvent;
51 import android.view.View;
52 import android.view.View.OnFocusChangeListener;
53 import android.view.View.OnTouchListener;
54 import android.view.inputmethod.EditorInfo;
55 import android.webkit.HttpAuthHandler;
56 import android.webkit.SslErrorHandler;
57 import android.webkit.WebView;
58 import android.widget.Button;
59 import android.widget.CheckBox;
60 import android.widget.EditText;
61 import android.widget.TextView;
62 import android.widget.TextView.OnEditorActionListener;
63 import android.widget.Toast;
64
65 import com.owncloud.android.MainApp;
66 import com.owncloud.android.R;
67 import com.owncloud.android.authentication.SsoWebViewClient.SsoWebViewClientListener;
68 import com.owncloud.android.lib.common.OwnCloudCredentials;
69 import com.owncloud.android.lib.common.OwnCloudCredentialsFactory;
70 import com.owncloud.android.lib.common.accounts.AccountTypeUtils;
71 import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;
72 import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;
73 import com.owncloud.android.lib.common.network.CertificateCombinedException;
74 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
75 import com.owncloud.android.lib.common.operations.RemoteOperation;
76 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
77 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
78 import com.owncloud.android.lib.common.utils.Log_OC;
79 import com.owncloud.android.lib.resources.status.OwnCloudVersion;
80 import com.owncloud.android.lib.resources.users.GetRemoteUserNameOperation;
81 import com.owncloud.android.operations.DetectAuthenticationMethodOperation.AuthenticationMethod;
82 import com.owncloud.android.operations.GetServerInfoOperation;
83 import com.owncloud.android.operations.OAuth2GetAccessToken;
84 import com.owncloud.android.services.OperationsService;
85 import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
86 import com.owncloud.android.ui.dialog.CredentialsDialogFragment;
87 import com.owncloud.android.ui.dialog.IndeterminateProgressDialog;
88 import com.owncloud.android.ui.dialog.SamlWebViewDialog;
89 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
90 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;
91 import com.owncloud.android.utils.DisplayUtils;
92
93 import java.security.cert.X509Certificate;
94 import java.util.Map;
95
96 /**
97 * This Activity is used to add an ownCloud account to the App
98 */
99 public class AuthenticatorActivity extends AccountAuthenticatorActivity
100 implements OnRemoteOperationListener, OnFocusChangeListener, OnEditorActionListener,
101 SsoWebViewClientListener, OnSslUntrustedCertListener,
102 AuthenticatorAsyncTask.OnAuthenticatorTaskListener {
103
104 private static final String TAG = AuthenticatorActivity.class.getSimpleName();
105
106 public static final String EXTRA_ACTION = "ACTION";
107 public static final String EXTRA_ACCOUNT = "ACCOUNT";
108
109 private static final String KEY_AUTH_TOKEN_TYPE = "AUTH_TOKEN_TYPE";
110
111 private static final String KEY_HOST_URL_TEXT = "HOST_URL_TEXT";
112 private static final String KEY_OC_VERSION = "OC_VERSION";
113 private static final String KEY_SERVER_VALID = "SERVER_VALID";
114 private static final String KEY_SERVER_CHECKED = "SERVER_CHECKED";
115 private static final String KEY_SERVER_STATUS_TEXT = "SERVER_STATUS_TEXT";
116 private static final String KEY_SERVER_STATUS_ICON = "SERVER_STATUS_ICON";
117 private static final String KEY_IS_SSL_CONN = "IS_SSL_CONN";
118 private static final String KEY_PASSWORD_EXPOSED = "PASSWORD_VISIBLE";
119 private static final String KEY_AUTH_STATUS_TEXT = "AUTH_STATUS_TEXT";
120 private static final String KEY_AUTH_STATUS_ICON = "AUTH_STATUS_ICON";
121 private static final String KEY_SERVER_AUTH_METHOD = "SERVER_AUTH_METHOD";
122 private static final String KEY_WAITING_FOR_OP_ID = "WAITING_FOR_OP_ID";
123 private static final String KEY_AUTH_TOKEN = "AUTH_TOKEN";
124
125 private static final String AUTH_ON = "on";
126 private static final String AUTH_OPTIONAL = "optional";
127
128 public static final byte ACTION_CREATE = 0;
129 public static final byte ACTION_UPDATE_TOKEN = 1; // requested by the user
130 public static final byte ACTION_UPDATE_EXPIRED_TOKEN = 2; // detected by the app
131
132 private static final String UNTRUSTED_CERT_DIALOG_TAG = "UNTRUSTED_CERT_DIALOG";
133 private static final String SAML_DIALOG_TAG = "SAML_DIALOG";
134 private static final String WAIT_DIALOG_TAG = "WAIT_DIALOG";
135 private static final String CREDENTIALS_DIALOG_TAG = "CREDENTIALS_DIALOG";
136 private static final String KEY_AUTH_IS_FIRST_ATTEMPT_TAG = "KEY_AUTH_IS_FIRST_ATTEMPT";
137
138 private static final String KEY_USERNAME = "USERNAME";
139 private static final String KEY_PASSWORD = "PASSWORD";
140 private static final String KEY_ASYNC_TASK_IN_PROGRESS = "AUTH_IN_PROGRESS";
141
142 /// parameters from EXTRAs in starter Intent
143 private byte mAction;
144 private Account mAccount;
145 private String mAuthTokenType;
146
147
148 /// activity-level references / state
149 private final Handler mHandler = new Handler();
150 private ServiceConnection mOperationsServiceConnection = null;
151 private OperationsServiceBinder mOperationsServiceBinder = null;
152 private AccountManager mAccountMgr;
153 private Uri mNewCapturedUriFromOAuth2Redirection;
154
155
156 /// Server PRE-Fragment elements
157 private EditText mHostUrlInput;
158 private View mRefreshButton;
159 private TextView mServerStatusView;
160
161 private TextWatcher mHostUrlInputWatcher;
162 private int mServerStatusText = 0, mServerStatusIcon = 0;
163
164 private boolean mServerIsChecked = false;
165 private boolean mServerIsValid = false;
166 private boolean mPendingAutoCheck = false;
167
168 private GetServerInfoOperation.ServerInfo mServerInfo =
169 new GetServerInfoOperation.ServerInfo();
170
171
172 /// Authentication PRE-Fragment elements
173 private CheckBox mOAuth2Check;
174 private TextView mOAuthAuthEndpointText;
175 private TextView mOAuthTokenEndpointText;
176 private EditText mUsernameInput;
177 private EditText mPasswordInput;
178 private View mOkButton;
179 private View mCenteredRefreshButton;
180 private TextView mAuthStatusView;
181
182 private int mAuthStatusText = 0, mAuthStatusIcon = 0;
183
184 private String mAuthToken = "";
185 private AuthenticatorAsyncTask mAsyncTask;
186
187 private boolean mIsFirstAuthAttempt;
188
189 /// Identifier of operation in progress which result shouldn't be lost
190 private long mWaitingForOpId = Long.MAX_VALUE;
191
192 private final String BASIC_TOKEN_TYPE = AccountTypeUtils.getAuthTokenTypePass(
193 MainApp.getAccountType());
194 private final String OAUTH_TOKEN_TYPE = AccountTypeUtils.getAuthTokenTypeAccessToken(
195 MainApp.getAccountType());
196 private final String SAML_TOKEN_TYPE =
197 AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType());
198
199
200 /**
201 * {@inheritDoc}
202 *
203 * IMPORTANT ENTRY POINT 1: activity is shown to the user
204 */
205 @Override
206 protected void onCreate(Bundle savedInstanceState) {
207 //Log_OC.wtf(TAG, "onCreate init");
208 super.onCreate(savedInstanceState);
209
210 // Workaround, for fixing a problem with Android Library Suppor v7 19
211 //getWindow().requestFeature(Window.FEATURE_NO_TITLE);
212 if (getSupportActionBar() != null) {
213 getSupportActionBar().hide();
214
215 getSupportActionBar().setDisplayHomeAsUpEnabled(false);
216 getSupportActionBar().setDisplayShowHomeEnabled(false);
217 getSupportActionBar().setDisplayShowTitleEnabled(false);
218 }
219
220 mIsFirstAuthAttempt = true;
221
222 // bind to Operations Service
223 mOperationsServiceConnection = new OperationsServiceConnection();
224 if (!bindService(new Intent(this, OperationsService.class),
225 mOperationsServiceConnection,
226 Context.BIND_AUTO_CREATE)) {
227 Toast.makeText(this,
228 R.string.error_cant_bind_to_operations_service,
229 Toast.LENGTH_LONG)
230 .show();
231 finish();
232 }
233
234 /// init activity state
235 mAccountMgr = AccountManager.get(this);
236 mNewCapturedUriFromOAuth2Redirection = null;
237
238 /// get input values
239 mAction = getIntent().getByteExtra(EXTRA_ACTION, ACTION_CREATE);
240 mAccount = getIntent().getExtras().getParcelable(EXTRA_ACCOUNT);
241 if (savedInstanceState == null) {
242 initAuthTokenType();
243 } else {
244 mAuthTokenType = savedInstanceState.getString(KEY_AUTH_TOKEN_TYPE);
245 mWaitingForOpId = savedInstanceState.getLong(KEY_WAITING_FOR_OP_ID);
246 mIsFirstAuthAttempt = savedInstanceState.getBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG);
247 }
248
249 /// load user interface
250 setContentView(R.layout.account_setup);
251
252 /// initialize general UI elements
253 initOverallUi();
254
255 mOkButton = findViewById(R.id.buttonOK);
256 mOkButton.setOnClickListener(new View.OnClickListener() {
257
258 @Override
259 public void onClick(View v) {
260 onOkClick();
261 }
262 });
263
264 mCenteredRefreshButton = findViewById(R.id.centeredRefreshButton);
265 mCenteredRefreshButton.setOnClickListener(new View.OnClickListener() {
266
267 @Override
268 public void onClick(View v) {
269 checkOcServer();
270 }
271 });
272
273 mOkButton = findViewById(R.id.buttonOK);
274
275 /// initialize block to be moved to single Fragment to check server and get info about it
276 initServerPreFragment(savedInstanceState);
277
278 /// initialize block to be moved to single Fragment to retrieve and validate credentials
279 initAuthorizationPreFragment(savedInstanceState);
280
281 //Log_OC.wtf(TAG, "onCreate end");
282 }
283
284 private void initAuthTokenType() {
285 mAuthTokenType =
286 getIntent().getExtras().getString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE);
287 if (mAuthTokenType == null) {
288 if (mAccount != null) {
289 boolean oAuthRequired =
290 (mAccountMgr.getUserData(mAccount, Constants.KEY_SUPPORTS_OAUTH2) != null);
291 boolean samlWebSsoRequired = (
292 mAccountMgr.getUserData(
293 mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO
294 ) != null
295 );
296 mAuthTokenType = chooseAuthTokenType(oAuthRequired, samlWebSsoRequired);
297
298 } else {
299 boolean oAuthSupported = AUTH_ON.equals(getString(R.string.auth_method_oauth2));
300 boolean samlWebSsoSupported =
301 AUTH_ON.equals(getString(R.string.auth_method_saml_web_sso));
302 mAuthTokenType = chooseAuthTokenType(oAuthSupported, samlWebSsoSupported);
303 }
304 }
305 }
306
307 private String chooseAuthTokenType(boolean oauth, boolean saml) {
308 if (saml) {
309 return SAML_TOKEN_TYPE;
310 } else if (oauth) {
311 return OAUTH_TOKEN_TYPE;
312 } else {
313 return BASIC_TOKEN_TYPE;
314 }
315 }
316
317
318 /**
319 * Configures elements in the user interface under direct control of the Activity.
320 */
321 private void initOverallUi() {
322
323 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
324 boolean isWelcomeLinkVisible = getResources().getBoolean(R.bool.show_welcome_link);
325
326 String instructionsMessageText = null;
327 if (mAction == ACTION_UPDATE_EXPIRED_TOKEN) {
328 if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType())
329 .equals(mAuthTokenType)) {
330 instructionsMessageText = getString(R.string.auth_expired_oauth_token_toast);
331
332 } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType())
333 .equals(mAuthTokenType)) {
334 instructionsMessageText = getString(R.string.auth_expired_saml_sso_token_toast);
335
336 } else {
337 instructionsMessageText = getString(R.string.auth_expired_basic_auth_toast);
338 }
339 }
340
341 /// step 2 - set properties of UI elements (text, visibility, enabled...)
342 Button welcomeLink = (Button) findViewById(R.id.welcome_link);
343 welcomeLink.setVisibility(isWelcomeLinkVisible ? View.VISIBLE : View.GONE);
344 welcomeLink.setText(
345 String.format(getString(R.string.auth_register), getString(R.string.app_name)));
346
347 TextView instructionsView = (TextView) findViewById(R.id.instructions_message);
348 if (instructionsMessageText != null) {
349 instructionsView.setVisibility(View.VISIBLE);
350 instructionsView.setText(instructionsMessageText);
351 } else {
352 instructionsView.setVisibility(View.GONE);
353 }
354 }
355
356
357 /**
358 *
359 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
360 */
361 private void initServerPreFragment(Bundle savedInstanceState) {
362
363 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
364 boolean isUrlInputAllowed = getResources().getBoolean(R.bool.show_server_url_input);
365 if (savedInstanceState == null) {
366 if (mAccount != null) {
367 mServerInfo.mBaseUrl = mAccountMgr.getUserData(mAccount, Constants.KEY_OC_BASE_URL);
368 // TODO do next in a setter for mBaseUrl
369 mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith("https://");
370 mServerInfo.mVersion = AccountUtils.getServerVersion(mAccount);
371 } else {
372 mServerInfo.mBaseUrl = getString(R.string.server_url).trim();
373 mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith("https://");
374 }
375 } else {
376 mServerStatusText = savedInstanceState.getInt(KEY_SERVER_STATUS_TEXT);
377 mServerStatusIcon = savedInstanceState.getInt(KEY_SERVER_STATUS_ICON);
378
379 mServerIsValid = savedInstanceState.getBoolean(KEY_SERVER_VALID);
380 mServerIsChecked = savedInstanceState.getBoolean(KEY_SERVER_CHECKED);
381
382 // TODO parcelable
383 mServerInfo.mIsSslConn = savedInstanceState.getBoolean(KEY_IS_SSL_CONN);
384 mServerInfo.mBaseUrl = savedInstanceState.getString(KEY_HOST_URL_TEXT);
385 String ocVersion = savedInstanceState.getString(KEY_OC_VERSION);
386 if (ocVersion != null) {
387 mServerInfo.mVersion = new OwnCloudVersion(ocVersion);
388 }
389 mServerInfo.mAuthMethod = AuthenticationMethod.valueOf(
390 savedInstanceState.getString(KEY_SERVER_AUTH_METHOD));
391
392 }
393
394 /// step 2 - set properties of UI elements (text, visibility, enabled...)
395 mHostUrlInput = (EditText) findViewById(R.id.hostUrlInput);
396 // Convert IDN to Unicode
397 mHostUrlInput.setText(DisplayUtils.convertIdn(mServerInfo.mBaseUrl, false));
398 if (mAction != ACTION_CREATE) {
399 /// lock things that should not change
400 mHostUrlInput.setEnabled(false);
401 mHostUrlInput.setFocusable(false);
402 }
403 if (isUrlInputAllowed) {
404 mRefreshButton = findViewById(R.id.embeddedRefreshButton);
405 } else {
406 findViewById(R.id.hostUrlFrame).setVisibility(View.GONE);
407 mRefreshButton = findViewById(R.id.centeredRefreshButton);
408 }
409 showRefreshButton(mServerIsChecked && !mServerIsValid &&
410 mWaitingForOpId > Integer.MAX_VALUE);
411 mServerStatusView = (TextView) findViewById(R.id.server_status_text);
412 showServerStatus();
413
414 /// step 3 - bind some listeners and options
415 mHostUrlInput.setImeOptions(EditorInfo.IME_ACTION_NEXT);
416 mHostUrlInput.setOnEditorActionListener(this);
417
418 /// step 4 - create listeners that will be bound at onResume
419 mHostUrlInputWatcher = new TextWatcher() {
420
421 @Override
422 public void afterTextChanged(Editable s) {
423 if (mOkButton.isEnabled() &&
424 !mServerInfo.mBaseUrl.equals(
425 normalizeUrl(s.toString(), mServerInfo.mIsSslConn))) {
426 mOkButton.setEnabled(false);
427 }
428 }
429
430 @Override
431 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
432 }
433
434 @Override
435 public void onTextChanged(CharSequence s, int start, int before, int count) {
436 if (mAuthStatusIcon != 0) {
437 Log_OC.d(TAG, "onTextChanged: hiding authentication status");
438 mAuthStatusIcon = 0;
439 mAuthStatusText = 0;
440 showAuthStatus();
441 }
442 }
443 };
444
445
446 // TODO find out if this is really necessary, or if it can done in a different way
447 findViewById(R.id.scroll).setOnTouchListener(new OnTouchListener() {
448 @Override
449 public boolean onTouch(View view, MotionEvent event) {
450 if (event.getAction() == MotionEvent.ACTION_DOWN) {
451 if (
452 AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(
453 MainApp.getAccountType()
454 ).equals(mAuthTokenType) &&
455 mHostUrlInput.hasFocus()
456 ) {
457 checkOcServer();
458 }
459 }
460 return false;
461 }
462 });
463
464
465 /// step 4 - mark automatic check to be started when OperationsService is ready
466 mPendingAutoCheck = (savedInstanceState == null &&
467 (mAction != ACTION_CREATE || !isUrlInputAllowed));
468 }
469
470
471 /**
472 *
473 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
474 */
475 private void initAuthorizationPreFragment(Bundle savedInstanceState) {
476
477 /// step 0 - get UI elements in layout
478 mOAuth2Check = (CheckBox) findViewById(R.id.oauth_onOff_check);
479 mOAuthAuthEndpointText = (TextView)findViewById(R.id.oAuthEntryPoint_1);
480 mOAuthTokenEndpointText = (TextView)findViewById(R.id.oAuthEntryPoint_2);
481 mUsernameInput = (EditText) findViewById(R.id.account_username);
482 mPasswordInput = (EditText) findViewById(R.id.account_password);
483 mAuthStatusView = (TextView) findViewById(R.id.auth_status_text);
484
485 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
486 String presetUserName = null;
487 boolean isPasswordExposed = false;
488 if (savedInstanceState == null) {
489 if (mAccount != null) {
490 presetUserName = mAccount.name.substring(0, mAccount.name.lastIndexOf('@'));
491 }
492
493 } else {
494 isPasswordExposed = savedInstanceState.getBoolean(KEY_PASSWORD_EXPOSED, false);
495 mAuthStatusText = savedInstanceState.getInt(KEY_AUTH_STATUS_TEXT);
496 mAuthStatusIcon = savedInstanceState.getInt(KEY_AUTH_STATUS_ICON);
497 mAuthToken = savedInstanceState.getString(KEY_AUTH_TOKEN);
498 }
499
500 /// step 2 - set properties of UI elements (text, visibility, enabled...)
501 mOAuth2Check.setChecked(
502 AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType())
503 .equals(mAuthTokenType));
504 if (presetUserName != null) {
505 mUsernameInput.setText(presetUserName);
506 }
507 if (mAction != ACTION_CREATE) {
508 mUsernameInput.setEnabled(false);
509 mUsernameInput.setFocusable(false);
510 }
511 mPasswordInput.setText(""); // clean password to avoid social hacking
512 if (isPasswordExposed) {
513 showPassword();
514 }
515 updateAuthenticationPreFragmentVisibility();
516 showAuthStatus();
517 mOkButton.setEnabled(mServerIsValid);
518
519
520 /// step 3 - bind listeners
521 // bindings for password input field
522 mPasswordInput.setOnFocusChangeListener(this);
523 mPasswordInput.setImeOptions(EditorInfo.IME_ACTION_DONE);
524 mPasswordInput.setOnEditorActionListener(this);
525 mPasswordInput.setOnTouchListener(new RightDrawableOnTouchListener() {
526 @Override
527 public boolean onDrawableTouch(final MotionEvent event) {
528 if (event.getAction() == MotionEvent.ACTION_UP) {
529 AuthenticatorActivity.this.onViewPasswordClick();
530 }
531 return true;
532 }
533 });
534
535 }
536
537
538 /**
539 * Changes the visibility of input elements depending on
540 * the current authorization method.
541 */
542 private void updateAuthenticationPreFragmentVisibility () {
543 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
544 equals(mAuthTokenType)) {
545 // SAML-based web Single Sign On
546 mOAuth2Check.setVisibility(View.GONE);
547 mOAuthAuthEndpointText.setVisibility(View.GONE);
548 mOAuthTokenEndpointText.setVisibility(View.GONE);
549 mUsernameInput.setVisibility(View.GONE);
550 mPasswordInput.setVisibility(View.GONE);
551
552 } else {
553 if (mAction == ACTION_CREATE &&
554 AUTH_OPTIONAL.equals(getString(R.string.auth_method_oauth2))) {
555 mOAuth2Check.setVisibility(View.VISIBLE);
556 } else {
557 mOAuth2Check.setVisibility(View.GONE);
558 }
559
560 if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).
561 equals(mAuthTokenType)) {
562 // OAuth 2 authorization
563
564 mOAuthAuthEndpointText.setVisibility(View.VISIBLE);
565 mOAuthTokenEndpointText.setVisibility(View.VISIBLE);
566 mUsernameInput.setVisibility(View.GONE);
567 mPasswordInput.setVisibility(View.GONE);
568
569 } else {
570 // basic HTTP authorization
571 mOAuthAuthEndpointText.setVisibility(View.GONE);
572 mOAuthTokenEndpointText.setVisibility(View.GONE);
573 mUsernameInput.setVisibility(View.VISIBLE);
574 mPasswordInput.setVisibility(View.VISIBLE);
575 }
576 }
577 }
578
579
580
581 /**
582 * Saves relevant state before {@link #onPause()}
583 *
584 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag,
585 * intended to defer the processing of the redirection caught in
586 * {@link #onNewIntent(Intent)} until {@link #onResume()}
587 *
588 * See {@link super#onSaveInstanceState(Bundle)}
589 */
590 @Override
591 protected void onSaveInstanceState(Bundle outState) {
592 //Log_OC.wtf(TAG, "onSaveInstanceState init" );
593 super.onSaveInstanceState(outState);
594
595 /// global state
596 outState.putString(KEY_AUTH_TOKEN_TYPE, mAuthTokenType);
597 outState.putLong(KEY_WAITING_FOR_OP_ID, mWaitingForOpId);
598
599 /// Server PRE-fragment state
600 outState.putInt(KEY_SERVER_STATUS_TEXT, mServerStatusText);
601 outState.putInt(KEY_SERVER_STATUS_ICON, mServerStatusIcon);
602 outState.putBoolean(KEY_SERVER_CHECKED, mServerIsChecked);
603 outState.putBoolean(KEY_SERVER_VALID, mServerIsValid);
604 outState.putBoolean(KEY_IS_SSL_CONN, mServerInfo.mIsSslConn);
605 outState.putString(KEY_HOST_URL_TEXT, mServerInfo.mBaseUrl);
606 if (mServerInfo.mVersion != null) {
607 outState.putString(KEY_OC_VERSION, mServerInfo.mVersion.getVersion());
608 }
609 outState.putString(KEY_SERVER_AUTH_METHOD, mServerInfo.mAuthMethod.name());
610
611 /// Authentication PRE-fragment state
612 outState.putBoolean(KEY_PASSWORD_EXPOSED, isPasswordVisible());
613 outState.putInt(KEY_AUTH_STATUS_ICON, mAuthStatusIcon);
614 outState.putInt(KEY_AUTH_STATUS_TEXT, mAuthStatusText);
615 outState.putString(KEY_AUTH_TOKEN, mAuthToken);
616
617 /// authentication
618 outState.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG, mIsFirstAuthAttempt);
619
620 /// AsyncTask (User and password)
621 outState.putString(KEY_USERNAME, mUsernameInput.getText().toString());
622 outState.putString(KEY_PASSWORD, mPasswordInput.getText().toString());
623
624 if (mAsyncTask != null) {
625 mAsyncTask.cancel(true);
626 outState.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS, true);
627 } else {
628 outState.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS, false);
629 }
630 mAsyncTask = null;
631
632 //Log_OC.wtf(TAG, "onSaveInstanceState end" );
633 }
634
635 @Override
636 public void onRestoreInstanceState(Bundle savedInstanceState) {
637 super.onRestoreInstanceState(savedInstanceState);
638
639 // AsyncTask
640 boolean inProgress = savedInstanceState.getBoolean(KEY_ASYNC_TASK_IN_PROGRESS);
641 if (inProgress){
642 String username = savedInstanceState.getString(KEY_USERNAME);
643 String password = savedInstanceState.getString(KEY_PASSWORD);
644
645 OwnCloudCredentials credentials = null;
646 if (BASIC_TOKEN_TYPE.equals(mAuthTokenType)) {
647 credentials = OwnCloudCredentialsFactory.newBasicCredentials(username, password);
648
649 } else if (OAUTH_TOKEN_TYPE.equals(mAuthTokenType)) {
650 credentials = OwnCloudCredentialsFactory.newBearerCredentials(mAuthToken);
651
652 }
653 accessRootFolder(credentials);
654 }
655 }
656
657 /**
658 * The redirection triggered by the OAuth authentication server as response to the
659 * GET AUTHORIZATION request is caught here.
660 *
661 * To make this possible, this activity needs to be qualified with android:launchMode =
662 * "singleTask" in the AndroidManifest.xml file.
663 */
664 @Override
665 protected void onNewIntent (Intent intent) {
666 Log_OC.d(TAG, "onNewIntent()");
667 Uri data = intent.getData();
668 if (data != null && data.toString().startsWith(getString(R.string.oauth2_redirect_uri))) {
669 mNewCapturedUriFromOAuth2Redirection = data;
670 }
671 }
672
673
674 /**
675 * The redirection triggered by the OAuth authentication server as response to the
676 * GET AUTHORIZATION, and deferred in {@link #onNewIntent(Intent)}, is processed here.
677 */
678 @Override
679 protected void onResume() {
680 super.onResume();
681
682 // bound here to avoid spurious changes triggered by Android on device rotations
683 mHostUrlInput.setOnFocusChangeListener(this);
684 mHostUrlInput.addTextChangedListener(mHostUrlInputWatcher);
685
686 if (mNewCapturedUriFromOAuth2Redirection != null) {
687 getOAuth2AccessTokenFromCapturedRedirection();
688 }
689
690 if (mOperationsServiceBinder != null) {
691 doOnResumeAndBound();
692 }
693
694 }
695
696
697 @Override
698 protected void onPause() {
699 if (mOperationsServiceBinder != null) {
700 mOperationsServiceBinder.removeOperationListener(this);
701 }
702
703 mHostUrlInput.removeTextChangedListener(mHostUrlInputWatcher);
704 mHostUrlInput.setOnFocusChangeListener(null);
705
706 super.onPause();
707 }
708
709 @Override
710 protected void onDestroy() {
711
712 mHostUrlInputWatcher = null;
713
714 if (mOperationsServiceConnection != null) {
715 unbindService(mOperationsServiceConnection);
716 mOperationsServiceBinder = null;
717 }
718 super.onDestroy();
719 }
720
721
722 /**
723 * Parses the redirection with the response to the GET AUTHORIZATION request to the
724 * oAuth server and requests for the access token (GET ACCESS TOKEN)
725 */
726 private void getOAuth2AccessTokenFromCapturedRedirection() {
727 /// Parse data from OAuth redirection
728 String queryParameters = mNewCapturedUriFromOAuth2Redirection.getQuery();
729 mNewCapturedUriFromOAuth2Redirection = null;
730
731 /// Showing the dialog with instructions for the user.
732 IndeterminateProgressDialog dialog =
733 IndeterminateProgressDialog.newInstance(R.string.auth_getting_authorization, true);
734 dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);
735
736 /// GET ACCESS TOKEN to the oAuth server
737 Intent getServerInfoIntent = new Intent();
738 getServerInfoIntent.setAction(OperationsService.ACTION_OAUTH2_GET_ACCESS_TOKEN);
739
740 getServerInfoIntent.putExtra(
741 OperationsService.EXTRA_SERVER_URL,
742 mOAuthTokenEndpointText.getText().toString().trim());
743
744 getServerInfoIntent.putExtra(
745 OperationsService.EXTRA_OAUTH2_QUERY_PARAMETERS,
746 queryParameters);
747
748 if (mOperationsServiceBinder != null) {
749 //Log_OC.wtf(TAG, "getting access token..." );
750 mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getServerInfoIntent);
751 }
752 }
753
754
755
756 /**
757 * Handles the change of focus on the text inputs for the server URL and the password
758 */
759 public void onFocusChange(View view, boolean hasFocus) {
760 if (view.getId() == R.id.hostUrlInput) {
761 if (!hasFocus) {
762 onUrlInputFocusLost();
763 }
764 else {
765 showRefreshButton(false);
766 }
767
768 } else if (view.getId() == R.id.account_password) {
769 onPasswordFocusChanged(hasFocus);
770 }
771 }
772
773
774 /**
775 * Handles changes in focus on the text input for the server URL.
776 *
777 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
778 * other field. The operation to check the existence of the server in the entered URL is
779 * started.
780 *
781 * When hasFocus: user 'comes back' to write again the server URL.
782 */
783 private void onUrlInputFocusLost() {
784 if (!mServerInfo.mBaseUrl.equals(
785 normalizeUrl(mHostUrlInput.getText().toString(), mServerInfo.mIsSslConn))) {
786 // check server again only if the user changed something in the field
787 checkOcServer();
788 } else {
789 mOkButton.setEnabled(mServerIsValid);
790 showRefreshButton(!mServerIsValid);
791 }
792 }
793
794
795 private void checkOcServer() {
796 String uri = mHostUrlInput.getText().toString().trim();
797 mServerIsValid = false;
798 mServerIsChecked = false;
799 mOkButton.setEnabled(false);
800 mServerInfo = new GetServerInfoOperation.ServerInfo();
801 showRefreshButton(false);
802
803 if (uri.length() != 0) {
804 uri = stripIndexPhpOrAppsFiles(uri, mHostUrlInput);
805
806 // Handle internationalized domain names
807 uri = DisplayUtils.convertIdn(uri, true);
808
809 mServerStatusText = R.string.auth_testing_connection;
810 mServerStatusIcon = R.drawable.progress_small;
811 showServerStatus();
812
813 Intent getServerInfoIntent = new Intent();
814 getServerInfoIntent.setAction(OperationsService.ACTION_GET_SERVER_INFO);
815 getServerInfoIntent.putExtra(
816 OperationsService.EXTRA_SERVER_URL,
817 normalizeUrlSuffix(uri)
818 );
819 if (mOperationsServiceBinder != null) {
820 mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getServerInfoIntent);
821 } else {
822 Log_OC.wtf(TAG, "Server check tried with OperationService unbound!" );
823 }
824
825 } else {
826 mServerStatusText = 0;
827 mServerStatusIcon = 0;
828 showServerStatus();
829 }
830 }
831
832
833 /**
834 * Handles changes in focus on the text input for the password (basic authorization).
835 *
836 * When (hasFocus), the button to toggle password visibility is shown.
837 *
838 * When (!hasFocus), the button is made invisible and the password is hidden.
839 *
840 * @param hasFocus 'True' if focus is received, 'false' if is lost
841 */
842 private void onPasswordFocusChanged(boolean hasFocus) {
843 if (hasFocus) {
844 showViewPasswordButton();
845 } else {
846 hidePassword();
847 hidePasswordButton();
848 }
849 }
850
851
852 private void showViewPasswordButton() {
853 int drawable = R.drawable.ic_view;
854 if (isPasswordVisible()) {
855 drawable = R.drawable.ic_hide;
856 }
857 mPasswordInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable, 0);
858 }
859
860 private boolean isPasswordVisible() {
861 return ((mPasswordInput.getInputType() & InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) ==
862 InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
863 }
864
865 private void hidePasswordButton() {
866 mPasswordInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
867 }
868
869 private void showPassword() {
870 mPasswordInput.setInputType(
871 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
872 );
873 showViewPasswordButton();
874 }
875
876 private void hidePassword() {
877 mPasswordInput.setInputType(
878 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
879 );
880 showViewPasswordButton();
881 }
882
883 /**
884 * Checks the credentials of the user in the root of the ownCloud server
885 * before creating a new local account.
886 *
887 * For basic authorization, a check of existence of the root folder is
888 * performed.
889 *
890 * For OAuth, starts the flow to get an access token; the credentials test
891 * is postponed until it is available.
892 *
893 * IMPORTANT ENTRY POINT 4
894 */
895 public void onOkClick() {
896 // this check should be unnecessary
897 if (mServerInfo.mVersion == null ||
898 !mServerInfo.mVersion.isVersionValid() ||
899 mServerInfo.mBaseUrl == null ||
900 mServerInfo.mBaseUrl.length() == 0) {
901 mServerStatusIcon = R.drawable.common_error;
902 mServerStatusText = R.string.auth_wtf_reenter_URL;
903 showServerStatus();
904 mOkButton.setEnabled(false);
905 return;
906 }
907
908 if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).
909 equals(mAuthTokenType)) {
910
911 startOauthorization();
912 } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
913 equals(mAuthTokenType)) {
914
915 startSamlBasedFederatedSingleSignOnAuthorization();
916 } else {
917 checkBasicAuthorization();
918 }
919 }
920
921
922 /**
923 * Tests the credentials entered by the user performing a check of existence on
924 * the root folder of the ownCloud server.
925 */
926 private void checkBasicAuthorization() {
927 /// get basic credentials entered by user
928 String username = mUsernameInput.getText().toString();
929 String password = mPasswordInput.getText().toString();
930
931 /// be gentle with the user
932 IndeterminateProgressDialog dialog =
933 IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);
934 dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);
935
936 /// validate credentials accessing the root folder
937 OwnCloudCredentials credentials = OwnCloudCredentialsFactory.newBasicCredentials(username,
938 password);
939 accessRootFolder(credentials);
940 }
941
942 private void accessRootFolder(OwnCloudCredentials credentials) {
943 mAsyncTask = new AuthenticatorAsyncTask(this);
944 Object[] params = { mServerInfo.mBaseUrl, credentials };
945 mAsyncTask.execute(params);
946 }
947
948
949 /**
950 * Starts the OAuth 'grant type' flow to get an access token, with
951 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
952 */
953 private void startOauthorization() {
954 // be gentle with the user
955 mAuthStatusIcon = R.drawable.progress_small;
956 mAuthStatusText = R.string.oauth_login_connection;
957 showAuthStatus();
958
959 // GET AUTHORIZATION request
960 Uri uri = Uri.parse(mOAuthAuthEndpointText.getText().toString().trim());
961 Uri.Builder uriBuilder = uri.buildUpon();
962 uriBuilder.appendQueryParameter(
963 OAuth2Constants.KEY_RESPONSE_TYPE, getString(R.string.oauth2_response_type)
964 );
965 uriBuilder.appendQueryParameter(
966 OAuth2Constants.KEY_REDIRECT_URI, getString(R.string.oauth2_redirect_uri)
967 );
968 uriBuilder.appendQueryParameter(
969 OAuth2Constants.KEY_CLIENT_ID, getString(R.string.oauth2_client_id)
970 );
971 uriBuilder.appendQueryParameter(
972 OAuth2Constants.KEY_SCOPE, getString(R.string.oauth2_scope)
973 );
974 uri = uriBuilder.build();
975 Log_OC.d(TAG, "Starting browser to view " + uri.toString());
976 Intent i = new Intent(Intent.ACTION_VIEW, uri);
977 startActivity(i);
978 }
979
980
981 /**
982 * Starts the Web Single Sign On flow to get access to the root folder
983 * in the server.
984 */
985 private void startSamlBasedFederatedSingleSignOnAuthorization() {
986 /// be gentle with the user
987 mAuthStatusIcon = R.drawable.progress_small;
988 mAuthStatusText = R.string.auth_connecting_auth_server;
989 showAuthStatus();
990
991 /// Show SAML-based SSO web dialog
992 String targetUrl = mServerInfo.mBaseUrl
993 + AccountUtils.getWebdavPath(mServerInfo.mVersion, mAuthTokenType);
994 SamlWebViewDialog dialog = SamlWebViewDialog.newInstance(targetUrl, targetUrl);
995 dialog.show(getSupportFragmentManager(), SAML_DIALOG_TAG);
996 }
997
998 /**
999 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
1000 *
1001 * Dispatches the operation flow to the right method.
1002 */
1003 @Override
1004 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1005
1006 if (operation instanceof GetServerInfoOperation) {
1007 if (operation.hashCode() == mWaitingForOpId) {
1008 onGetServerInfoFinish(result);
1009 } // else nothing ; only the last check operation is considered;
1010 // multiple can be started if the user amends a URL quickly
1011
1012 } else if (operation instanceof OAuth2GetAccessToken) {
1013 onGetOAuthAccessTokenFinish(result);
1014
1015 } else if (operation instanceof GetRemoteUserNameOperation) {
1016 onGetUserNameFinish(result);
1017 }
1018
1019 }
1020
1021 private void onGetUserNameFinish(RemoteOperationResult result) {
1022 mWaitingForOpId = Long.MAX_VALUE;
1023 if (result.isSuccess()) {
1024 boolean success = false;
1025 String username = (String) result.getData().get(0);
1026
1027 if ( mAction == ACTION_CREATE) {
1028 mUsernameInput.setText(username);
1029 success = createAccount(result);
1030 } else {
1031
1032 if (!mUsernameInput.getText().toString().equals(username)) {
1033 // fail - not a new account, but an existing one; disallow
1034 result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_THE_SAME);
1035 mAuthToken = "";
1036 updateAuthStatusIconAndText(result);
1037 showAuthStatus();
1038 Log_OC.d(TAG, result.getLogMessage());
1039 } else {
1040 try {
1041 updateAccountAuthentication();
1042 success = true;
1043
1044 } catch (AccountNotFoundException e) {
1045 Log_OC.e(TAG, "Account " + mAccount + " was removed!", e);
1046 Toast.makeText(this, R.string.auth_account_does_not_exist,
1047 Toast.LENGTH_SHORT).show();
1048 finish();
1049 }
1050 }
1051 }
1052
1053 if (success)
1054 finish();
1055 } else {
1056 updateStatusIconFailUserName();
1057 showAuthStatus();
1058 Log_OC.e(TAG, "Access to user name failed: " + result.getLogMessage());
1059 }
1060
1061 }
1062
1063 /**
1064 * Processes the result of the server check performed when the user finishes the enter of the
1065 * server URL.
1066 *
1067 * @param result Result of the check.
1068 */
1069 private void onGetServerInfoFinish(RemoteOperationResult result) {
1070 /// update activity state
1071 mServerIsChecked = true;
1072 mWaitingForOpId = Long.MAX_VALUE;
1073
1074 // update server status, but don't show it yet
1075 updateServerStatusIconAndText(result);
1076
1077 if (result.isSuccess()) {
1078 /// SUCCESS means:
1079 // 1. connection succeeded, and we know if it's SSL or not
1080 // 2. server is installed
1081 // 3. we got the server version
1082 // 4. we got the authentication method required by the server
1083 mServerInfo = (GetServerInfoOperation.ServerInfo) (result.getData().get(0));
1084
1085 if (!authSupported(mServerInfo.mAuthMethod)) {
1086
1087 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1088 mServerIsValid = false;
1089
1090 } else {
1091 mServerIsValid = true;
1092 }
1093
1094 } else {
1095 mServerIsValid = false;
1096 }
1097
1098 // refresh UI
1099 showRefreshButton(!mServerIsValid);
1100 showServerStatus();
1101 mOkButton.setEnabled(mServerIsValid);
1102
1103 /// very special case (TODO: move to a common place for all the remote operations)
1104 if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
1105 showUntrustedCertDialog(result);
1106 }
1107 }
1108
1109
1110 private boolean authSupported(AuthenticationMethod authMethod) {
1111 return (( BASIC_TOKEN_TYPE.equals(mAuthTokenType) &&
1112 AuthenticationMethod.BASIC_HTTP_AUTH.equals(authMethod) ) ||
1113 ( OAUTH_TOKEN_TYPE.equals(mAuthTokenType) &&
1114 AuthenticationMethod.BEARER_TOKEN.equals(authMethod)) ||
1115 ( SAML_TOKEN_TYPE.equals(mAuthTokenType) &&
1116 AuthenticationMethod.SAML_WEB_SSO.equals(authMethod))
1117 );
1118 }
1119
1120
1121 // TODO remove, if possible
1122 private String normalizeUrl(String url, boolean sslWhenUnprefixed) {
1123 if (url != null && url.length() > 0) {
1124 url = url.trim();
1125 if (!url.toLowerCase().startsWith("http://") &&
1126 !url.toLowerCase().startsWith("https://")) {
1127 if (sslWhenUnprefixed) {
1128 url = "https://" + url;
1129 } else {
1130 url = "http://" + url;
1131 }
1132 }
1133
1134 url = normalizeUrlSuffix(url);
1135 }
1136 return (url != null ? url : "");
1137 }
1138
1139
1140 private String normalizeUrlSuffix(String url) {
1141 if (url.endsWith("/")) {
1142 url = url.substring(0, url.length() - 1);
1143 }
1144 url = trimUrlWebdav(url);
1145 return url;
1146 }
1147
1148 private String stripIndexPhpOrAppsFiles(String url, EditText mHostUrlInput) {
1149 if (url.endsWith("/index.php")) {
1150 url = url.substring(0, url.lastIndexOf("/index.php"));
1151 mHostUrlInput.setText(url);
1152 } else if (url.contains("/index.php/apps/")) {
1153 url = url.substring(0, url.lastIndexOf("/index.php/apps/"));
1154 mHostUrlInput.setText(url);
1155 }
1156
1157 return url;
1158 }
1159
1160 // TODO remove, if possible
1161 private String trimUrlWebdav(String url){
1162 if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0_AND_LATER)){
1163 url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0_AND_LATER.length());
1164 }
1165 return url;
1166 }
1167
1168
1169 /**
1170 * Chooses the right icon and text to show to the user for the received operation result.
1171 *
1172 * @param result Result of a remote operation performed in this activity
1173 */
1174 private void updateServerStatusIconAndText(RemoteOperationResult result) {
1175 mServerStatusIcon = R.drawable.common_error; // the most common case in the switch below
1176
1177 switch (result.getCode()) {
1178 case OK_SSL:
1179 mServerStatusIcon = R.drawable.ic_lock;
1180 mServerStatusText = R.string.auth_secure_connection;
1181 break;
1182
1183 case OK_NO_SSL:
1184 case OK:
1185 if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1186 mServerStatusText = R.string.auth_connection_established;
1187 mServerStatusIcon = R.drawable.ic_ok;
1188 } else {
1189 mServerStatusText = R.string.auth_nossl_plain_ok_title;
1190 mServerStatusIcon = R.drawable.ic_lock_open;
1191 }
1192 break;
1193
1194 case NO_NETWORK_CONNECTION:
1195 mServerStatusIcon = R.drawable.no_network;
1196 mServerStatusText = R.string.auth_no_net_conn_title;
1197 break;
1198
1199 case SSL_RECOVERABLE_PEER_UNVERIFIED:
1200 mServerStatusText = R.string.auth_ssl_unverified_server_title;
1201 break;
1202 case BAD_OC_VERSION:
1203 mServerStatusText = R.string.auth_bad_oc_version_title;
1204 break;
1205 case WRONG_CONNECTION:
1206 mServerStatusText = R.string.auth_wrong_connection_title;
1207 break;
1208 case TIMEOUT:
1209 mServerStatusText = R.string.auth_timeout_title;
1210 break;
1211 case INCORRECT_ADDRESS:
1212 mServerStatusText = R.string.auth_incorrect_address_title;
1213 break;
1214 case SSL_ERROR:
1215 mServerStatusText = R.string.auth_ssl_general_error_title;
1216 break;
1217 case UNAUTHORIZED:
1218 mServerStatusText = R.string.auth_unauthorized;
1219 break;
1220 case HOST_NOT_AVAILABLE:
1221 mServerStatusText = R.string.auth_unknown_host_title;
1222 break;
1223 case INSTANCE_NOT_CONFIGURED:
1224 mServerStatusText = R.string.auth_not_configured_title;
1225 break;
1226 case FILE_NOT_FOUND:
1227 mServerStatusText = R.string.auth_incorrect_path_title;
1228 break;
1229 case OAUTH2_ERROR:
1230 mServerStatusText = R.string.auth_oauth_error;
1231 break;
1232 case OAUTH2_ERROR_ACCESS_DENIED:
1233 mServerStatusText = R.string.auth_oauth_error_access_denied;
1234 break;
1235 case UNHANDLED_HTTP_CODE:
1236 case UNKNOWN_ERROR:
1237 mServerStatusText = R.string.auth_unknown_error_title;
1238 break;
1239 case OK_REDIRECT_TO_NON_SECURE_CONNECTION:
1240 mServerStatusIcon = R.drawable.ic_lock_open;
1241 mServerStatusText = R.string.auth_redirect_non_secure_connection_title;
1242 break;
1243 default:
1244 mServerStatusText = 0;
1245 mServerStatusIcon = 0;
1246 }
1247 }
1248
1249
1250 /**
1251 * Chooses the right icon and text to show to the user for the received operation result.
1252 *
1253 * @param result Result of a remote operation performed in this activity
1254 */
1255 private void updateAuthStatusIconAndText(RemoteOperationResult result) {
1256 mAuthStatusIcon = R.drawable.common_error; // the most common case in the switch below
1257
1258 switch (result.getCode()) {
1259 case OK_SSL:
1260 mAuthStatusIcon = R.drawable.ic_lock;
1261 mAuthStatusText = R.string.auth_secure_connection;
1262 break;
1263
1264 case OK_NO_SSL:
1265 case OK:
1266 if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1267 mAuthStatusText = R.string.auth_connection_established;
1268 mAuthStatusIcon = R.drawable.ic_ok;
1269 } else {
1270 mAuthStatusText = R.string.auth_nossl_plain_ok_title;
1271 mAuthStatusIcon = R.drawable.ic_lock_open;
1272 }
1273 break;
1274
1275 case NO_NETWORK_CONNECTION:
1276 mAuthStatusIcon = R.drawable.no_network;
1277 mAuthStatusText = R.string.auth_no_net_conn_title;
1278 break;
1279
1280 case SSL_RECOVERABLE_PEER_UNVERIFIED:
1281 mAuthStatusText = R.string.auth_ssl_unverified_server_title;
1282 break;
1283 case BAD_OC_VERSION:
1284 mAuthStatusText = R.string.auth_bad_oc_version_title;
1285 break;
1286 case WRONG_CONNECTION:
1287 mAuthStatusText = R.string.auth_wrong_connection_title;
1288 break;
1289 case TIMEOUT:
1290 mAuthStatusText = R.string.auth_timeout_title;
1291 break;
1292 case INCORRECT_ADDRESS:
1293 mAuthStatusText = R.string.auth_incorrect_address_title;
1294 break;
1295 case SSL_ERROR:
1296 mAuthStatusText = R.string.auth_ssl_general_error_title;
1297 break;
1298 case UNAUTHORIZED:
1299 mAuthStatusText = R.string.auth_unauthorized;
1300 break;
1301 case HOST_NOT_AVAILABLE:
1302 mAuthStatusText = R.string.auth_unknown_host_title;
1303 break;
1304 case INSTANCE_NOT_CONFIGURED:
1305 mAuthStatusText = R.string.auth_not_configured_title;
1306 break;
1307 case FILE_NOT_FOUND:
1308 mAuthStatusText = R.string.auth_incorrect_path_title;
1309 break;
1310 case OAUTH2_ERROR:
1311 mAuthStatusText = R.string.auth_oauth_error;
1312 break;
1313 case OAUTH2_ERROR_ACCESS_DENIED:
1314 mAuthStatusText = R.string.auth_oauth_error_access_denied;
1315 break;
1316 case ACCOUNT_NOT_NEW:
1317 mAuthStatusText = R.string.auth_account_not_new;
1318 break;
1319 case ACCOUNT_NOT_THE_SAME:
1320 mAuthStatusText = R.string.auth_account_not_the_same;
1321 break;
1322 case UNHANDLED_HTTP_CODE:
1323 case UNKNOWN_ERROR:
1324 mAuthStatusText = R.string.auth_unknown_error_title;
1325 break;
1326 default:
1327 mAuthStatusText = 0;
1328 mAuthStatusIcon = 0;
1329 }
1330 }
1331
1332
1333 private void updateStatusIconFailUserName(){
1334 mAuthStatusIcon = R.drawable.common_error;
1335 mAuthStatusText = R.string.auth_fail_get_user_name;
1336 }
1337
1338 private void updateServerStatusIconNoRegularAuth(){
1339 mServerStatusIcon = R.drawable.common_error;
1340 mServerStatusText = R.string.auth_can_not_auth_against_server;
1341 }
1342
1343 /**
1344 * Processes the result of the request for and access token send
1345 * to an OAuth authorization server.
1346 *
1347 * @param result Result of the operation.
1348 */
1349 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result) {
1350 mWaitingForOpId = Long.MAX_VALUE;
1351 dismissDialog(WAIT_DIALOG_TAG);
1352
1353 if (result.isSuccess()) {
1354 /// be gentle with the user
1355 IndeterminateProgressDialog dialog =
1356 IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);
1357 dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);
1358
1359 /// time to test the retrieved access token on the ownCloud server
1360 @SuppressWarnings("unchecked")
1361 Map<String, String> tokens = (Map<String, String>)(result.getData().get(0));
1362 mAuthToken = tokens.get(OAuth2Constants.KEY_ACCESS_TOKEN);
1363 Log_OC.d(TAG, "Got ACCESS TOKEN: " + mAuthToken);
1364
1365 /// validate token accessing to root folder / getting session
1366 OwnCloudCredentials credentials = OwnCloudCredentialsFactory.newBearerCredentials(
1367 mAuthToken);
1368 accessRootFolder(credentials);
1369
1370 } else {
1371 updateAuthStatusIconAndText(result);
1372 showAuthStatus();
1373 Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
1374 }
1375 }
1376
1377
1378 /**
1379 * Processes the result of the access check performed to try the user credentials.
1380 *
1381 * Creates a new account through the AccountManager.
1382 *
1383 * @param result Result of the operation.
1384 */
1385 @Override
1386 public void onAuthenticatorTaskCallback(RemoteOperationResult result) {
1387 mWaitingForOpId = Long.MAX_VALUE;
1388 dismissDialog(WAIT_DIALOG_TAG);
1389
1390 if (result.isSuccess()) {
1391 Log_OC.d(TAG, "Successful access - time to save the account");
1392
1393 boolean success = false;
1394
1395 if (mAction == ACTION_CREATE) {
1396 success = createAccount(result);
1397
1398 } else {
1399 try {
1400 updateAccountAuthentication();
1401 success = true;
1402
1403 } catch (AccountNotFoundException e) {
1404 Log_OC.e(TAG, "Account " + mAccount + " was removed!", e);
1405 Toast.makeText(this, R.string.auth_account_does_not_exist,
1406 Toast.LENGTH_SHORT).show();
1407 finish();
1408 }
1409 }
1410
1411 if (success) {
1412 finish();
1413 }
1414
1415 } else if (result.isServerFail() || result.isException()) {
1416 /// server errors or exceptions in authorization take to requiring a new check of
1417 /// the server
1418 mServerIsChecked = true;
1419 mServerIsValid = false;
1420 mServerInfo = new GetServerInfoOperation.ServerInfo();
1421
1422 // update status icon and text
1423 updateServerStatusIconAndText(result);
1424 showServerStatus();
1425 mAuthStatusIcon = 0;
1426 mAuthStatusText = 0;
1427 showAuthStatus();
1428
1429 // update input controls state
1430 showRefreshButton(true);
1431 mOkButton.setEnabled(false);
1432
1433 // very special case (TODO: move to a common place for all the remote operations)
1434 if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
1435 showUntrustedCertDialog(result);
1436 }
1437
1438 } else { // authorization fail due to client side - probably wrong credentials
1439 updateAuthStatusIconAndText(result);
1440 showAuthStatus();
1441 Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
1442 }
1443 }
1444
1445
1446
1447
1448 /**
1449 * Updates the authentication token.
1450 *
1451 * Sets the proper response so that the AccountAuthenticator that started this activity
1452 * saves a new authorization token for mAccount.
1453 *
1454 * Kills the session kept by OwnCloudClientManager so that a new one will created with
1455 * the new credentials when needed.
1456 */
1457 private void updateAccountAuthentication() throws AccountNotFoundException {
1458
1459 Bundle response = new Bundle();
1460 response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
1461 response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);
1462
1463 if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).
1464 equals(mAuthTokenType)) {
1465 response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
1466 // the next line is necessary, notifications are calling directly to the
1467 // AuthenticatorActivity to update, without AccountManager intervention
1468 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
1469
1470 } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
1471 equals(mAuthTokenType)) {
1472
1473 response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
1474 // the next line is necessary; by now, notifications are calling directly to the
1475 // AuthenticatorActivity to update, without AccountManager intervention
1476 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
1477
1478 } else {
1479 response.putString(AccountManager.KEY_AUTHTOKEN, mPasswordInput.getText().toString());
1480 mAccountMgr.setPassword(mAccount, mPasswordInput.getText().toString());
1481 }
1482 setAccountAuthenticatorResult(response);
1483
1484 }
1485
1486
1487 /**
1488 * Creates a new account through the Account Authenticator that started this activity.
1489 *
1490 * This makes the account permanent.
1491 *
1492 * TODO Decide how to name the OAuth accounts
1493 */
1494 private boolean createAccount(RemoteOperationResult authResult) {
1495 /// create and save new ownCloud account
1496 boolean isOAuth = AccountTypeUtils.
1497 getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType);
1498 boolean isSaml = AccountTypeUtils.
1499 getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType);
1500
1501 String lastPermanentLocation = authResult.getLastPermanentLocation();
1502 if (lastPermanentLocation != null) {
1503 mServerInfo.mBaseUrl = AccountUtils.trimWebdavSuffix(lastPermanentLocation);
1504 }
1505
1506 Uri uri = Uri.parse(mServerInfo.mBaseUrl);
1507 String username = mUsernameInput.getText().toString().trim();
1508 if (isOAuth) {
1509 username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();
1510 }
1511 String accountName = com.owncloud.android.lib.common.accounts.AccountUtils.
1512 buildAccountName(uri, username);
1513 Account newAccount = new Account(accountName, MainApp.getAccountType());
1514 if (AccountUtils.exists(newAccount, getApplicationContext())) {
1515 // fail - not a new account, but an existing one; disallow
1516 RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW);
1517 updateAuthStatusIconAndText(result);
1518 showAuthStatus();
1519 Log_OC.d(TAG, result.getLogMessage());
1520 return false;
1521
1522 } else {
1523 mAccount = newAccount;
1524
1525 if (isOAuth || isSaml) {
1526 // with external authorizations, the password is never input in the app
1527 mAccountMgr.addAccountExplicitly(mAccount, "", null);
1528 } else {
1529 mAccountMgr.addAccountExplicitly(
1530 mAccount, mPasswordInput.getText().toString(), null
1531 );
1532 }
1533
1534 // include account version with the new account
1535 mAccountMgr.setUserData(
1536 mAccount,
1537 Constants.KEY_OC_ACCOUNT_VERSION,
1538 Integer.toString(AccountUtils.ACCOUNT_VERSION)
1539 );
1540
1541 /// add the new account as default in preferences, if there is none already
1542 Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
1543 if (defaultAccount == null) {
1544 SharedPreferences.Editor editor = PreferenceManager
1545 .getDefaultSharedPreferences(this).edit();
1546 editor.putString("select_oc_account", accountName);
1547 editor.commit();
1548 }
1549
1550 /// prepare result to return to the Authenticator
1551 // TODO check again what the Authenticator makes with it; probably has the same
1552 // effect as addAccountExplicitly, but it's not well done
1553 final Intent intent = new Intent();
1554 intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, MainApp.getAccountType());
1555 intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
1556 intent.putExtra(AccountManager.KEY_USERDATA, username);
1557 if (isOAuth || isSaml) {
1558 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
1559 }
1560 /// add user data to the new account; TODO probably can be done in the last parameter
1561 // addAccountExplicitly, or in KEY_USERDATA
1562 mAccountMgr.setUserData(
1563 mAccount, Constants.KEY_OC_VERSION, mServerInfo.mVersion.getVersion()
1564 );
1565 mAccountMgr.setUserData(
1566 mAccount, Constants.KEY_OC_BASE_URL, mServerInfo.mBaseUrl
1567 );
1568
1569 if (isSaml) {
1570 mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE");
1571 } else if (isOAuth) {
1572 mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_OAUTH2, "TRUE");
1573 }
1574
1575 setAccountAuthenticatorResult(intent.getExtras());
1576 setResult(RESULT_OK, intent);
1577
1578 return true;
1579 }
1580 }
1581
1582
1583 /**
1584 * Starts and activity to open the 'new account' page in the ownCloud web site
1585 *
1586 * @param view 'Account register' button
1587 */
1588 public void onRegisterClick(View view) {
1589 Intent register = new Intent(
1590 Intent.ACTION_VIEW, Uri.parse(getString(R.string.welcome_link_url))
1591 );
1592 setResult(RESULT_CANCELED);
1593 startActivity(register);
1594 }
1595
1596
1597 /**
1598 * Updates the content and visibility state of the icon and text associated
1599 * to the last check on the ownCloud server.
1600 *
1601 */
1602 private void showServerStatus() {
1603 if (mServerStatusIcon == 0 && mServerStatusText == 0) {
1604 mServerStatusView.setVisibility(View.INVISIBLE);
1605
1606 } else {
1607 mServerStatusView.setText(mServerStatusText);
1608 mServerStatusView.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon, 0, 0, 0);
1609 mServerStatusView.setVisibility(View.VISIBLE);
1610 }
1611
1612 }
1613
1614
1615 /**
1616 * Updates the content and visibility state of the icon and text associated
1617 * to the interactions with the OAuth authorization server.
1618 */
1619 private void showAuthStatus() {
1620 if (mAuthStatusIcon == 0 && mAuthStatusText == 0) {
1621 mAuthStatusView.setVisibility(View.INVISIBLE);
1622
1623 } else {
1624 mAuthStatusView.setText(mAuthStatusText);
1625 mAuthStatusView.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon, 0, 0, 0);
1626 mAuthStatusView.setVisibility(View.VISIBLE);
1627 }
1628 }
1629
1630
1631 private void showRefreshButton (boolean show) {
1632 if (show) {
1633 mRefreshButton.setVisibility(View.VISIBLE);
1634 } else {
1635 mRefreshButton.setVisibility(View.GONE);
1636 }
1637 }
1638
1639 /**
1640 * Called when the refresh button in the input field for ownCloud host is clicked.
1641 *
1642 * Performs a new check on the URL in the input field.
1643 *
1644 * @param view Refresh 'button'
1645 */
1646 public void onRefreshClick(View view) {
1647 checkOcServer();
1648 }
1649
1650
1651 /**
1652 * Called when the eye icon in the password field is clicked.
1653 *
1654 * Toggles the visibility of the password in the field.
1655 */
1656 public void onViewPasswordClick() {
1657 int selectionStart = mPasswordInput.getSelectionStart();
1658 int selectionEnd = mPasswordInput.getSelectionEnd();
1659 if (isPasswordVisible()) {
1660 hidePassword();
1661 } else {
1662 showPassword();
1663 }
1664 mPasswordInput.setSelection(selectionStart, selectionEnd);
1665 }
1666
1667
1668 /**
1669 * Called when the checkbox for OAuth authorization is clicked.
1670 *
1671 * Hides or shows the input fields for user & password.
1672 *
1673 * @param view 'View password' 'button'
1674 */
1675 public void onCheckClick(View view) {
1676 CheckBox oAuth2Check = (CheckBox)view;
1677 if (oAuth2Check.isChecked()) {
1678 mAuthTokenType = OAUTH_TOKEN_TYPE;
1679 } else {
1680 mAuthTokenType = BASIC_TOKEN_TYPE;
1681 }
1682 updateAuthenticationPreFragmentVisibility();
1683 }
1684
1685
1686 /**
1687 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1688 *
1689 * Used to trigger the authentication check when the user presses 'enter' after writing the
1690 * password, or to throw the server test when the only field on screen is the URL input field.
1691 */
1692 @Override
1693 public boolean onEditorAction(TextView inputField, int actionId, KeyEvent event) {
1694 if (actionId == EditorInfo.IME_ACTION_DONE && inputField != null &&
1695 inputField.equals(mPasswordInput)) {
1696 if (mOkButton.isEnabled()) {
1697 mOkButton.performClick();
1698 }
1699
1700 } else if (actionId == EditorInfo.IME_ACTION_NEXT && inputField != null &&
1701 inputField.equals(mHostUrlInput)) {
1702 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
1703 equals(mAuthTokenType)) {
1704 checkOcServer();
1705 }
1706 }
1707 return false; // always return false to grant that the software keyboard is hidden anyway
1708 }
1709
1710
1711 private abstract static class RightDrawableOnTouchListener implements OnTouchListener {
1712
1713 private int fuzz = 75;
1714
1715 /**
1716 * {@inheritDoc}
1717 */
1718 @Override
1719 public boolean onTouch(View view, MotionEvent event) {
1720 Drawable rightDrawable = null;
1721 if (view instanceof TextView) {
1722 Drawable[] drawables = ((TextView)view).getCompoundDrawables();
1723 if (drawables.length > 2) {
1724 rightDrawable = drawables[2];
1725 }
1726 }
1727 if (rightDrawable != null) {
1728 final int x = (int) event.getX();
1729 final int y = (int) event.getY();
1730 final Rect bounds = rightDrawable.getBounds();
1731 if ( x >= (view.getRight() - bounds.width() - fuzz) &&
1732 x <= (view.getRight() - view.getPaddingRight() + fuzz) &&
1733 y >= (view.getPaddingTop() - fuzz) &&
1734 y <= (view.getHeight() - view.getPaddingBottom()) + fuzz) {
1735
1736 return onDrawableTouch(event);
1737 }
1738 }
1739 return false;
1740 }
1741
1742 public abstract boolean onDrawableTouch(final MotionEvent event);
1743 }
1744
1745
1746 private void getRemoteUserNameOperation(String sessionCookie) {
1747
1748 Intent getUserNameIntent = new Intent();
1749 getUserNameIntent.setAction(OperationsService.ACTION_GET_USER_NAME);
1750 getUserNameIntent.putExtra(OperationsService.EXTRA_SERVER_URL, mServerInfo.mBaseUrl);
1751 getUserNameIntent.putExtra(OperationsService.EXTRA_COOKIE, sessionCookie);
1752
1753 if (mOperationsServiceBinder != null) {
1754 mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getUserNameIntent);
1755 }
1756 }
1757
1758
1759 @Override
1760 public void onSsoFinished(String sessionCookie) {
1761 if (sessionCookie != null && sessionCookie.length() > 0) {
1762 Log_OC.d(TAG, "Successful SSO - time to save the account");
1763 mAuthToken = sessionCookie;
1764 getRemoteUserNameOperation(sessionCookie);
1765 Fragment fd = getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG);
1766 if (fd != null && fd instanceof DialogFragment) {
1767 Dialog d = ((DialogFragment)fd).getDialog();
1768 if (d != null && d.isShowing()) {
1769 d.dismiss();
1770 }
1771 }
1772
1773 } else {
1774 // TODO - show fail
1775 Log_OC.d(TAG, "SSO failed");
1776 }
1777
1778 }
1779
1780 @Override
1781 public boolean onTouchEvent(MotionEvent event) {
1782 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
1783 equals(mAuthTokenType) &&
1784 mHostUrlInput.hasFocus() && event.getAction() == MotionEvent.ACTION_DOWN) {
1785 checkOcServer();
1786 }
1787 return super.onTouchEvent(event);
1788 }
1789
1790
1791 /**
1792 * Show untrusted cert dialog
1793 */
1794 public void showUntrustedCertDialog(
1795 X509Certificate x509Certificate, SslError error, SslErrorHandler handler
1796 ) {
1797 // Show a dialog with the certificate info
1798 SslUntrustedCertDialog dialog;
1799 if (x509Certificate == null) {
1800 dialog = SslUntrustedCertDialog.newInstanceForEmptySslError(error, handler);
1801 } else {
1802 dialog = SslUntrustedCertDialog.
1803 newInstanceForFullSslError(x509Certificate, error, handler);
1804 }
1805 FragmentManager fm = getSupportFragmentManager();
1806 FragmentTransaction ft = fm.beginTransaction();
1807 ft.addToBackStack(null);
1808 dialog.show(ft, UNTRUSTED_CERT_DIALOG_TAG);
1809 }
1810
1811
1812 /**
1813 * Show untrusted cert dialog
1814 */
1815 private void showUntrustedCertDialog(RemoteOperationResult result) {
1816 // Show a dialog with the certificate info
1817 SslUntrustedCertDialog dialog = SslUntrustedCertDialog.
1818 newInstanceForFullSslError((CertificateCombinedException)result.getException());
1819 FragmentManager fm = getSupportFragmentManager();
1820 FragmentTransaction ft = fm.beginTransaction();
1821 ft.addToBackStack(null);
1822 dialog.show(ft, UNTRUSTED_CERT_DIALOG_TAG);
1823
1824 }
1825
1826 /**
1827 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1828 */
1829 public void onSavedCertificate() {
1830 Fragment fd = getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG);
1831 if (fd == null) {
1832 // if SAML dialog is not shown,
1833 // the SslDialog was shown due to an SSL error in the server check
1834 checkOcServer();
1835 }
1836 }
1837
1838 /**
1839 * Called from SslValidatorDialog when a new server certificate could not be saved
1840 * when the user requested it.
1841 */
1842 @Override
1843 public void onFailedSavingCertificate() {
1844 dismissDialog(SAML_DIALOG_TAG);
1845 Toast.makeText(this, R.string.ssl_validator_not_saved, Toast.LENGTH_LONG).show();
1846 }
1847
1848 @Override
1849 public void onCancelCertificate() {
1850 dismissDialog(SAML_DIALOG_TAG);
1851 }
1852
1853
1854 private void doOnResumeAndBound() {
1855 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1856 mOperationsServiceBinder.addOperationListener(AuthenticatorActivity.this, mHandler);
1857 if (mWaitingForOpId <= Integer.MAX_VALUE) {
1858 mOperationsServiceBinder.dispatchResultIfFinished((int)mWaitingForOpId, this);
1859 }
1860
1861 if (mPendingAutoCheck) {
1862 checkOcServer();
1863 }
1864 }
1865
1866
1867 private void dismissDialog(String dialogTag){
1868 Fragment frag = getSupportFragmentManager().findFragmentByTag(dialogTag);
1869 if (frag != null && frag instanceof DialogFragment) {
1870 DialogFragment dialog = (DialogFragment) frag;
1871 dialog.dismiss();
1872 }
1873 }
1874
1875
1876 /**
1877 * Implements callback methods for service binding.
1878 */
1879 private class OperationsServiceConnection implements ServiceConnection {
1880
1881 @Override
1882 public void onServiceConnected(ComponentName component, IBinder service) {
1883 if (component.equals(
1884 new ComponentName(AuthenticatorActivity.this, OperationsService.class)
1885 )) {
1886 mOperationsServiceBinder = (OperationsServiceBinder) service;
1887
1888 doOnResumeAndBound();
1889
1890 }
1891
1892 }
1893
1894 @Override
1895 public void onServiceDisconnected(ComponentName component) {
1896 if (component.equals(
1897 new ComponentName(AuthenticatorActivity.this, OperationsService.class)
1898 )) {
1899 Log_OC.e(TAG, "Operations service crashed");
1900 mOperationsServiceBinder = null;
1901 }
1902 }
1903
1904 }
1905
1906 /**
1907 * Create and show dialog for request authentication to the user
1908 * @param webView Web view to emebd into the authentication dialog.
1909 * @param handler Object responsible for catching and recovering HTTP authentication fails.
1910 */
1911 public void createAuthenticationDialog(WebView webView, HttpAuthHandler handler) {
1912
1913 // Show a dialog with the certificate info
1914 CredentialsDialogFragment dialog =
1915 CredentialsDialogFragment.newInstanceForCredentials(webView, handler);
1916 FragmentManager fm = getSupportFragmentManager();
1917 FragmentTransaction ft = fm.beginTransaction();
1918 ft.addToBackStack(null);
1919 dialog.setCancelable(false);
1920 dialog.show(ft, CREDENTIALS_DIALOG_TAG);
1921
1922 if (!mIsFirstAuthAttempt) {
1923 Toast.makeText(
1924 getApplicationContext(),
1925 getText(R.string.saml_authentication_wrong_pass),
1926 Toast.LENGTH_LONG
1927 ).show();
1928 } else {
1929 mIsFirstAuthAttempt = false;
1930 }
1931 }
1932
1933 /**
1934 * For retrieving the clicking on authentication cancel button
1935 */
1936 public void doNegativeAuthenticatioDialogClick(){
1937 mIsFirstAuthAttempt = true;
1938 }
1939
1940 }