AuthenticatorActivity.java 76 KB

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