AccountUtils.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /**
  2. * ownCloud Android client application
  3. *
  4. * Copyright (C) 2012 Bartek Przybylski
  5. * Copyright (C) 2016 ownCloud Inc.
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License version 2,
  9. * as published by the Free Software Foundation.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. *
  19. */
  20. package com.owncloud.android.authentication;
  21. import android.accounts.Account;
  22. import android.accounts.AccountManager;
  23. import android.content.Context;
  24. import android.content.SharedPreferences;
  25. import android.net.Uri;
  26. import android.preference.PreferenceManager;
  27. import android.support.annotation.Nullable;
  28. import com.owncloud.android.MainApp;
  29. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  30. import com.owncloud.android.datamodel.FileDataStorageManager;
  31. import com.owncloud.android.lib.common.OwnCloudAccount;
  32. import com.owncloud.android.lib.common.OwnCloudClient;
  33. import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
  34. import com.owncloud.android.lib.common.UserInfo;
  35. import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;
  36. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  37. import com.owncloud.android.lib.common.utils.Log_OC;
  38. import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  39. import com.owncloud.android.lib.resources.users.GetRemoteUserInfoOperation;
  40. import com.owncloud.android.operations.GetCapabilitiesOperarion;
  41. import com.owncloud.android.ui.activity.ManageAccountsActivity;
  42. import java.util.Locale;
  43. public class AccountUtils {
  44. private static final String TAG = AccountUtils.class.getSimpleName();
  45. public static final int ACCOUNT_VERSION = 1;
  46. public static final int ACCOUNT_VERSION_WITH_PROPER_ID = 2;
  47. public static final String ACCOUNT_USES_STANDARD_PASSWORD = "ACCOUNT_USES_STANDARD_PASSWORD";
  48. /**
  49. * Can be used to get the currently selected ownCloud {@link Account} in the
  50. * application preferences.
  51. *
  52. * @param context The current application {@link Context}
  53. * @return The ownCloud {@link Account} currently saved in preferences, or the first
  54. * {@link Account} available, if valid (still registered in the system as ownCloud
  55. * account). If none is available and valid, returns null.
  56. */
  57. public static @Nullable
  58. Account getCurrentOwnCloudAccount(Context context) {
  59. Account[] ocAccounts = getAccounts(context);
  60. Account defaultAccount = null;
  61. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(context.getContentResolver());
  62. SharedPreferences appPreferences = PreferenceManager.getDefaultSharedPreferences(context);
  63. String accountName = appPreferences.getString("select_oc_account", null);
  64. // account validation: the saved account MUST be in the list of ownCloud Accounts known by the AccountManager
  65. if (accountName != null) {
  66. for (Account account : ocAccounts) {
  67. if (account.name.equals(accountName)) {
  68. defaultAccount = account;
  69. break;
  70. }
  71. }
  72. }
  73. if (defaultAccount == null && ocAccounts.length > 0) {
  74. // take first which is not pending for removal account as fallback
  75. for (Account account: ocAccounts) {
  76. boolean pendingForRemoval = arbitraryDataProvider.getBooleanValue(account,
  77. ManageAccountsActivity.PENDING_FOR_REMOVAL);
  78. if (!pendingForRemoval) {
  79. defaultAccount = account;
  80. break;
  81. }
  82. }
  83. }
  84. return defaultAccount;
  85. }
  86. public static Account[] getAccounts(Context context) {
  87. AccountManager accountManager = AccountManager.get(context);
  88. return accountManager.getAccountsByType(MainApp.getAccountType());
  89. }
  90. public static boolean exists(Account account, Context context) {
  91. Account[] ocAccounts = getAccounts(context);
  92. if (account != null && account.name != null) {
  93. int lastAtPos = account.name.lastIndexOf("@");
  94. String hostAndPort = account.name.substring(lastAtPos + 1);
  95. String username = account.name.substring(0, lastAtPos);
  96. String otherHostAndPort;
  97. String otherUsername;
  98. Locale currentLocale = context.getResources().getConfiguration().locale;
  99. for (Account otherAccount : ocAccounts) {
  100. lastAtPos = otherAccount.name.lastIndexOf("@");
  101. otherHostAndPort = otherAccount.name.substring(lastAtPos + 1);
  102. otherUsername = otherAccount.name.substring(0, lastAtPos);
  103. if (otherHostAndPort.equals(hostAndPort) &&
  104. otherUsername.toLowerCase(currentLocale).
  105. equals(username.toLowerCase(currentLocale))) {
  106. return true;
  107. }
  108. }
  109. }
  110. return false;
  111. }
  112. /**
  113. * returns the user's name based on the account name.
  114. *
  115. * @param accountName the account name
  116. * @return the user's name
  117. */
  118. public static String getAccountUsername(String accountName) {
  119. if (accountName != null) {
  120. return accountName.substring(0, accountName.lastIndexOf('@'));
  121. } else {
  122. return null;
  123. }
  124. }
  125. /**
  126. * Returns owncloud account identified by accountName or null if it does not exist.
  127. * @param context the context
  128. * @param accountName name of account to be returned
  129. * @return owncloud account named accountName
  130. */
  131. public static Account getOwnCloudAccountByName(Context context, String accountName) {
  132. Account[] ocAccounts = AccountManager.get(context).getAccountsByType(
  133. MainApp.getAccountType());
  134. for (Account account : ocAccounts) {
  135. if(account.name.equals(accountName)) {
  136. return account;
  137. }
  138. }
  139. return null;
  140. }
  141. public static boolean setCurrentOwnCloudAccount(final Context context, String accountName) {
  142. boolean result = false;
  143. if (accountName != null) {
  144. boolean found;
  145. for (final Account account : getAccounts(context)) {
  146. found = (account.name.equals(accountName));
  147. if (found) {
  148. SharedPreferences.Editor appPrefs = PreferenceManager.getDefaultSharedPreferences(context).edit();
  149. appPrefs.putString("select_oc_account", accountName);
  150. // update credentials
  151. Thread t = new Thread(new Runnable() {
  152. @Override
  153. public void run() {
  154. FileDataStorageManager storageManager = new FileDataStorageManager(account,
  155. context.getContentResolver());
  156. GetCapabilitiesOperarion getCapabilities = new GetCapabilitiesOperarion();
  157. RemoteOperationResult updateResult = getCapabilities.execute(storageManager, context);
  158. Log_OC.w(TAG, "Update Capabilities: " + updateResult.isSuccess());
  159. }
  160. });
  161. t.start();
  162. appPrefs.apply();
  163. result = true;
  164. break;
  165. }
  166. }
  167. }
  168. return result;
  169. }
  170. public static void resetOwnCloudAccount(Context context) {
  171. SharedPreferences.Editor appPrefs = PreferenceManager.getDefaultSharedPreferences(context).edit();
  172. appPrefs.putString("select_oc_account", null);
  173. appPrefs.apply();
  174. }
  175. /**
  176. * Update the accounts in AccountManager to meet the current version of accounts expected by the app, if needed.
  177. *
  178. * Introduced to handle a change in the structure of stored account names needed to allow different OC servers
  179. * in the same domain, but not in the same path.
  180. *
  181. * @param context Used to access the AccountManager.
  182. */
  183. public static void updateAccountVersion(Context context) {
  184. Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(context);
  185. AccountManager accountMgr = AccountManager.get(context);
  186. if ( currentAccount != null ) {
  187. String currentAccountVersion = accountMgr.getUserData(currentAccount, Constants.KEY_OC_ACCOUNT_VERSION);
  188. if (!String.valueOf(ACCOUNT_VERSION_WITH_PROPER_ID).equalsIgnoreCase(currentAccountVersion)) {
  189. Log_OC.i(TAG, "Upgrading accounts to account version #" + ACCOUNT_VERSION_WITH_PROPER_ID);
  190. Account[] ocAccounts = accountMgr.getAccountsByType(MainApp.getAccountType());
  191. String serverUrl;
  192. String username;
  193. String newAccountName;
  194. String password;
  195. Account newAccount;
  196. for (Account account : ocAccounts) {
  197. // build new account name
  198. serverUrl = accountMgr.getUserData(account, Constants.KEY_OC_BASE_URL);
  199. // update user name
  200. try {
  201. OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
  202. OwnCloudClient client = OwnCloudClientManagerFactory.getDefaultSingleton()
  203. .getClientFor(ocAccount, context);
  204. GetRemoteUserInfoOperation remoteUserNameOperation = new GetRemoteUserInfoOperation();
  205. RemoteOperationResult result = remoteUserNameOperation.execute(client);
  206. if (result.isSuccess()) {
  207. UserInfo userInfo = (UserInfo) result.getData().get(0);
  208. username = userInfo.id;
  209. } else {
  210. // skip account, try it next time
  211. Log_OC.e(TAG, "Error while getting username for account: " + account.name);
  212. continue;
  213. }
  214. } catch (Exception e) {
  215. Log_OC.e(TAG, "Error while getting username: " + e.getMessage());
  216. continue;
  217. }
  218. newAccountName = com.owncloud.android.lib.common.accounts.AccountUtils.
  219. buildAccountName(Uri.parse(serverUrl), username);
  220. // migrate to a new account, if needed
  221. if (!newAccountName.equals(account.name)) {
  222. Log_OC.d(TAG, "Upgrading " + account.name + " to " + newAccountName);
  223. // create the new account
  224. newAccount = new Account(newAccountName, MainApp.getAccountType());
  225. password = accountMgr.getPassword(account);
  226. accountMgr.addAccountExplicitly(newAccount, (password != null) ? password : "", null);
  227. // copy base URL
  228. accountMgr.setUserData(newAccount, Constants.KEY_OC_BASE_URL, serverUrl);
  229. // copy server version
  230. accountMgr.setUserData(
  231. newAccount,
  232. Constants.KEY_OC_VERSION,
  233. accountMgr.getUserData(account, Constants.KEY_OC_VERSION)
  234. );
  235. // copy cookies
  236. accountMgr.setUserData(
  237. newAccount,
  238. Constants.KEY_COOKIES,
  239. accountMgr.getUserData(account, Constants.KEY_COOKIES)
  240. );
  241. // copy type of authentication
  242. final String isSamlStr = accountMgr.getUserData(account, Constants.KEY_SUPPORTS_SAML_WEB_SSO);
  243. if (Boolean.parseBoolean(isSamlStr)) {
  244. accountMgr.setUserData(newAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE");
  245. }
  246. final String isOauthStr = accountMgr.getUserData(account, Constants.KEY_SUPPORTS_OAUTH2);
  247. if (Boolean.parseBoolean(isOauthStr)) {
  248. accountMgr.setUserData(newAccount, Constants.KEY_SUPPORTS_OAUTH2, "TRUE");
  249. }
  250. /* TODO - study if it's possible to run this method in a background thread to copy the authToken
  251. if (isOAuth || isSaml) {
  252. accountMgr.setAuthToken(newAccount, mAuthTokenType, mAuthToken);
  253. }
  254. */
  255. // don't forget the account saved in preferences as the current one
  256. if (currentAccount.name.equals(account.name)) {
  257. AccountUtils.setCurrentOwnCloudAccount(context, newAccountName);
  258. }
  259. // remove the old account
  260. accountMgr.removeAccount(account, null, null);
  261. // will assume it succeeds, not a big deal otherwise
  262. } else {
  263. // servers which base URL is in the root of their domain need no change
  264. Log_OC.d(TAG, account.name + " needs no upgrade ");
  265. newAccount = account;
  266. }
  267. // at least, upgrade account version
  268. Log_OC.d(TAG, "Setting version " + ACCOUNT_VERSION_WITH_PROPER_ID + " to " + newAccountName);
  269. accountMgr.setUserData(newAccount,
  270. Constants.KEY_OC_ACCOUNT_VERSION, Integer.toString(ACCOUNT_VERSION_WITH_PROPER_ID));
  271. }
  272. }
  273. }
  274. }
  275. /**
  276. * Access the version of the OC server corresponding to an account SAVED IN THE ACCOUNTMANAGER
  277. *
  278. * @param account ownCloud account
  279. * @return Version of the OC server corresponding to account, according to the data saved
  280. * in the system AccountManager
  281. */
  282. public static OwnCloudVersion getServerVersion(Account account) {
  283. OwnCloudVersion serverVersion = null;
  284. if (account != null) {
  285. AccountManager accountMgr = AccountManager.get(MainApp.getAppContext());
  286. String serverVersionStr = accountMgr.getUserData(account, Constants.KEY_OC_VERSION);
  287. if (serverVersionStr != null) {
  288. serverVersion = new OwnCloudVersion(serverVersionStr);
  289. }
  290. }
  291. return serverVersion;
  292. }
  293. public static boolean hasSearchUsersSupport(Account account){
  294. OwnCloudVersion serverVersion = getServerVersion(account);
  295. return (serverVersion != null && serverVersion.isSearchUsersSupported());
  296. }
  297. public static boolean hasSearchSupport(Account account) {
  298. OwnCloudVersion serverVersion = getServerVersion(account);
  299. return (serverVersion != null && serverVersion.isSearchSupported());
  300. }
  301. }