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