AuthenticatorActivity.java 78 KB

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