AuthenticatorActivity.java 74 KB

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