AuthenticatorActivity.java 74 KB

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