AuthenticatorActivity.java 72 KB

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