AuthenticatorActivity.java 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198
  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. }
  477. @Override
  478. public void onTextChanged(CharSequence s, int start, int before, int count) {
  479. if (mAuthStatusIcon != 0) {
  480. Log_OC.d(TAG, "onTextChanged: hiding authentication status");
  481. mAuthStatusIcon = 0;
  482. mAuthStatusText = 0;
  483. showAuthStatus();
  484. }
  485. }
  486. };
  487. // TODO find out if this is really necessary, or if it can done in a different way
  488. findViewById(R.id.scroll).setOnTouchListener(new OnTouchListener() {
  489. @Override
  490. public boolean onTouch(View view, MotionEvent event) {
  491. if (event.getAction() == MotionEvent.ACTION_DOWN &&
  492. AccountTypeUtils
  493. .getAuthTokenTypeSamlSessionCookie(MainApp
  494. .getAccountType()).equals(mAuthTokenType) &&
  495. mHostUrlInput.hasFocus()) {
  496. checkOcServer();
  497. }
  498. return false;
  499. }
  500. });
  501. }
  502. }
  503. /**
  504. * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
  505. */
  506. private void initAuthorizationPreFragment(Bundle savedInstanceState) {
  507. /// step 0 - get UI elements in layout
  508. mOAuth2Check = (CheckBox) findViewById(R.id.oauth_onOff_check);
  509. mOAuthAuthEndpointText = (TextView) findViewById(R.id.oAuthEntryPoint_1);
  510. mOAuthTokenEndpointText = (TextView) findViewById(R.id.oAuthEntryPoint_2);
  511. mUsernameInput = (EditText) findViewById(R.id.account_username);
  512. mPasswordInput = (EditText) findViewById(R.id.account_password);
  513. mAuthStatusView = (TextView) findViewById(R.id.auth_status_text);
  514. /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
  515. String presetUserName = null;
  516. boolean isPasswordExposed = false;
  517. if (savedInstanceState == null) {
  518. if (mAccount != null) {
  519. presetUserName = com.owncloud.android.lib.common.accounts.AccountUtils.getUsernameForAccount(mAccount);
  520. }
  521. } else {
  522. isPasswordExposed = savedInstanceState.getBoolean(KEY_PASSWORD_EXPOSED, false);
  523. mAuthStatusText = savedInstanceState.getInt(KEY_AUTH_STATUS_TEXT);
  524. mAuthStatusIcon = savedInstanceState.getInt(KEY_AUTH_STATUS_ICON);
  525. mAuthToken = savedInstanceState.getString(KEY_AUTH_TOKEN);
  526. }
  527. /// step 2 - set properties of UI elements (text, visibility, enabled...)
  528. mOAuth2Check.setChecked(
  529. AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType())
  530. .equals(mAuthTokenType));
  531. if (presetUserName != null) {
  532. mUsernameInput.setText(presetUserName);
  533. }
  534. if (mAction != ACTION_CREATE) {
  535. mUsernameInput.setEnabled(false);
  536. mUsernameInput.setFocusable(false);
  537. }
  538. mPasswordInput.setText(""); // clean password to avoid social hacking
  539. if (isPasswordExposed) {
  540. showPassword();
  541. }
  542. updateAuthenticationPreFragmentVisibility();
  543. showAuthStatus();
  544. mOkButton.setEnabled(mServerIsValid);
  545. /// step 3 - bind listeners
  546. // bindings for password input field
  547. mPasswordInput.setOnFocusChangeListener(this);
  548. mPasswordInput.setImeOptions(EditorInfo.IME_ACTION_DONE);
  549. mPasswordInput.setOnEditorActionListener(this);
  550. mPasswordInput.setOnTouchListener(new RightDrawableOnTouchListener() {
  551. @Override
  552. public boolean onDrawableTouch(final MotionEvent event) {
  553. if (event.getAction() == MotionEvent.ACTION_UP) {
  554. AuthenticatorActivity.this.onViewPasswordClick();
  555. }
  556. return true;
  557. }
  558. });
  559. }
  560. /**
  561. * Changes the visibility of input elements depending on
  562. * the current authorization method.
  563. */
  564. private void updateAuthenticationPreFragmentVisibility() {
  565. if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
  566. equals(mAuthTokenType)) {
  567. // SAML-based web Single Sign On
  568. mOAuth2Check.setVisibility(View.GONE);
  569. mOAuthAuthEndpointText.setVisibility(View.GONE);
  570. mOAuthTokenEndpointText.setVisibility(View.GONE);
  571. mUsernameInput.setVisibility(View.GONE);
  572. mPasswordInput.setVisibility(View.GONE);
  573. } else {
  574. if (mAction == ACTION_CREATE &&
  575. AUTH_OPTIONAL.equals(getString(R.string.auth_method_oauth2))) {
  576. mOAuth2Check.setVisibility(View.VISIBLE);
  577. } else {
  578. mOAuth2Check.setVisibility(View.GONE);
  579. }
  580. if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).
  581. equals(mAuthTokenType)) {
  582. // OAuth 2 authorization
  583. mOAuthAuthEndpointText.setVisibility(View.VISIBLE);
  584. mOAuthTokenEndpointText.setVisibility(View.VISIBLE);
  585. mUsernameInput.setVisibility(View.GONE);
  586. mPasswordInput.setVisibility(View.GONE);
  587. } else {
  588. // basic HTTP authorization
  589. mOAuthAuthEndpointText.setVisibility(View.GONE);
  590. mOAuthTokenEndpointText.setVisibility(View.GONE);
  591. mUsernameInput.setVisibility(View.VISIBLE);
  592. mPasswordInput.setVisibility(View.VISIBLE);
  593. }
  594. }
  595. }
  596. /**
  597. * Saves relevant state before {@link #onPause()}
  598. *
  599. * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag,
  600. * intended to defer the processing of the redirection caught in
  601. * {@link #onNewIntent(Intent)} until {@link #onResume()}
  602. *
  603. * See {@link super#onSaveInstanceState(Bundle)}
  604. */
  605. @Override
  606. protected void onSaveInstanceState(Bundle outState) {
  607. //Log_OC.e(TAG, "onSaveInstanceState init" );
  608. super.onSaveInstanceState(outState);
  609. /// global state
  610. outState.putString(KEY_AUTH_TOKEN_TYPE, mAuthTokenType);
  611. outState.putLong(KEY_WAITING_FOR_OP_ID, mWaitingForOpId);
  612. if (!webViewLoginMethod) {
  613. /// Server PRE-fragment state
  614. outState.putInt(KEY_SERVER_STATUS_TEXT, mServerStatusText);
  615. outState.putInt(KEY_SERVER_STATUS_ICON, mServerStatusIcon);
  616. outState.putBoolean(KEY_SERVER_CHECKED, mServerIsChecked);
  617. outState.putBoolean(KEY_SERVER_VALID, mServerIsValid);
  618. /// Authentication PRE-fragment state
  619. outState.putBoolean(KEY_PASSWORD_EXPOSED, isPasswordVisible());
  620. outState.putInt(KEY_AUTH_STATUS_ICON, mAuthStatusIcon);
  621. outState.putInt(KEY_AUTH_STATUS_TEXT, mAuthStatusText);
  622. outState.putString(KEY_AUTH_TOKEN, mAuthToken);
  623. }
  624. outState.putBoolean(KEY_IS_SSL_CONN, mServerInfo.mIsSslConn);
  625. outState.putString(KEY_HOST_URL_TEXT, mServerInfo.mBaseUrl);
  626. if (mServerInfo.mVersion != null) {
  627. outState.putString(KEY_OC_VERSION, mServerInfo.mVersion.getVersion());
  628. }
  629. outState.putString(KEY_SERVER_AUTH_METHOD, mServerInfo.mAuthMethod.name());
  630. /// authentication
  631. outState.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG, mIsFirstAuthAttempt);
  632. /// AsyncTask (User and password)
  633. if (!webViewLoginMethod) {
  634. outState.putString(KEY_USERNAME, mUsernameInput.getText().toString().trim());
  635. outState.putString(KEY_PASSWORD, mPasswordInput.getText().toString());
  636. }
  637. if (mAsyncTask != null) {
  638. mAsyncTask.cancel(true);
  639. outState.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS, true);
  640. } else {
  641. outState.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS, false);
  642. }
  643. mAsyncTask = null;
  644. //Log_OC.e(TAG, "onSaveInstanceState end" );
  645. }
  646. @Override
  647. public void onRestoreInstanceState(Bundle savedInstanceState) {
  648. super.onRestoreInstanceState(savedInstanceState);
  649. mServerIsChecked = savedInstanceState.getBoolean(KEY_SERVER_CHECKED, false);
  650. // AsyncTask
  651. boolean inProgress = savedInstanceState.getBoolean(KEY_ASYNC_TASK_IN_PROGRESS);
  652. if (inProgress) {
  653. String username = savedInstanceState.getString(KEY_USERNAME);
  654. String password = savedInstanceState.getString(KEY_PASSWORD);
  655. OwnCloudCredentials credentials = null;
  656. if (BASIC_TOKEN_TYPE.equals(mAuthTokenType)) {
  657. credentials = OwnCloudCredentialsFactory.newBasicCredentials(username, password);
  658. } else if (OAUTH_TOKEN_TYPE.equals(mAuthTokenType)) {
  659. credentials = OwnCloudCredentialsFactory.newBearerCredentials(mAuthToken);
  660. }
  661. accessRootFolder(credentials);
  662. }
  663. }
  664. /**
  665. * The redirection triggered by the OAuth authentication server as response to the
  666. * GET AUTHORIZATION request is caught here.
  667. *
  668. * To make this possible, this activity needs to be qualified with android:launchMode =
  669. * "singleTask" in the AndroidManifest.xml file.
  670. */
  671. @Override
  672. protected void onNewIntent(Intent intent) {
  673. Log_OC.d(TAG, "onNewIntent()");
  674. Uri data = intent.getData();
  675. if (data != null && data.toString().startsWith(getString(R.string.oauth2_redirect_uri))) {
  676. mNewCapturedUriFromOAuth2Redirection = data;
  677. }
  678. }
  679. /**
  680. * The redirection triggered by the OAuth authentication server as response to the
  681. * GET AUTHORIZATION, and deferred in {@link #onNewIntent(Intent)}, is processed here.
  682. */
  683. @Override
  684. protected void onResume() {
  685. super.onResume();
  686. AnalyticsUtils.setCurrentScreenName(this, SCREEN_NAME, TAG);
  687. if (!webViewLoginMethod) {
  688. // bound here to avoid spurious changes triggered by Android on device rotations
  689. mHostUrlInput.setOnFocusChangeListener(this);
  690. mHostUrlInput.addTextChangedListener(mHostUrlInputWatcher);
  691. if (mNewCapturedUriFromOAuth2Redirection != null) {
  692. getOAuth2AccessTokenFromCapturedRedirection();
  693. }
  694. String dataString = getIntent().getDataString();
  695. if (dataString != null) {
  696. try {
  697. populateLoginFields(dataString);
  698. } catch (IllegalArgumentException e) {
  699. Toast.makeText(this, "Illegal login data URL used", Toast.LENGTH_SHORT).show();
  700. Log_OC.e(TAG, "Illegal login data URL used, no Login pre-fill!", e);
  701. }
  702. }
  703. }
  704. // bind to Operations Service
  705. mOperationsServiceConnection = new OperationsServiceConnection();
  706. if (!bindService(new Intent(this, OperationsService.class),
  707. mOperationsServiceConnection,
  708. Context.BIND_AUTO_CREATE)) {
  709. Toast.makeText(this,
  710. R.string.error_cant_bind_to_operations_service,
  711. Toast.LENGTH_LONG)
  712. .show();
  713. finish();
  714. }
  715. if (mOperationsServiceBinder != null) {
  716. doOnResumeAndBound();
  717. }
  718. }
  719. @Override
  720. protected void onPause() {
  721. if (mOperationsServiceBinder != null) {
  722. mOperationsServiceBinder.removeOperationListener(this);
  723. }
  724. if (!webViewLoginMethod) {
  725. mHostUrlInput.removeTextChangedListener(mHostUrlInputWatcher);
  726. mHostUrlInput.setOnFocusChangeListener(null);
  727. }
  728. super.onPause();
  729. }
  730. @Override
  731. protected void onDestroy() {
  732. mHostUrlInputWatcher = null;
  733. if (mOperationsServiceConnection != null) {
  734. unbindService(mOperationsServiceConnection);
  735. mOperationsServiceBinder = null;
  736. }
  737. if (webViewLoginMethod) {
  738. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
  739. }
  740. super.onDestroy();
  741. }
  742. /**
  743. * Parses the redirection with the response to the GET AUTHORIZATION request to the
  744. * oAuth server and requests for the access token (GET ACCESS TOKEN)
  745. */
  746. private void getOAuth2AccessTokenFromCapturedRedirection() {
  747. /// Parse data from OAuth redirection
  748. String queryParameters = mNewCapturedUriFromOAuth2Redirection.getQuery();
  749. mNewCapturedUriFromOAuth2Redirection = null;
  750. /// Showing the dialog with instructions for the user.
  751. IndeterminateProgressDialog dialog =
  752. IndeterminateProgressDialog.newInstance(R.string.auth_getting_authorization, true);
  753. dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);
  754. /// GET ACCESS TOKEN to the oAuth server
  755. Intent getServerInfoIntent = new Intent();
  756. getServerInfoIntent.setAction(OperationsService.ACTION_OAUTH2_GET_ACCESS_TOKEN);
  757. getServerInfoIntent.putExtra(
  758. OperationsService.EXTRA_SERVER_URL,
  759. mOAuthTokenEndpointText.getText().toString().trim());
  760. getServerInfoIntent.putExtra(
  761. OperationsService.EXTRA_OAUTH2_QUERY_PARAMETERS,
  762. queryParameters);
  763. if (mOperationsServiceBinder != null) {
  764. //Log_OC.e(TAG, "getting access token..." );
  765. mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getServerInfoIntent);
  766. }
  767. }
  768. /**
  769. * Handles the change of focus on the text inputs for the server URL and the password
  770. */
  771. public void onFocusChange(View view, boolean hasFocus) {
  772. if (view.getId() == R.id.hostUrlInput) {
  773. if (!hasFocus) {
  774. onUrlInputFocusLost();
  775. } else {
  776. showRefreshButton(false);
  777. }
  778. } else if (view.getId() == R.id.account_password) {
  779. onPasswordFocusChanged(hasFocus);
  780. }
  781. }
  782. /**
  783. * Handles changes in focus on the text input for the server URL.
  784. *
  785. * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
  786. * other field. The operation to check the existence of the server in the entered URL is
  787. * started.
  788. *
  789. * When hasFocus: user 'comes back' to write again the server URL.
  790. */
  791. private void onUrlInputFocusLost() {
  792. if (!mServerInfo.mBaseUrl.equals(
  793. normalizeUrl(mHostUrlInput.getText().toString(), mServerInfo.mIsSslConn))) {
  794. // check server again only if the user changed something in the field
  795. checkOcServer();
  796. } else {
  797. mOkButton.setEnabled(mServerIsValid);
  798. showRefreshButton(!mServerIsValid);
  799. }
  800. }
  801. private void checkOcServer() {
  802. String uri;
  803. if (mHostUrlInput != null) {
  804. uri = mHostUrlInput.getText().toString().trim();
  805. mOkButton.setEnabled(false);
  806. showRefreshButton(false);
  807. } else {
  808. uri = mServerInfo.mBaseUrl;
  809. }
  810. mServerIsValid = false;
  811. mServerIsChecked = false;
  812. mServerInfo = new GetServerInfoOperation.ServerInfo();
  813. if (uri.length() != 0) {
  814. if (mHostUrlInput != null) {
  815. uri = stripIndexPhpOrAppsFiles(uri, mHostUrlInput);
  816. }
  817. // Handle internationalized domain names
  818. try {
  819. uri = DisplayUtils.convertIdn(uri, true);
  820. } catch (IllegalArgumentException ex) {
  821. // Let Owncloud library check the error of the malformed URI
  822. }
  823. if (mHostUrlInput != null) {
  824. mServerStatusText = R.string.auth_testing_connection;
  825. mServerStatusIcon = R.drawable.progress_small;
  826. showServerStatus();
  827. }
  828. Intent getServerInfoIntent = new Intent();
  829. getServerInfoIntent.setAction(OperationsService.ACTION_GET_SERVER_INFO);
  830. getServerInfoIntent.putExtra(
  831. OperationsService.EXTRA_SERVER_URL,
  832. normalizeUrlSuffix(uri)
  833. );
  834. if (mOperationsServiceBinder != null) {
  835. mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getServerInfoIntent);
  836. } else {
  837. Log_OC.e(TAG, "Server check tried with OperationService unbound!");
  838. }
  839. } else {
  840. mServerStatusText = 0;
  841. mServerStatusIcon = 0;
  842. if (!webViewLoginMethod) {
  843. showServerStatus();
  844. }
  845. }
  846. }
  847. /**
  848. * Handles changes in focus on the text input for the password (basic authorization).
  849. *
  850. * When (hasFocus), the button to toggle password visibility is shown.
  851. *
  852. * When (!hasFocus), the button is made invisible and the password is hidden.
  853. *
  854. * @param hasFocus 'True' if focus is received, 'false' if is lost
  855. */
  856. private void onPasswordFocusChanged(boolean hasFocus) {
  857. if (hasFocus) {
  858. showViewPasswordButton();
  859. } else {
  860. hidePassword();
  861. hidePasswordButton();
  862. }
  863. }
  864. private void showViewPasswordButton() {
  865. int drawable = R.drawable.ic_view;
  866. if (isPasswordVisible()) {
  867. drawable = R.drawable.ic_hide;
  868. }
  869. mPasswordInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable, 0);
  870. }
  871. private boolean isPasswordVisible() {
  872. return ((mPasswordInput.getInputType() & InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) ==
  873. InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
  874. }
  875. private void hidePasswordButton() {
  876. mPasswordInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
  877. }
  878. private void showPassword() {
  879. mPasswordInput.setInputType(
  880. InputType.TYPE_CLASS_TEXT |
  881. InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD |
  882. InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
  883. );
  884. showViewPasswordButton();
  885. }
  886. private void hidePassword() {
  887. mPasswordInput.setInputType(
  888. InputType.TYPE_CLASS_TEXT |
  889. InputType.TYPE_TEXT_VARIATION_PASSWORD |
  890. InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
  891. );
  892. showViewPasswordButton();
  893. }
  894. /**
  895. * Checks the credentials of the user in the root of the ownCloud server
  896. * before creating a new local account.
  897. *
  898. * For basic authorization, a check of existence of the root folder is
  899. * performed.
  900. *
  901. * For OAuth, starts the flow to get an access token; the credentials test
  902. * is postponed until it is available.
  903. *
  904. * IMPORTANT ENTRY POINT 4
  905. */
  906. public void onOkClick() {
  907. // this check should be unnecessary
  908. if (mServerInfo.mVersion == null ||
  909. !mServerInfo.mVersion.isVersionValid() ||
  910. mServerInfo.mBaseUrl == null ||
  911. mServerInfo.mBaseUrl.length() == 0) {
  912. mServerStatusIcon = R.drawable.ic_alert;
  913. mServerStatusText = R.string.auth_wtf_reenter_URL;
  914. showServerStatus();
  915. mOkButton.setEnabled(false);
  916. return;
  917. }
  918. if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).
  919. equals(mAuthTokenType)) {
  920. startOauthorization();
  921. } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
  922. equals(mAuthTokenType)) {
  923. startSamlBasedFederatedSingleSignOnAuthorization();
  924. } else {
  925. checkBasicAuthorization(null, null);
  926. }
  927. }
  928. /**
  929. * Tests the credentials entered by the user performing a check of existence on
  930. * the root folder of the ownCloud server.
  931. */
  932. private void checkBasicAuthorization(@Nullable String webViewUsername, @Nullable String webViewPassword) {
  933. /// get basic credentials entered by user
  934. String username;
  935. String password;
  936. if (!webViewLoginMethod) {
  937. username = mUsernameInput.getText().toString().trim();
  938. password = mPasswordInput.getText().toString();
  939. } else {
  940. username = webViewUsername;
  941. password = webViewPassword;
  942. }
  943. /// be gentle with the user
  944. IndeterminateProgressDialog dialog =
  945. IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);
  946. dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);
  947. /// validate credentials accessing the root folder
  948. OwnCloudCredentials credentials = OwnCloudCredentialsFactory.newBasicCredentials(username,
  949. password);
  950. accessRootFolder(credentials);
  951. }
  952. private void accessRootFolder(OwnCloudCredentials credentials) {
  953. mAsyncTask = new AuthenticatorAsyncTask(this);
  954. Object[] params = {mServerInfo.mBaseUrl, credentials};
  955. mAsyncTask.execute(params);
  956. }
  957. /**
  958. * Starts the OAuth 'grant type' flow to get an access token, with
  959. * a GET AUTHORIZATION request to the BUILT-IN authorization server.
  960. */
  961. private void startOauthorization() {
  962. // be gentle with the user
  963. mAuthStatusIcon = R.drawable.progress_small;
  964. mAuthStatusText = R.string.oauth_login_connection;
  965. showAuthStatus();
  966. // GET AUTHORIZATION request
  967. Uri uri = Uri.parse(mOAuthAuthEndpointText.getText().toString().trim());
  968. Uri.Builder uriBuilder = uri.buildUpon();
  969. uriBuilder.appendQueryParameter(
  970. OAuth2Constants.KEY_RESPONSE_TYPE, getString(R.string.oauth2_response_type)
  971. );
  972. uriBuilder.appendQueryParameter(
  973. OAuth2Constants.KEY_REDIRECT_URI, getString(R.string.oauth2_redirect_uri)
  974. );
  975. uriBuilder.appendQueryParameter(
  976. OAuth2Constants.KEY_CLIENT_ID, getString(R.string.oauth2_client_id)
  977. );
  978. uriBuilder.appendQueryParameter(
  979. OAuth2Constants.KEY_SCOPE, getString(R.string.oauth2_scope)
  980. );
  981. uri = uriBuilder.build();
  982. Log_OC.d(TAG, "Starting browser to view " + uri.toString());
  983. Intent i = new Intent(Intent.ACTION_VIEW, uri);
  984. startActivity(i);
  985. }
  986. /**
  987. * Starts the Web Single Sign On flow to get access to the root folder
  988. * in the server.
  989. */
  990. private void startSamlBasedFederatedSingleSignOnAuthorization() {
  991. /// be gentle with the user
  992. mAuthStatusIcon = R.drawable.progress_small;
  993. mAuthStatusText = R.string.auth_connecting_auth_server;
  994. showAuthStatus();
  995. /// Show SAML-based SSO web dialog
  996. String targetUrl = mServerInfo.mBaseUrl
  997. + AccountUtils.getWebdavPath(mServerInfo.mVersion, mAuthTokenType);
  998. SamlWebViewDialog dialog = SamlWebViewDialog.newInstance(targetUrl, targetUrl);
  999. dialog.show(getSupportFragmentManager(), SAML_DIALOG_TAG);
  1000. }
  1001. /**
  1002. * Callback method invoked when a RemoteOperation executed by this Activity finishes.
  1003. *
  1004. * Dispatches the operation flow to the right method.
  1005. */
  1006. @Override
  1007. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  1008. if (operation instanceof GetServerInfoOperation) {
  1009. if (operation.hashCode() == mWaitingForOpId) {
  1010. onGetServerInfoFinish(result);
  1011. } // else nothing ; only the last check operation is considered;
  1012. // multiple can be started if the user amends a URL quickly
  1013. } else if (operation instanceof OAuth2GetAccessToken) {
  1014. onGetOAuthAccessTokenFinish(result);
  1015. } else if (operation instanceof GetRemoteUserInfoOperation) {
  1016. onGetUserNameFinish(result);
  1017. }
  1018. }
  1019. private void onGetUserNameFinish(RemoteOperationResult result) {
  1020. mWaitingForOpId = Long.MAX_VALUE;
  1021. if (result.isSuccess()) {
  1022. boolean success = false;
  1023. String username;
  1024. if (result.getData().get(0) instanceof UserInfo) {
  1025. username = ((UserInfo) result.getData().get(0)).getDisplayName();
  1026. } else {
  1027. username = (String) result.getData().get(0);
  1028. }
  1029. if (mAction == ACTION_CREATE) {
  1030. if (!webViewLoginMethod) {
  1031. mUsernameInput.setText(username);
  1032. }
  1033. success = createAccount(result);
  1034. } else {
  1035. if (!webViewLoginMethod && !mUsernameInput.getText().toString().trim().equals(username)) {
  1036. // fail - not a new account, but an existing one; disallow
  1037. result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_THE_SAME);
  1038. mAuthToken = "";
  1039. updateAuthStatusIconAndText(result);
  1040. showAuthStatus();
  1041. Log_OC.d(TAG, result.getLogMessage());
  1042. } else {
  1043. try {
  1044. updateAccountAuthentication();
  1045. success = true;
  1046. } catch (AccountNotFoundException e) {
  1047. Log_OC.e(TAG, "Account " + mAccount + " was removed!", e);
  1048. Toast.makeText(this, R.string.auth_account_does_not_exist,
  1049. Toast.LENGTH_SHORT).show();
  1050. finish();
  1051. }
  1052. }
  1053. }
  1054. if (success) {
  1055. finish();
  1056. }
  1057. } else {
  1058. if (!webViewLoginMethod) {
  1059. int statusText = result.getCode() == ResultCode.MAINTENANCE_MODE ? R.string.maintenance_mode : R.string.auth_fail_get_user_name;
  1060. updateStatusIconFailUserName(statusText);
  1061. showAuthStatus();
  1062. }
  1063. Log_OC.e(TAG, "Access to user name failed: " + result.getLogMessage());
  1064. }
  1065. }
  1066. /**
  1067. * Processes the result of the server check performed when the user finishes the enter of the
  1068. * server URL.
  1069. *
  1070. * @param result Result of the check.
  1071. */
  1072. private void onGetServerInfoFinish(RemoteOperationResult result) {
  1073. /// update activity state
  1074. mServerIsChecked = true;
  1075. mWaitingForOpId = Long.MAX_VALUE;
  1076. // update server status, but don't show it yet
  1077. if (!webViewLoginMethod) {
  1078. updateServerStatusIconAndText(result);
  1079. }
  1080. if (result.isSuccess()) {
  1081. /// SUCCESS means:
  1082. // 1. connection succeeded, and we know if it's SSL or not
  1083. // 2. server is installed
  1084. // 3. we got the server version
  1085. // 4. we got the authentication method required by the server
  1086. mServerInfo = (GetServerInfoOperation.ServerInfo) (result.getData().get(0));
  1087. if (webViewLoginMethod) {
  1088. checkBasicAuthorization(webViewUser, webViewPassword);
  1089. }
  1090. if (!authSupported(mServerInfo.mAuthMethod)) {
  1091. if (!webViewLoginMethod) {
  1092. // overrides updateServerStatusIconAndText()
  1093. updateServerStatusIconNoRegularAuth();
  1094. }
  1095. mServerIsValid = false;
  1096. } else {
  1097. mServerIsValid = true;
  1098. }
  1099. } else {
  1100. mServerIsValid = false;
  1101. }
  1102. // refresh UI
  1103. if (!webViewLoginMethod) {
  1104. showRefreshButton(!mServerIsValid);
  1105. showServerStatus();
  1106. mOkButton.setEnabled(mServerIsValid);
  1107. }
  1108. /// very special case (TODO: move to a common place for all the remote operations)
  1109. if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
  1110. showUntrustedCertDialog(result);
  1111. }
  1112. }
  1113. private boolean authSupported(AuthenticationMethod authMethod) {
  1114. return ((BASIC_TOKEN_TYPE.equals(mAuthTokenType) &&
  1115. AuthenticationMethod.BASIC_HTTP_AUTH.equals(authMethod)) ||
  1116. (OAUTH_TOKEN_TYPE.equals(mAuthTokenType) &&
  1117. AuthenticationMethod.BEARER_TOKEN.equals(authMethod)) ||
  1118. (SAML_TOKEN_TYPE.equals(mAuthTokenType) &&
  1119. AuthenticationMethod.SAML_WEB_SSO.equals(authMethod))
  1120. );
  1121. }
  1122. // TODO remove, if possible
  1123. private String normalizeUrl(String url, boolean sslWhenUnprefixed) {
  1124. if (url != null && url.length() > 0) {
  1125. url = url.trim();
  1126. if (!url.toLowerCase().startsWith(HTTP_PROTOCOL) &&
  1127. !url.toLowerCase().startsWith(HTTP_PROTOCOL)) {
  1128. if (sslWhenUnprefixed) {
  1129. url = HTTPS_PROTOCOL + url;
  1130. } else {
  1131. url = HTTP_PROTOCOL + url;
  1132. }
  1133. }
  1134. url = normalizeUrlSuffix(url);
  1135. }
  1136. return (url != null ? url : "");
  1137. }
  1138. private String normalizeUrlSuffix(String url) {
  1139. if (url.endsWith("/")) {
  1140. url = url.substring(0, url.length() - 1);
  1141. }
  1142. url = trimUrlWebdav(url);
  1143. return url;
  1144. }
  1145. private String stripIndexPhpOrAppsFiles(String url, EditText mHostUrlInput) {
  1146. if (url.endsWith("/index.php")) {
  1147. url = url.substring(0, url.lastIndexOf("/index.php"));
  1148. mHostUrlInput.setText(url);
  1149. } else if (url.contains("/index.php/apps/")) {
  1150. url = url.substring(0, url.lastIndexOf("/index.php/apps/"));
  1151. mHostUrlInput.setText(url);
  1152. }
  1153. return url;
  1154. }
  1155. // TODO remove, if possible
  1156. private String trimUrlWebdav(String url) {
  1157. if (url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0_AND_LATER)) {
  1158. url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0_AND_LATER.length());
  1159. }
  1160. return url;
  1161. }
  1162. /**
  1163. * Chooses the right icon and text to show to the user for the received operation result.
  1164. *
  1165. * @param result Result of a remote operation performed in this activity
  1166. */
  1167. private void updateServerStatusIconAndText(RemoteOperationResult result) {
  1168. mServerStatusIcon = R.drawable.ic_alert; // the most common case in the switch below
  1169. switch (result.getCode()) {
  1170. case OK_SSL:
  1171. mServerStatusIcon = R.drawable.ic_lock_white;
  1172. mServerStatusText = R.string.auth_secure_connection;
  1173. break;
  1174. case OK_NO_SSL:
  1175. case OK:
  1176. if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith(HTTP_PROTOCOL)) {
  1177. mServerStatusText = R.string.auth_connection_established;
  1178. mServerStatusIcon = R.drawable.ic_ok;
  1179. } else {
  1180. mServerStatusText = R.string.auth_nossl_plain_ok_title;
  1181. mServerStatusIcon = R.drawable.ic_lock_open_white;
  1182. }
  1183. break;
  1184. case NO_NETWORK_CONNECTION:
  1185. mServerStatusIcon = R.drawable.no_network;
  1186. mServerStatusText = R.string.auth_no_net_conn_title;
  1187. break;
  1188. case SSL_RECOVERABLE_PEER_UNVERIFIED:
  1189. mServerStatusText = R.string.auth_ssl_unverified_server_title;
  1190. break;
  1191. case BAD_OC_VERSION:
  1192. mServerStatusText = R.string.auth_bad_oc_version_title;
  1193. break;
  1194. case WRONG_CONNECTION:
  1195. mServerStatusText = R.string.auth_wrong_connection_title;
  1196. break;
  1197. case TIMEOUT:
  1198. mServerStatusText = R.string.auth_timeout_title;
  1199. break;
  1200. case INCORRECT_ADDRESS:
  1201. mServerStatusText = R.string.auth_incorrect_address_title;
  1202. break;
  1203. case SSL_ERROR:
  1204. mServerStatusText = R.string.auth_ssl_general_error_title;
  1205. break;
  1206. case UNAUTHORIZED:
  1207. mServerStatusText = R.string.auth_unauthorized;
  1208. break;
  1209. case HOST_NOT_AVAILABLE:
  1210. mServerStatusText = R.string.auth_unknown_host_title;
  1211. break;
  1212. case INSTANCE_NOT_CONFIGURED:
  1213. mServerStatusText = R.string.auth_not_configured_title;
  1214. break;
  1215. case FILE_NOT_FOUND:
  1216. mServerStatusText = R.string.auth_incorrect_path_title;
  1217. break;
  1218. case OAUTH2_ERROR:
  1219. mServerStatusText = R.string.auth_oauth_error;
  1220. break;
  1221. case OAUTH2_ERROR_ACCESS_DENIED:
  1222. mServerStatusText = R.string.auth_oauth_error_access_denied;
  1223. break;
  1224. case UNHANDLED_HTTP_CODE:
  1225. case UNKNOWN_ERROR:
  1226. mServerStatusText = R.string.auth_unknown_error_title;
  1227. break;
  1228. case OK_REDIRECT_TO_NON_SECURE_CONNECTION:
  1229. mServerStatusIcon = R.drawable.ic_lock_open_white;
  1230. mServerStatusText = R.string.auth_redirect_non_secure_connection_title;
  1231. break;
  1232. case MAINTENANCE_MODE:
  1233. mServerStatusText = R.string.maintenance_mode;
  1234. break;
  1235. default:
  1236. mServerStatusText = 0;
  1237. mServerStatusIcon = 0;
  1238. }
  1239. }
  1240. /**
  1241. * Chooses the right icon and text to show to the user for the received operation result.
  1242. *
  1243. * @param result Result of a remote operation performed in this activity
  1244. */
  1245. private void updateAuthStatusIconAndText(RemoteOperationResult result) {
  1246. mAuthStatusIcon = R.drawable.ic_alert; // the most common case in the switch below
  1247. switch (result.getCode()) {
  1248. case OK_SSL:
  1249. mAuthStatusIcon = R.drawable.ic_lock_white;
  1250. mAuthStatusText = R.string.auth_secure_connection;
  1251. break;
  1252. case OK_NO_SSL:
  1253. case OK:
  1254. if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith(HTTP_PROTOCOL)) {
  1255. mAuthStatusText = R.string.auth_connection_established;
  1256. mAuthStatusIcon = R.drawable.ic_ok;
  1257. } else {
  1258. mAuthStatusText = R.string.auth_nossl_plain_ok_title;
  1259. mAuthStatusIcon = R.drawable.ic_lock_open_white;
  1260. }
  1261. break;
  1262. case NO_NETWORK_CONNECTION:
  1263. mAuthStatusIcon = R.drawable.no_network;
  1264. mAuthStatusText = R.string.auth_no_net_conn_title;
  1265. break;
  1266. case SSL_RECOVERABLE_PEER_UNVERIFIED:
  1267. mAuthStatusText = R.string.auth_ssl_unverified_server_title;
  1268. break;
  1269. case BAD_OC_VERSION:
  1270. mAuthStatusText = R.string.auth_bad_oc_version_title;
  1271. break;
  1272. case WRONG_CONNECTION:
  1273. mAuthStatusText = R.string.auth_wrong_connection_title;
  1274. break;
  1275. case TIMEOUT:
  1276. mAuthStatusText = R.string.auth_timeout_title;
  1277. break;
  1278. case INCORRECT_ADDRESS:
  1279. mAuthStatusText = R.string.auth_incorrect_address_title;
  1280. break;
  1281. case SSL_ERROR:
  1282. mAuthStatusText = R.string.auth_ssl_general_error_title;
  1283. break;
  1284. case UNAUTHORIZED:
  1285. mAuthStatusText = R.string.auth_unauthorized;
  1286. break;
  1287. case HOST_NOT_AVAILABLE:
  1288. mAuthStatusText = R.string.auth_unknown_host_title;
  1289. break;
  1290. case INSTANCE_NOT_CONFIGURED:
  1291. mAuthStatusText = R.string.auth_not_configured_title;
  1292. break;
  1293. case FILE_NOT_FOUND:
  1294. mAuthStatusText = R.string.auth_incorrect_path_title;
  1295. break;
  1296. case OAUTH2_ERROR:
  1297. mAuthStatusText = R.string.auth_oauth_error;
  1298. break;
  1299. case OAUTH2_ERROR_ACCESS_DENIED:
  1300. mAuthStatusText = R.string.auth_oauth_error_access_denied;
  1301. break;
  1302. case ACCOUNT_NOT_NEW:
  1303. mAuthStatusText = R.string.auth_account_not_new;
  1304. break;
  1305. case ACCOUNT_NOT_THE_SAME:
  1306. mAuthStatusText = R.string.auth_account_not_the_same;
  1307. break;
  1308. case UNHANDLED_HTTP_CODE:
  1309. case UNKNOWN_ERROR:
  1310. mAuthStatusText = R.string.auth_unknown_error_title;
  1311. break;
  1312. default:
  1313. mAuthStatusText = 0;
  1314. mAuthStatusIcon = 0;
  1315. }
  1316. }
  1317. private void updateStatusIconFailUserName(int statusText) {
  1318. mAuthStatusIcon = R.drawable.ic_alert;
  1319. mAuthStatusText = statusText;
  1320. }
  1321. private void updateStatusIconFailUserName(int failedStatusText){
  1322. mAuthStatusIcon = R.drawable.ic_alert;
  1323. mAuthStatusText = failedStatusText;
  1324. }
  1325. private void updateFailedAuthStatusIconAndText(int failedStatusText){
  1326. mAuthStatusIcon = R.drawable.ic_alert;
  1327. mAuthStatusText = statusText;
  1328. }
  1329. private void updateServerStatusIconNoRegularAuth() {
  1330. mServerStatusIcon = R.drawable.ic_alert;
  1331. mServerStatusText = R.string.auth_can_not_auth_against_server;
  1332. }
  1333. /**
  1334. * Processes the result of the request for and access token send
  1335. * to an OAuth authorization server.
  1336. *
  1337. * @param result Result of the operation.
  1338. */
  1339. private void onGetOAuthAccessTokenFinish(RemoteOperationResult result) {
  1340. mWaitingForOpId = Long.MAX_VALUE;
  1341. dismissDialog(WAIT_DIALOG_TAG);
  1342. if (result.isSuccess()) {
  1343. /// be gentle with the user
  1344. IndeterminateProgressDialog dialog =
  1345. IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);
  1346. dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);
  1347. /// time to test the retrieved access token on the ownCloud server
  1348. @SuppressWarnings("unchecked")
  1349. Map<String, String> tokens = (Map<String, String>) (result.getData().get(0));
  1350. mAuthToken = tokens.get(OAuth2Constants.KEY_ACCESS_TOKEN);
  1351. Log_OC.d(TAG, "Got ACCESS TOKEN: " + mAuthToken);
  1352. /// validate token accessing to root folder / getting session
  1353. OwnCloudCredentials credentials = OwnCloudCredentialsFactory.newBearerCredentials(
  1354. mAuthToken);
  1355. accessRootFolder(credentials);
  1356. } else {
  1357. updateAuthStatusIconAndText(result);
  1358. showAuthStatus();
  1359. Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
  1360. }
  1361. }
  1362. /**
  1363. * Processes the result of the access check performed to try the user credentials.
  1364. *
  1365. * Creates a new account through the AccountManager.
  1366. *
  1367. * @param result Result of the operation.
  1368. */
  1369. @Override
  1370. public void onAuthenticatorTaskCallback(RemoteOperationResult result) {
  1371. mWaitingForOpId = Long.MAX_VALUE;
  1372. dismissDialog(WAIT_DIALOG_TAG);
  1373. mAsyncTask = null;
  1374. if (result.isSuccess()) {
  1375. Log_OC.d(TAG, "Successful access - time to save the account");
  1376. boolean success = false;
  1377. if (mAction == ACTION_CREATE) {
  1378. success = createAccount(result);
  1379. } else {
  1380. try {
  1381. updateAccountAuthentication();
  1382. success = true;
  1383. } catch (AccountNotFoundException e) {
  1384. Log_OC.e(TAG, "Account " + mAccount + " was removed!", e);
  1385. Toast.makeText(this, R.string.auth_account_does_not_exist,
  1386. Toast.LENGTH_SHORT).show();
  1387. finish();
  1388. }
  1389. }
  1390. if (success) {
  1391. finish();
  1392. }
  1393. } else if (result.isServerFail() || result.isException()) {
  1394. /// server errors or exceptions in authorization take to requiring a new check of
  1395. /// the server
  1396. mServerIsChecked = true;
  1397. mServerIsValid = false;
  1398. mServerInfo = new GetServerInfoOperation.ServerInfo();
  1399. // update status icon and text
  1400. updateServerStatusIconAndText(result);
  1401. showServerStatus();
  1402. mAuthStatusIcon = 0;
  1403. mAuthStatusText = 0;
  1404. if (!webViewLoginMethod) {
  1405. showAuthStatus();
  1406. // update input controls state
  1407. showRefreshButton(true);
  1408. mOkButton.setEnabled(false);
  1409. }
  1410. // very special case (TODO: move to a common place for all the remote operations)
  1411. if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
  1412. showUntrustedCertDialog(result);
  1413. }
  1414. } else { // authorization fail due to client side - probably wrong credentials
  1415. if (!webViewLoginMethod) {
  1416. updateAuthStatusIconAndText(result);
  1417. showAuthStatus();
  1418. }
  1419. Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
  1420. }
  1421. }
  1422. /**
  1423. * Updates the authentication token.
  1424. *
  1425. * Sets the proper response so that the AccountAuthenticator that started this activity
  1426. * saves a new authorization token for mAccount.
  1427. *
  1428. * Kills the session kept by OwnCloudClientManager so that a new one will created with
  1429. * the new credentials when needed.
  1430. */
  1431. private void updateAccountAuthentication() throws AccountNotFoundException {
  1432. Bundle response = new Bundle();
  1433. response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
  1434. response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);
  1435. if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).
  1436. equals(mAuthTokenType)) {
  1437. response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
  1438. // the next line is necessary, notifications are calling directly to the
  1439. // AuthenticatorActivity to update, without AccountManager intervention
  1440. mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
  1441. } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
  1442. equals(mAuthTokenType)) {
  1443. response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
  1444. // the next line is necessary; by now, notifications are calling directly to the
  1445. // AuthenticatorActivity to update, without AccountManager intervention
  1446. mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
  1447. } else {
  1448. if (!webViewLoginMethod) {
  1449. response.putString(AccountManager.KEY_AUTHTOKEN, mPasswordInput.getText().toString());
  1450. mAccountMgr.setPassword(mAccount, mPasswordInput.getText().toString());
  1451. } else {
  1452. response.putString(AccountManager.KEY_AUTHTOKEN, webViewPassword);
  1453. mAccountMgr.setPassword(mAccount, webViewPassword);
  1454. }
  1455. }
  1456. // remove managed clients for this account to enforce creation with fresh credentials
  1457. OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount, this);
  1458. OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(ocAccount);
  1459. setAccountAuthenticatorResult(response);
  1460. final Intent intent = new Intent();
  1461. intent.putExtras(response);
  1462. setResult(RESULT_OK, intent);
  1463. }
  1464. /**
  1465. * Creates a new account through the Account Authenticator that started this activity.
  1466. *
  1467. * This makes the account permanent.
  1468. *
  1469. * TODO Decide how to name the OAuth accounts
  1470. */
  1471. @SuppressFBWarnings("DMI")
  1472. private boolean createAccount(RemoteOperationResult authResult) {
  1473. /// create and save new ownCloud account
  1474. boolean isOAuth = AccountTypeUtils.
  1475. getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType);
  1476. boolean isSaml = AccountTypeUtils.
  1477. getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType);
  1478. String lastPermanentLocation = authResult.getLastPermanentLocation();
  1479. if (lastPermanentLocation != null) {
  1480. mServerInfo.mBaseUrl = AccountUtils.trimWebdavSuffix(lastPermanentLocation);
  1481. }
  1482. Uri uri = Uri.parse(mServerInfo.mBaseUrl);
  1483. String username;
  1484. if (!webViewLoginMethod) {
  1485. username = mUsernameInput.getText().toString().trim();
  1486. } else {
  1487. username = webViewUser;
  1488. }
  1489. if (isOAuth) {
  1490. username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();
  1491. }
  1492. String accountName = com.owncloud.android.lib.common.accounts.AccountUtils.
  1493. buildAccountName(uri, username);
  1494. Account newAccount = new Account(accountName, MainApp.getAccountType());
  1495. if (AccountUtils.exists(newAccount, getApplicationContext())) {
  1496. // fail - not a new account, but an existing one; disallow
  1497. RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW);
  1498. if (!webViewLoginMethod) {
  1499. updateAuthStatusIconAndText(result);
  1500. showAuthStatus();
  1501. }
  1502. Log_OC.d(TAG, result.getLogMessage());
  1503. return false;
  1504. } else {
  1505. mAccount = newAccount;
  1506. if (isOAuth || isSaml) {
  1507. // with external authorizations, the password is never input in the app
  1508. mAccountMgr.addAccountExplicitly(mAccount, "", null);
  1509. } else {
  1510. if (!webViewLoginMethod) {
  1511. mAccountMgr.addAccountExplicitly(
  1512. mAccount, mPasswordInput.getText().toString(), null
  1513. );
  1514. } else {
  1515. mAccountMgr.addAccountExplicitly(
  1516. mAccount, webViewPassword, null
  1517. );
  1518. }
  1519. }
  1520. // include account version with the new account
  1521. mAccountMgr.setUserData(
  1522. mAccount,
  1523. Constants.KEY_OC_ACCOUNT_VERSION,
  1524. Integer.toString(AccountUtils.ACCOUNT_VERSION)
  1525. );
  1526. /// add the new account as default in preferences, if there is none already
  1527. Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
  1528. if (defaultAccount == null) {
  1529. SharedPreferences.Editor editor = PreferenceManager
  1530. .getDefaultSharedPreferences(this).edit();
  1531. editor.putString("select_oc_account", accountName);
  1532. editor.commit();
  1533. }
  1534. /// prepare result to return to the Authenticator
  1535. // TODO check again what the Authenticator makes with it; probably has the same
  1536. // effect as addAccountExplicitly, but it's not well done
  1537. final Intent intent = new Intent();
  1538. intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, MainApp.getAccountType());
  1539. intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
  1540. intent.putExtra(AccountManager.KEY_USERDATA, username);
  1541. if (isOAuth || isSaml) {
  1542. mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
  1543. }
  1544. /// add user data to the new account; TODO probably can be done in the last parameter
  1545. // addAccountExplicitly, or in KEY_USERDATA
  1546. mAccountMgr.setUserData(
  1547. mAccount, Constants.KEY_OC_VERSION, mServerInfo.mVersion.getVersion()
  1548. );
  1549. mAccountMgr.setUserData(
  1550. mAccount, Constants.KEY_OC_BASE_URL, mServerInfo.mBaseUrl
  1551. );
  1552. if (authResult.getData() != null) {
  1553. try {
  1554. UserInfo userInfo = (UserInfo) authResult.getData().get(0);
  1555. mAccountMgr.setUserData(
  1556. mAccount, Constants.KEY_DISPLAY_NAME, userInfo.getDisplayName()
  1557. );
  1558. } catch (ClassCastException c) {
  1559. Log_OC.w(TAG, "Couldn't get display name for " + username);
  1560. }
  1561. } else {
  1562. Log_OC.w(TAG, "Couldn't get display name for " + username);
  1563. }
  1564. if (isSaml) {
  1565. mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE");
  1566. } else if (isOAuth) {
  1567. mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_OAUTH2, "TRUE");
  1568. }
  1569. setAccountAuthenticatorResult(intent.getExtras());
  1570. setResult(RESULT_OK, intent);
  1571. return true;
  1572. }
  1573. }
  1574. /**
  1575. * Starts and activity to open the 'new account' page in the ownCloud web site
  1576. *
  1577. * @param view 'Account register' button
  1578. */
  1579. public void onRegisterClick(View view) {
  1580. Intent register = new Intent(
  1581. Intent.ACTION_VIEW, Uri.parse(getString(R.string.welcome_link_url))
  1582. );
  1583. setResult(RESULT_CANCELED);
  1584. startActivity(register);
  1585. }
  1586. /**
  1587. * Updates the content and visibility state of the icon and text associated
  1588. * to the last check on the ownCloud server.
  1589. */
  1590. private void showServerStatus() {
  1591. if (!webViewLoginMethod) {
  1592. if (mServerStatusIcon == 0 && mServerStatusText == 0) {
  1593. mServerStatusView.setVisibility(View.INVISIBLE);
  1594. } else {
  1595. mServerStatusView.setText(mServerStatusText);
  1596. mServerStatusView.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon, 0, 0, 0);
  1597. mServerStatusView.setVisibility(View.VISIBLE);
  1598. }
  1599. }
  1600. }
  1601. /**
  1602. * Updates the content and visibility state of the icon and text associated
  1603. * to the interactions with the OAuth authorization server.
  1604. */
  1605. private void showAuthStatus() {
  1606. if (!webViewLoginMethod) {
  1607. if (mAuthStatusIcon == 0 && mAuthStatusText == 0) {
  1608. mAuthStatusView.setVisibility(View.INVISIBLE);
  1609. } else {
  1610. mAuthStatusView.setText(mAuthStatusText);
  1611. mAuthStatusView.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon, 0, 0, 0);
  1612. mAuthStatusView.setVisibility(View.VISIBLE);
  1613. }
  1614. }
  1615. }
  1616. private void showRefreshButton(boolean show) {
  1617. if (webViewLoginMethod) {
  1618. if (show) {
  1619. mRefreshButton.setVisibility(View.VISIBLE);
  1620. } else {
  1621. mRefreshButton.setVisibility(View.GONE);
  1622. }
  1623. }
  1624. }
  1625. /**
  1626. * Called when the eye icon in the password field is clicked.
  1627. *
  1628. * Toggles the visibility of the password in the field.
  1629. */
  1630. public void onViewPasswordClick() {
  1631. int selectionStart = mPasswordInput.getSelectionStart();
  1632. int selectionEnd = mPasswordInput.getSelectionEnd();
  1633. if (isPasswordVisible()) {
  1634. hidePassword();
  1635. } else {
  1636. showPassword();
  1637. }
  1638. mPasswordInput.setSelection(selectionStart, selectionEnd);
  1639. }
  1640. /**
  1641. * Called when the checkbox for OAuth authorization is clicked.
  1642. *
  1643. * Hides or shows the input fields for user & password.
  1644. *
  1645. * @param view 'View password' 'button'
  1646. */
  1647. public void onCheckClick(View view) {
  1648. CheckBox oAuth2Check = (CheckBox) view;
  1649. if (oAuth2Check.isChecked()) {
  1650. mAuthTokenType = OAUTH_TOKEN_TYPE;
  1651. } else {
  1652. mAuthTokenType = BASIC_TOKEN_TYPE;
  1653. }
  1654. updateAuthenticationPreFragmentVisibility();
  1655. }
  1656. /**
  1657. * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
  1658. *
  1659. * Used to trigger the authentication check when the user presses 'enter' after writing the
  1660. * password, or to throw the server test when the only field on screen is the URL input field.
  1661. */
  1662. @Override
  1663. public boolean onEditorAction(TextView inputField, int actionId, KeyEvent event) {
  1664. if (actionId == EditorInfo.IME_ACTION_DONE && inputField != null &&
  1665. inputField.equals(mPasswordInput)) {
  1666. if (mOkButton.isEnabled()) {
  1667. mOkButton.performClick();
  1668. }
  1669. } else if (actionId == EditorInfo.IME_ACTION_NEXT && inputField != null &&
  1670. inputField.equals(mHostUrlInput) &&
  1671. AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
  1672. equals(mAuthTokenType)) {
  1673. checkOcServer();
  1674. }
  1675. return false; // always return false to grant that the software keyboard is hidden anyway
  1676. }
  1677. private abstract static class RightDrawableOnTouchListener implements OnTouchListener {
  1678. private int fuzz = 75;
  1679. /**
  1680. * {@inheritDoc}
  1681. */
  1682. @Override
  1683. public boolean onTouch(View view, MotionEvent event) {
  1684. Drawable rightDrawable = null;
  1685. if (view instanceof TextView) {
  1686. Drawable[] drawables = ((TextView) view).getCompoundDrawables();
  1687. if (drawables.length > 2) {
  1688. rightDrawable = drawables[2];
  1689. }
  1690. }
  1691. if (rightDrawable != null) {
  1692. final int x = (int) event.getX();
  1693. final int y = (int) event.getY();
  1694. final Rect bounds = rightDrawable.getBounds();
  1695. if (x >= (view.getRight() - bounds.width() - fuzz) &&
  1696. x <= (view.getRight() - view.getPaddingRight() + fuzz) &&
  1697. y >= (view.getPaddingTop() - fuzz) &&
  1698. y <= (view.getHeight() - view.getPaddingBottom()) + fuzz) {
  1699. return onDrawableTouch(event);
  1700. }
  1701. }
  1702. return false;
  1703. }
  1704. public abstract boolean onDrawableTouch(final MotionEvent event);
  1705. }
  1706. private void getRemoteUserNameOperation(String sessionCookie) {
  1707. Intent getUserNameIntent = new Intent();
  1708. getUserNameIntent.setAction(OperationsService.ACTION_GET_USER_NAME);
  1709. getUserNameIntent.putExtra(OperationsService.EXTRA_SERVER_URL, mServerInfo.mBaseUrl);
  1710. getUserNameIntent.putExtra(OperationsService.EXTRA_COOKIE, sessionCookie);
  1711. if (mOperationsServiceBinder != null) {
  1712. mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getUserNameIntent);
  1713. }
  1714. }
  1715. @Override
  1716. public void onSsoFinished(String sessionCookie) {
  1717. if (sessionCookie != null && sessionCookie.length() > 0) {
  1718. Log_OC.d(TAG, "Successful SSO - time to save the account");
  1719. mAuthToken = sessionCookie;
  1720. getRemoteUserNameOperation(sessionCookie);
  1721. Fragment fd = getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG);
  1722. if (fd instanceof DialogFragment) {
  1723. Dialog d = ((DialogFragment) fd).getDialog();
  1724. if (d != null && d.isShowing()) {
  1725. d.dismiss();
  1726. }
  1727. }
  1728. } else {
  1729. // TODO - show fail
  1730. Log_OC.d(TAG, "SSO failed");
  1731. }
  1732. }
  1733. @Override
  1734. public boolean onTouchEvent(MotionEvent event) {
  1735. if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
  1736. equals(mAuthTokenType) &&
  1737. mHostUrlInput.hasFocus() && event.getAction() == MotionEvent.ACTION_DOWN) {
  1738. checkOcServer();
  1739. }
  1740. return super.onTouchEvent(event);
  1741. }
  1742. /**
  1743. * Show untrusted cert dialog
  1744. */
  1745. public void showUntrustedCertDialog(
  1746. X509Certificate x509Certificate, SslError error, SslErrorHandler handler
  1747. ) {
  1748. // Show a dialog with the certificate info
  1749. SslUntrustedCertDialog dialog;
  1750. if (x509Certificate == null) {
  1751. dialog = SslUntrustedCertDialog.newInstanceForEmptySslError(error, handler);
  1752. } else {
  1753. dialog = SslUntrustedCertDialog.
  1754. newInstanceForFullSslError(x509Certificate, error, handler);
  1755. }
  1756. FragmentManager fm = getSupportFragmentManager();
  1757. FragmentTransaction ft = fm.beginTransaction();
  1758. ft.addToBackStack(null);
  1759. dialog.show(ft, UNTRUSTED_CERT_DIALOG_TAG);
  1760. }
  1761. /**
  1762. * Show untrusted cert dialog
  1763. */
  1764. private void showUntrustedCertDialog(RemoteOperationResult result) {
  1765. // Show a dialog with the certificate info
  1766. SslUntrustedCertDialog dialog = SslUntrustedCertDialog.
  1767. newInstanceForFullSslError((CertificateCombinedException) result.getException());
  1768. FragmentManager fm = getSupportFragmentManager();
  1769. FragmentTransaction ft = fm.beginTransaction();
  1770. ft.addToBackStack(null);
  1771. dialog.show(ft, UNTRUSTED_CERT_DIALOG_TAG);
  1772. }
  1773. /**
  1774. * Called from SslValidatorDialog when a new server certificate was correctly saved.
  1775. */
  1776. public void onSavedCertificate() {
  1777. Fragment fd = getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG);
  1778. if (fd == null) {
  1779. // if SAML dialog is not shown,
  1780. // the SslDialog was shown due to an SSL error in the server check
  1781. checkOcServer();
  1782. }
  1783. }
  1784. /**
  1785. * Called from SslValidatorDialog when a new server certificate could not be saved
  1786. * when the user requested it.
  1787. */
  1788. @Override
  1789. public void onFailedSavingCertificate() {
  1790. dismissDialog(SAML_DIALOG_TAG);
  1791. Toast.makeText(this, R.string.ssl_validator_not_saved, Toast.LENGTH_LONG).show();
  1792. }
  1793. @Override
  1794. public void onCancelCertificate() {
  1795. dismissDialog(SAML_DIALOG_TAG);
  1796. }
  1797. private void doOnResumeAndBound() {
  1798. //Log_OC.e(TAG, "registering to listen for operation callbacks" );
  1799. mOperationsServiceBinder.addOperationListener(AuthenticatorActivity.this, mHandler);
  1800. if (mWaitingForOpId <= Integer.MAX_VALUE) {
  1801. mOperationsServiceBinder.dispatchResultIfFinished((int) mWaitingForOpId, this);
  1802. }
  1803. if (!webViewLoginMethod && mHostUrlInput.getText() != null && mHostUrlInput.getText().length() > 0
  1804. && !mServerIsChecked) {
  1805. checkOcServer();
  1806. }
  1807. }
  1808. private void dismissDialog(String dialogTag) {
  1809. Fragment frag = getSupportFragmentManager().findFragmentByTag(dialogTag);
  1810. if (frag instanceof DialogFragment) {
  1811. DialogFragment dialog = (DialogFragment) frag;
  1812. dialog.dismiss();
  1813. }
  1814. }
  1815. /**
  1816. * Implements callback methods for service binding.
  1817. */
  1818. private class OperationsServiceConnection implements ServiceConnection {
  1819. @Override
  1820. public void onServiceConnected(ComponentName component, IBinder service) {
  1821. if (component.equals(
  1822. new ComponentName(AuthenticatorActivity.this, OperationsService.class)
  1823. )) {
  1824. mOperationsServiceBinder = (OperationsServiceBinder) service;
  1825. doOnResumeAndBound();
  1826. }
  1827. }
  1828. @Override
  1829. public void onServiceDisconnected(ComponentName component) {
  1830. if (component.equals(
  1831. new ComponentName(AuthenticatorActivity.this, OperationsService.class)
  1832. )) {
  1833. Log_OC.e(TAG, "Operations service crashed");
  1834. mOperationsServiceBinder = null;
  1835. }
  1836. }
  1837. }
  1838. /**
  1839. * Create and show dialog for request authentication to the user
  1840. *
  1841. * @param webView Web view to emebd into the authentication dialog.
  1842. * @param handler Object responsible for catching and recovering HTTP authentication fails.
  1843. */
  1844. public void createAuthenticationDialog(WebView webView, HttpAuthHandler handler) {
  1845. // Show a dialog with the certificate info
  1846. CredentialsDialogFragment dialog = CredentialsDialogFragment.newInstanceForCredentials(webView, handler);
  1847. FragmentManager fm = getSupportFragmentManager();
  1848. FragmentTransaction ft = fm.beginTransaction();
  1849. ft.addToBackStack(null);
  1850. dialog.setCancelable(false);
  1851. dialog.show(ft, CREDENTIALS_DIALOG_TAG);
  1852. if (!mIsFirstAuthAttempt) {
  1853. Toast.makeText(
  1854. getApplicationContext(),
  1855. getText(R.string.saml_authentication_wrong_pass),
  1856. Toast.LENGTH_LONG
  1857. ).show();
  1858. } else {
  1859. mIsFirstAuthAttempt = false;
  1860. }
  1861. }
  1862. /**
  1863. * For retrieving the clicking on authentication cancel button
  1864. */
  1865. public void doNegativeAuthenticatioDialogClick() {
  1866. mIsFirstAuthAttempt = true;
  1867. }
  1868. }