AuthenticatorActivity.java 76 KB

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