AuthenticatorActivity.java 75 KB

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