AuthenticatorActivity.java 76 KB

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