AuthenticatorActivity.java 76 KB

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