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