AuthenticatorActivity.java 65 KB

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