OAuth clean-up and refactoring
[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 as published by
7 * the Free Software Foundation, either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 */
19
20 package com.owncloud.android.authentication;
21
22
23 import android.accounts.*;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.os.Bundle;
27 import android.util.Log;
28
29
30 /**
31 * Authenticator for ownCloud accounts.
32 *
33 * Controller class accessed from the system AccountManager, providing integration of ownCloud accounts with the Android system.
34 *
35 * TODO - better separation in operations for OAuth-capable and regular ownCloud accounts.
36 * TODO - review completeness
37 *
38 * @author David A. Velasco
39 */
40 public class AccountAuthenticator extends AbstractAccountAuthenticator {
41 /**
42 * Is used by android system to assign accounts to authenticators. Should be
43 * used by application and all extensions.
44 */
45 public static final String ACCOUNT_TYPE = "owncloud";
46 public static final String AUTHORITY = "org.owncloud";
47 public static final String AUTH_TOKEN_TYPE = "org.owncloud";
48 public static final String AUTH_TOKEN_TYPE_PASSWORD = "owncloud.password";
49 public static final String AUTH_TOKEN_TYPE_ACCESS_TOKEN = "owncloud.oauth2.access_token";
50 public static final String AUTH_TOKEN_TYPE_REFRESH_TOKEN = "owncloud.oauth2.refresh_token";
51
52 public static final String KEY_AUTH_TOKEN_TYPE = "authTokenType";
53 public static final String KEY_REQUIRED_FEATURES = "requiredFeatures";
54 public static final String KEY_LOGIN_OPTIONS = "loginOptions";
55 public static final String KEY_ACCOUNT = "account";
56 /**
57 * Value under this key should handle path to webdav php script. Will be
58 * removed and usage should be replaced by combining
59 * {@link com.owncloud.android.authentication.AuthenticatorActivity.KEY_OC_BASE_URL} and
60 * {@link com.owncloud.android.utils.OwnCloudVersion}
61 *
62 * @deprecated
63 */
64 public static final String KEY_OC_URL = "oc_url";
65 /**
66 * Version should be 3 numbers separated by dot so it can be parsed by
67 * {@link com.owncloud.android.utils.OwnCloudVersion}
68 */
69 public static final String KEY_OC_VERSION = "oc_version";
70 /**
71 * Base url should point to owncloud installation without trailing / ie:
72 * http://server/path or https://owncloud.server
73 */
74 public static final String KEY_OC_BASE_URL = "oc_base_url";
75 /**
76 * Flag signaling if the ownCloud server can be accessed with OAuth2 access tokens.
77 */
78 public static final String KEY_SUPPORTS_OAUTH2 = "oc_supports_oauth2";
79
80 private static final String TAG = AccountAuthenticator.class.getSimpleName();
81
82 private Context mContext;
83
84 public AccountAuthenticator(Context context) {
85 super(context);
86 mContext = context;
87 }
88
89 /**
90 * {@inheritDoc}
91 */
92 @Override
93 public Bundle addAccount(AccountAuthenticatorResponse response,
94 String accountType, String authTokenType,
95 String[] requiredFeatures, Bundle options)
96 throws NetworkErrorException {
97 Log.i(TAG, "Adding account with type " + accountType
98 + " and auth token " + authTokenType);
99 try {
100 validateAccountType(accountType);
101 } catch (AuthenticatorException e) {
102 Log.e(TAG, "Failed to validate account type " + accountType + ": "
103 + e.getMessage());
104 e.printStackTrace();
105 return e.getFailureBundle();
106 }
107 final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
108 intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
109 intent.putExtra(KEY_AUTH_TOKEN_TYPE, authTokenType);
110 intent.putExtra(KEY_REQUIRED_FEATURES, requiredFeatures);
111 intent.putExtra(KEY_LOGIN_OPTIONS, options);
112 intent.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_CREATE);
113
114 setIntentFlags(intent);
115
116 final Bundle bundle = new Bundle();
117 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
118 return bundle;
119 }
120
121 /**
122 * {@inheritDoc}
123 */
124 @Override
125 public Bundle confirmCredentials(AccountAuthenticatorResponse response,
126 Account account, Bundle options) throws NetworkErrorException {
127 try {
128 validateAccountType(account.type);
129 } catch (AuthenticatorException e) {
130 Log.e(TAG, "Failed to validate account type " + account.type + ": "
131 + e.getMessage());
132 e.printStackTrace();
133 return e.getFailureBundle();
134 }
135 Intent intent = new Intent(mContext, AuthenticatorActivity.class);
136 intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,
137 response);
138 intent.putExtra(KEY_ACCOUNT, account);
139 intent.putExtra(KEY_LOGIN_OPTIONS, options);
140
141 setIntentFlags(intent);
142
143 Bundle resultBundle = new Bundle();
144 resultBundle.putParcelable(AccountManager.KEY_INTENT, intent);
145 return resultBundle;
146 }
147
148 @Override
149 public Bundle editProperties(AccountAuthenticatorResponse response,
150 String accountType) {
151 return null;
152 }
153
154 /**
155 * {@inheritDoc}
156 */
157 @Override
158 public Bundle getAuthToken(AccountAuthenticatorResponse response,
159 Account account, String authTokenType, Bundle options)
160 throws NetworkErrorException {
161 /// validate parameters
162 try {
163 validateAccountType(account.type);
164 validateAuthTokenType(authTokenType);
165 } catch (AuthenticatorException e) {
166 Log.e(TAG, "Failed to validate account type " + account.type + ": "
167 + e.getMessage());
168 e.printStackTrace();
169 return e.getFailureBundle();
170 }
171
172 /// check if required token is stored
173 final AccountManager am = AccountManager.get(mContext);
174 String accessToken;
175 if (authTokenType.equals(AUTH_TOKEN_TYPE_PASSWORD)) {
176 accessToken = am.getPassword(account);
177 } else {
178 accessToken = am.peekAuthToken(account, authTokenType);
179 }
180 if (accessToken != null) {
181 final Bundle result = new Bundle();
182 result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
183 result.putString(AccountManager.KEY_ACCOUNT_TYPE, ACCOUNT_TYPE);
184 result.putString(AccountManager.KEY_AUTHTOKEN, accessToken);
185 return result;
186 }
187
188 /// if not stored, return Intent to access the AuthenticatorActivity and UPDATE the token for the account
189 final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
190 intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
191 intent.putExtra(KEY_AUTH_TOKEN_TYPE, authTokenType);
192 intent.putExtra(KEY_LOGIN_OPTIONS, options);
193 intent.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, account);
194 intent.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_TOKEN);
195
196
197 final Bundle bundle = new Bundle();
198 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
199 return bundle;
200 }
201
202 @Override
203 public String getAuthTokenLabel(String authTokenType) {
204 return null;
205 }
206
207 @Override
208 public Bundle hasFeatures(AccountAuthenticatorResponse response,
209 Account account, String[] features) throws NetworkErrorException {
210 final Bundle result = new Bundle();
211 result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, true);
212 return result;
213 }
214
215 @Override
216 public Bundle updateCredentials(AccountAuthenticatorResponse response,
217 Account account, String authTokenType, Bundle options)
218 throws NetworkErrorException {
219 final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
220 intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE,
221 response);
222 intent.putExtra(KEY_ACCOUNT, account);
223 intent.putExtra(KEY_AUTH_TOKEN_TYPE, authTokenType);
224 intent.putExtra(KEY_LOGIN_OPTIONS, options);
225 setIntentFlags(intent);
226
227 final Bundle bundle = new Bundle();
228 bundle.putParcelable(AccountManager.KEY_INTENT, intent);
229 return bundle;
230 }
231
232 @Override
233 public Bundle getAccountRemovalAllowed(
234 AccountAuthenticatorResponse response, Account account)
235 throws NetworkErrorException {
236 return super.getAccountRemovalAllowed(response, account);
237 }
238
239 private void setIntentFlags(Intent intent) {
240 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
241 //intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
242 //intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); // incompatible with the authorization code grant in OAuth
243 intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
244 intent.addFlags(Intent.FLAG_FROM_BACKGROUND);
245 }
246
247 private void validateAccountType(String type)
248 throws UnsupportedAccountTypeException {
249 if (!type.equals(ACCOUNT_TYPE)) {
250 throw new UnsupportedAccountTypeException();
251 }
252 }
253
254 private void validateAuthTokenType(String authTokenType)
255 throws UnsupportedAuthTokenTypeException {
256 if (!authTokenType.equals(AUTH_TOKEN_TYPE) &&
257 !authTokenType.equals(AUTH_TOKEN_TYPE_PASSWORD) &&
258 !authTokenType.equals(AUTH_TOKEN_TYPE_ACCESS_TOKEN) &&
259 !authTokenType.equals(AUTH_TOKEN_TYPE_REFRESH_TOKEN) ) {
260 throw new UnsupportedAuthTokenTypeException();
261 }
262 }
263
264 public static class AuthenticatorException extends Exception {
265 private static final long serialVersionUID = 1L;
266 private Bundle mFailureBundle;
267
268 public AuthenticatorException(int code, String errorMsg) {
269 mFailureBundle = new Bundle();
270 mFailureBundle.putInt(AccountManager.KEY_ERROR_CODE, code);
271 mFailureBundle
272 .putString(AccountManager.KEY_ERROR_MESSAGE, errorMsg);
273 }
274
275 public Bundle getFailureBundle() {
276 return mFailureBundle;
277 }
278 }
279
280 public static class UnsupportedAccountTypeException extends
281 AuthenticatorException {
282 private static final long serialVersionUID = 1L;
283
284 public UnsupportedAccountTypeException() {
285 super(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
286 "Unsupported account type");
287 }
288 }
289
290 public static class UnsupportedAuthTokenTypeException extends
291 AuthenticatorException {
292 private static final long serialVersionUID = 1L;
293
294 public UnsupportedAuthTokenTypeException() {
295 super(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
296 "Unsupported auth token type");
297 }
298 }
299
300 public static class UnsupportedFeaturesException extends
301 AuthenticatorException {
302 public static final long serialVersionUID = 1L;
303
304 public UnsupportedFeaturesException() {
305 super(AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
306 "Unsupported features");
307 }
308 }
309
310 public static class AccessDeniedException extends AuthenticatorException {
311 public AccessDeniedException(int code, String errorMsg) {
312 super(AccountManager.ERROR_CODE_INVALID_RESPONSE, "Access Denied");
313 }
314
315 private static final long serialVersionUID = 1L;
316
317 }
318 }