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