AuthenticatorActivity.java 85 KB

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