AuthenticatorActivity.java 74 KB

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