AuthenticatorActivity.java 86 KB

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