AuthenticatorActivity.java 93 KB

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