AuthenticatorActivity.java 76 KB

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