AuthenticatorActivity.java 86 KB

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