Merge pull request #946 from owncloud/upgrading_account_manager
[pub/Android/ownCloud.git] / src / com / owncloud / android / authentication / AccountUtils.java
1 /**
2 * ownCloud Android client application
3 *
4 * Copyright (C) 2012 Bartek Przybylski
5 * Copyright (C) 2015 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
21 package com.owncloud.android.authentication;
22
23 import java.util.Locale;
24
25 import com.owncloud.android.MainApp;
26 import com.owncloud.android.lib.common.accounts.AccountTypeUtils;
27 import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;
28 import com.owncloud.android.lib.common.utils.Log_OC;
29 import com.owncloud.android.lib.resources.status.OwnCloudVersion;
30
31 import android.accounts.Account;
32 import android.accounts.AccountManager;
33 import android.content.Context;
34 import android.content.SharedPreferences;
35 import android.net.Uri;
36 import android.preference.PreferenceManager;
37
38 public class AccountUtils {
39
40 private static final String TAG = AccountUtils.class.getSimpleName();
41
42 public static final String WEBDAV_PATH_4_0_AND_LATER = "/remote.php/webdav";
43 private static final String ODAV_PATH = "/remote.php/odav";
44 private static final String SAML_SSO_PATH = "/remote.php/webdav";
45 public static final String STATUS_PATH = "/status.php";
46
47 public static final int ACCOUNT_VERSION = 1;
48
49 /**
50 * Can be used to get the currently selected ownCloud {@link Account} in the
51 * application preferences.
52 *
53 * @param context The current application {@link Context}
54 * @return The ownCloud {@link Account} currently saved in preferences, or the first
55 * {@link Account} available, if valid (still registered in the system as ownCloud
56 * account). If none is available and valid, returns null.
57 */
58 public static Account getCurrentOwnCloudAccount(Context context) {
59 Account[] ocAccounts = AccountManager.get(context).getAccountsByType(
60 MainApp.getAccountType());
61 Account defaultAccount = null;
62
63 SharedPreferences appPreferences = PreferenceManager
64 .getDefaultSharedPreferences(context);
65 String accountName = appPreferences
66 .getString("select_oc_account", null);
67
68 // account validation: the saved account MUST be in the list of ownCloud Accounts known by the AccountManager
69 if (accountName != null) {
70 for (Account account : ocAccounts) {
71 if (account.name.equals(accountName)) {
72 defaultAccount = account;
73 break;
74 }
75 }
76 }
77
78 if (defaultAccount == null && ocAccounts.length != 0) {
79 // take first account as fallback
80 defaultAccount = ocAccounts[0];
81 }
82
83 return defaultAccount;
84 }
85
86
87 public static boolean exists(Account account, Context context) {
88 Account[] ocAccounts = AccountManager.get(context).getAccountsByType(
89 MainApp.getAccountType());
90
91 if (account != null && account.name != null) {
92 int lastAtPos = account.name.lastIndexOf("@");
93 String hostAndPort = account.name.substring(lastAtPos + 1);
94 String username = account.name.substring(0, lastAtPos);
95 String otherHostAndPort, otherUsername;
96 Locale currentLocale = context.getResources().getConfiguration().locale;
97 for (Account otherAccount : ocAccounts) {
98 lastAtPos = otherAccount.name.lastIndexOf("@");
99 otherHostAndPort = otherAccount.name.substring(lastAtPos + 1);
100 otherUsername = otherAccount.name.substring(0, lastAtPos);
101 if (otherHostAndPort.equals(hostAndPort) &&
102 otherUsername.toLowerCase(currentLocale).
103 equals(username.toLowerCase(currentLocale))) {
104 return true;
105 }
106 }
107 }
108 return false;
109 }
110
111
112 public static boolean setCurrentOwnCloudAccount(Context context, String accountName) {
113 boolean result = false;
114 if (accountName != null) {
115 Account[] ocAccounts = AccountManager.get(context).getAccountsByType(
116 MainApp.getAccountType());
117 boolean found = false;
118 for (Account account : ocAccounts) {
119 found = (account.name.equals(accountName));
120 if (found) {
121 SharedPreferences.Editor appPrefs = PreferenceManager
122 .getDefaultSharedPreferences(context).edit();
123 appPrefs.putString("select_oc_account", accountName);
124
125 appPrefs.commit();
126 result = true;
127 break;
128 }
129 }
130 }
131 return result;
132 }
133
134 /**
135 * Returns the proper URL path to access the WebDAV interface of an ownCloud server,
136 * according to its version and the authorization method used.
137 *
138 * @param version Version of ownCloud server.
139 * @param authTokenType Authorization token type, matching some of the AUTH_TOKEN_TYPE_* constants in
140 * {@link AccountAuthenticator}.
141 * @return WebDAV path for given OC version and authorization method, null if OC version
142 * is unknown; versions prior to ownCloud 4 are not supported anymore
143 */
144 public static String getWebdavPath(OwnCloudVersion version, String authTokenType) {
145 if (version != null) {
146 if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(authTokenType)) {
147 return ODAV_PATH;
148 }
149 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(authTokenType)) {
150 return SAML_SSO_PATH;
151 }
152 return WEBDAV_PATH_4_0_AND_LATER;
153 }
154 return null;
155 }
156
157
158 /**
159 * Update the accounts in AccountManager to meet the current version of accounts expected by the app, if needed.
160 *
161 * Introduced to handle a change in the structure of stored account names needed to allow different OC servers
162 * in the same domain, but not in the same path.
163 *
164 * @param context Used to access the AccountManager.
165 */
166 public static void updateAccountVersion(Context context) {
167 Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(context);
168 AccountManager accountMgr = AccountManager.get(context);
169
170 String currentAccountVersion = accountMgr.getUserData(currentAccount, Constants.KEY_OC_ACCOUNT_VERSION);
171
172 if (currentAccountVersion == null) {
173 Log_OC.i(TAG, "Upgrading accounts to account version #" + ACCOUNT_VERSION);
174 Account[] ocAccounts = accountMgr.getAccountsByType(MainApp.getAccountType());
175 String serverUrl, username, newAccountName, password;
176 Account newAccount;
177 for (Account account : ocAccounts) {
178 // build new account name
179 serverUrl = accountMgr.getUserData(account, Constants.KEY_OC_BASE_URL);
180 username = account.name.substring(0, account.name.lastIndexOf('@'));
181 newAccountName = com.owncloud.android.lib.common.accounts.AccountUtils.
182 buildAccountName(Uri.parse(serverUrl), username);
183
184 // migrate to a new account, if needed
185 if (!newAccountName.equals(account.name)) {
186 Log_OC.d(TAG, "Upgrading " + account.name + " to " + newAccountName );
187
188 // create the new account
189 newAccount = new Account(newAccountName, MainApp.getAccountType());
190 password = accountMgr.getPassword(account);
191 accountMgr.addAccountExplicitly(newAccount, (password != null) ? password : "", null);
192
193 // copy base URL
194 accountMgr.setUserData(newAccount, Constants.KEY_OC_BASE_URL, serverUrl);
195
196 // copy server version
197 accountMgr.setUserData(
198 newAccount,
199 Constants.KEY_OC_VERSION,
200 accountMgr.getUserData(account, Constants.KEY_OC_VERSION)
201 );
202
203 // copy cookies
204 accountMgr.setUserData(
205 newAccount,
206 Constants.KEY_COOKIES,
207 accountMgr.getUserData(account, Constants.KEY_COOKIES)
208 );
209
210 // copy type of authentication
211 String isSamlStr = accountMgr.getUserData(account, Constants.KEY_SUPPORTS_SAML_WEB_SSO);
212 boolean isSaml = "TRUE".equals(isSamlStr);
213 if (isSaml) {
214 accountMgr.setUserData(newAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE");
215 }
216
217 String isOauthStr = accountMgr.getUserData(account, Constants.KEY_SUPPORTS_OAUTH2);
218 boolean isOAuth = "TRUE".equals(isOauthStr);
219 if (isOAuth) {
220 accountMgr.setUserData(newAccount, Constants.KEY_SUPPORTS_OAUTH2, "TRUE");
221 }
222 /* TODO - study if it's possible to run this method in a background thread to copy the authToken
223 if (isOAuth || isSaml) {
224 accountMgr.setAuthToken(newAccount, mAuthTokenType, mAuthToken);
225 }
226 */
227
228 // don't forget the account saved in preferences as the current one
229 if (currentAccount != null && currentAccount.name.equals(account.name)) {
230 AccountUtils.setCurrentOwnCloudAccount(context, newAccountName);
231 }
232
233 // remove the old account
234 accountMgr.removeAccount(account, null, null); // will assume it succeeds, not a big deal otherwise
235
236 } else {
237 // servers which base URL is in the root of their domain need no change
238 Log_OC.d(TAG, account.name + " needs no upgrade ");
239 newAccount = account;
240 }
241
242 // at least, upgrade account version
243 Log_OC.d(TAG, "Setting version " + ACCOUNT_VERSION + " to " + newAccountName);
244 accountMgr.setUserData(newAccount, Constants.KEY_OC_ACCOUNT_VERSION, Integer.toString(ACCOUNT_VERSION));
245
246 }
247 }
248 }
249
250
251 }