AuthenticatorActivity.java 64 KB

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