AuthenticatorActivity.java 91 KB

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