a2a38e89fcad505214b0e47a2dd47cf10cf5fec8
[pub/Android/ownCloud.git] / src / com / owncloud / android / authentication / AccountAuthenticator.java
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
19 package com.owncloud.android.authentication;
20
21 import com.owncloud.android.Log_OC;
22 import com.owncloud.android.MainApp;
23 import com.owncloud.android.R;
24
25 import android.accounts.*;
26 import android.content.Context;
27 import android.content.Intent;
28 import android.os.Bundle;
29 import android.os.Handler;
30 import android.widget.Toast;
31
32
33
34
35 /**
36 * Authenticator for ownCloud accounts.
37 *
38 * Controller class accessed from the system AccountManager, providing integration of ownCloud accounts with the Android system.
39 *
40 * TODO - better separation in operations for OAuth-capable and regular ownCloud accounts.
41 * TODO - review completeness
42 *
43 * @author David A. Velasco
44 */
45 public class AccountAuthenticator extends AbstractAccountAuthenticator {
46
47 /**
48 * Is used by android system to assign accounts to authenticators. Should be
49 * used by application and all extensions.
50 */
51 /* These constants are now in MainApp
52 public static final String ACCOUNT_TYPE = "owncloud";
53 public static final String AUTHORITY = "org.owncloud";
54 public static final String AUTH_TOKEN_TYPE = "org.owncloud";
55 public static final String AUTH_TOKEN_TYPE_PASSWORD = "owncloud.password";
56 public static final String AUTH_TOKEN_TYPE_ACCESS_TOKEN = "owncloud.oauth2.access_token";
57 public static final String AUTH_TOKEN_TYPE_REFRESH_TOKEN = "owncloud.oauth2.refresh_token";
58 public static final String AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE = "owncloud.saml.web_sso.session_cookie";
59 */
60 public static final String KEY_AUTH_TOKEN_TYPE = "authTokenType";
61 public static final String KEY_REQUIRED_FEATURES = "requiredFeatures";
62 public static final String KEY_LOGIN_OPTIONS = "loginOptions";
63 public static final String KEY_ACCOUNT = "account";
64
65 /**
66 * Value under this key should handle path to webdav php script. Will be
67 * removed and usage should be replaced by combining
68 * {@link com.owncloud.android.authentication.AuthenticatorActivity.KEY_OC_BASE_URL} and
69 * {@link com.owncloud.android.utils.OwnCloudVersion}
70 *
71 * @deprecated
72 */
73 public static final String KEY_OC_URL = "oc_url";
74 /**
75 * Version should be 3 numbers separated by dot so it can be parsed by
76 * {@link com.owncloud.android.utils.OwnCloudVersion}
77 */
78 public static final String KEY_OC_VERSION = "oc_version";
79 /**
80 * Base url should point to owncloud installation without trailing / ie:
81 * http://server/path or https://owncloud.server
82 */
83 public static final String KEY_OC_BASE_URL = "oc_base_url";
84 /**
85 * Flag signaling if the ownCloud server can be accessed with OAuth2 access tokens.
86 */
87 public static final String KEY_SUPPORTS_OAUTH2 = "oc_supports_oauth2";
88 /**
89 * Flag signaling if the ownCloud server can be accessed with session cookies from SAML-based web single-sign-on.
90 */
91 public static final String KEY_SUPPORTS_SAML_WEB_SSO = "oc_supports_saml_web_sso";
92
93 private static final String TAG = AccountAuthenticator.class.getSimpleName();
94
95 private Context mContext;
96
97 private Handler mHandler;
98
99 public AccountAuthenticator(Context context) {
100 super(context);
101 mContext = context;
102 mHandler = new Handler();
103 }
104
105 /**
106 * {@inheritDoc}
107 */
108 @Override
109 public Bundle addAccount(AccountAuthenticatorResponse response,
110 String accountType, String authTokenType,
111 String[] requiredFeatures, Bundle options)
112 throws NetworkErrorException {
113 Log_OC.i(TAG, "Adding account with type " + accountType
114 + " and auth token " + authTokenType);
115
116 final Bundle bundle = new Bundle();
117
118 AccountManager accountManager = AccountManager.get(mContext);
119 Account[] accounts = accountManager.getAccountsByType(MainApp.getAccountType());
120
121 if (mContext.getResources().getBoolean(R.bool.multiaccount_support) || accounts.length < 1) {
122 try {
123 validateAccountType(accountType);
124 } catch (AuthenticatorException e) {
125 Log_OC.e(TAG, "Failed to validate account type " + accountType + ": "
126 + e.getMessage());
127 e.printStackTrace();
128 return e.getFailureBundle();
129 }
130
131 final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
132 intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
133 intent.putExtra(KEY_AUTH_TOKEN_TYPE, authTokenType);
134 intent.putExtra(KEY_REQUIRED_FEATURES, requiredFeatures);
135 intent.putExtra(KEY_LOGIN_OPTIONS, options);
136 intent.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_CREATE);
137
138 setIntentFlags(intent);
139
140 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
141
142 } else {
143
144 // Return an error
145 bundle.putInt(AccountManager.KEY_ERROR_CODE, AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION);
146 final String message = String.format(mContext.getString(R.string.auth_unsupported_multiaccount), mContext.getString(R.string.app_name));
147 bundle.putString(AccountManager.KEY_ERROR_MESSAGE, message);
148
149 mHandler.post(new Runnable() {
150
151 @Override
152 public void run() {
153 Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
154 }
155 });
156
157 }
158
159 return bundle;
160 }
161
162 /**
163 * {@inheritDoc}
164 */
165 @Override
166 public Bundle confirmCredentials(AccountAuthenticatorResponse response,
167 Account account, Bundle options) throws NetworkErrorException {
168 try {
169 validateAccountType(account.type);
170 } catch (AuthenticatorException e) {
171 Log_OC.e(TAG, "Failed to validate account type " + account.type + ": "
172 + e.getMessage());
173 e.printStackTrace();
174 return e.getFailureBundle();
175 }
176 Intent intent = new Intent(mContext, AuthenticatorActivity.class);
177 intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,
178 response);
179 intent.putExtra(KEY_ACCOUNT, account);
180 intent.putExtra(KEY_LOGIN_OPTIONS, options);
181
182 setIntentFlags(intent);
183
184 Bundle resultBundle = new Bundle();
185 resultBundle.putParcelable(AccountManager.KEY_INTENT, intent);
186 return resultBundle;
187 }
188
189 @Override
190 public Bundle editProperties(AccountAuthenticatorResponse response,
191 String accountType) {
192 return null;
193 }
194
195 /**
196 * {@inheritDoc}
197 */
198 @Override
199 public Bundle getAuthToken(AccountAuthenticatorResponse response,
200 Account account, String authTokenType, Bundle options)
201 throws NetworkErrorException {
202 /// validate parameters
203 try {
204 validateAccountType(account.type);
205 validateAuthTokenType(authTokenType);
206 } catch (AuthenticatorException e) {
207 Log_OC.e(TAG, "Failed to validate account type " + account.type + ": "
208 + e.getMessage());
209 e.printStackTrace();
210 return e.getFailureBundle();
211 }
212
213 /// check if required token is stored
214 final AccountManager am = AccountManager.get(mContext);
215 String accessToken;
216 if (authTokenType.equals(MainApp.getAuthTokenTypePass())) {
217 accessToken = am.getPassword(account);
218 } else {
219 accessToken = am.peekAuthToken(account, authTokenType);
220 }
221 if (accessToken != null) {
222 final Bundle result = new Bundle();
223 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
224 result.putString(AccountManager.KEY_ACCOUNT_TYPE, MainApp.getAccountType());
225 result.putString(AccountManager.KEY_AUTHTOKEN, accessToken);
226 return result;
227 }
228
229 /// if not stored, return Intent to access the AuthenticatorActivity and UPDATE the token for the account
230 final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
231 intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
232 intent.putExtra(KEY_AUTH_TOKEN_TYPE, authTokenType);
233 intent.putExtra(KEY_LOGIN_OPTIONS, options);
234 intent.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, account);
235 intent.putExtra(AuthenticatorActivity.EXTRA_ENFORCED_UPDATE, true);
236 intent.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_TOKEN);
237
238
239 final Bundle bundle = new Bundle();
240 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
241 return bundle;
242 }
243
244 @Override
245 public String getAuthTokenLabel(String authTokenType) {
246 return null;
247 }
248
249 @Override
250 public Bundle hasFeatures(AccountAuthenticatorResponse response,
251 Account account, String[] features) throws NetworkErrorException {
252 final Bundle result = new Bundle();
253 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, true);
254 return result;
255 }
256
257 @Override
258 public Bundle updateCredentials(AccountAuthenticatorResponse response,
259 Account account, String authTokenType, Bundle options)
260 throws NetworkErrorException {
261 final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
262 intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,
263 response);
264 intent.putExtra(KEY_ACCOUNT, account);
265 intent.putExtra(KEY_AUTH_TOKEN_TYPE, authTokenType);
266 intent.putExtra(KEY_LOGIN_OPTIONS, options);
267 setIntentFlags(intent);
268
269 final Bundle bundle = new Bundle();
270 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
271 return bundle;
272 }
273
274 @Override
275 public Bundle getAccountRemovalAllowed(
276 AccountAuthenticatorResponse response, Account account)
277 throws NetworkErrorException {
278 return super.getAccountRemovalAllowed(response, account);
279 }
280
281 private void setIntentFlags(Intent intent) {
282 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
283 intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
284 intent.addFlags(Intent.FLAG_FROM_BACKGROUND);
285 }
286
287 private void validateAccountType(String type)
288 throws UnsupportedAccountTypeException {
289 if (!type.equals(MainApp.getAccountType())) {
290 throw new UnsupportedAccountTypeException();
291 }
292 }
293
294 private void validateAuthTokenType(String authTokenType)
295 throws UnsupportedAuthTokenTypeException {
296 if (!authTokenType.equals(MainApp.getAuthTokenType()) &&
297 !authTokenType.equals(MainApp.getAuthTokenTypePass()) &&
298 !authTokenType.equals(MainApp.getAuthTokenTypeAccessToken()) &&
299 !authTokenType.equals(MainApp.getAuthTokenTypeRefreshToken()) &&
300 !authTokenType.equals(MainApp.getAuthTokenTypeSamlSessionCookie())) {
301 throw new UnsupportedAuthTokenTypeException();
302 }
303 }
304
305 public static class AuthenticatorException extends Exception {
306 private static final long serialVersionUID = 1L;
307 private Bundle mFailureBundle;
308
309 public AuthenticatorException(int code, String errorMsg) {
310 mFailureBundle = new Bundle();
311 mFailureBundle.putInt(AccountManager.KEY_ERROR_CODE, code);
312 mFailureBundle
313 .putString(AccountManager.KEY_ERROR_MESSAGE, errorMsg);
314 }
315
316 public Bundle getFailureBundle() {
317 return mFailureBundle;
318 }
319 }
320
321 public static class UnsupportedAccountTypeException extends
322 AuthenticatorException {
323 private static final long serialVersionUID = 1L;
324
325 public UnsupportedAccountTypeException() {
326 super(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
327 "Unsupported account type");
328 }
329 }
330
331 public static class UnsupportedAuthTokenTypeException extends
332 AuthenticatorException {
333 private static final long serialVersionUID = 1L;
334
335 public UnsupportedAuthTokenTypeException() {
336 super(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
337 "Unsupported auth token type");
338 }
339 }
340
341 public static class UnsupportedFeaturesException extends
342 AuthenticatorException {
343 public static final long serialVersionUID = 1L;
344
345 public UnsupportedFeaturesException() {
346 super(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
347 "Unsupported features");
348 }
349 }
350
351 public static class AccessDeniedException extends AuthenticatorException {
352 public AccessDeniedException(int code, String errorMsg) {
353 super(AccountManager.ERROR_CODE_INVALID_RESPONSE, "Access Denied");
354 }
355
356 private static final long serialVersionUID = 1L;
357
358 }
359 }