AuthenticatorActivity.java 74 KB

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