AuthenticatorActivity.java 73 KB

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