forked from pockethub/PocketHub
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAccountUtils.java
More file actions
354 lines (311 loc) · 12 KB
/
AccountUtils.java
File metadata and controls
354 lines (311 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/*
* Copyright 2012 GitHub Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.mobile.accounts;
import static android.accounts.AccountManager.KEY_ACCOUNT_NAME;
import static android.content.DialogInterface.BUTTON_POSITIVE;
import static android.util.Log.DEBUG;
import static com.github.mobile.accounts.AccountConstants.ACCOUNT_TYPE;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerFuture;
import android.accounts.AccountsException;
import android.accounts.AuthenticatorDescription;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import com.github.mobile.R.string;
import com.github.mobile.ui.LightAlertDialog;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.egit.github.core.User;
import org.eclipse.egit.github.core.client.RequestException;
/**
* Helpers for accessing {@link AccountManager}
*/
public class AccountUtils {
private static final String TAG = "AccountUtils";
private static boolean AUTHENTICATOR_CHECKED;
private static boolean HAS_AUTHENTICATOR;
private static final AtomicInteger UPDATE_COUNT = new AtomicInteger(0);
private static class AuthenticatorConflictException extends IOException {
private static final long serialVersionUID = 641279204734869183L;
}
/**
* Verify authenticator registered for account type matches the package name
* of this application
*
* @param manager
* @return true is authenticator registered, false otherwise
*/
public static boolean hasAuthenticator(final AccountManager manager) {
if (!AUTHENTICATOR_CHECKED) {
final AuthenticatorDescription[] types = manager
.getAuthenticatorTypes();
if (types != null && types.length > 0)
for (AuthenticatorDescription descriptor : types)
if (descriptor != null
&& ACCOUNT_TYPE.equals(descriptor.type)) {
HAS_AUTHENTICATOR = "com.github.mobile"
.equals(descriptor.packageName);
break;
}
AUTHENTICATOR_CHECKED = true;
}
return HAS_AUTHENTICATOR;
}
/**
* Is the given user the owner of the default account?
*
* @param context
* @param user
* @return true if default account user, false otherwise
*/
public static boolean isUser(final Context context, final User user) {
if (user == null)
return false;
String login = user.getLogin();
if (login == null)
return false;
return login.equals(getLogin(context));
}
/**
* Get login name of configured account
*
* @param context
* @return login name or null if none configure
*/
public static String getLogin(final Context context) {
final Account account = getAccount(context);
return account != null ? account.name : null;
}
/**
* Get configured account
*
* @param context
* @return account or null if none
*/
public static Account getAccount(final Context context) {
final Account[] accounts = AccountManager.get(context)
.getAccountsByType(ACCOUNT_TYPE);
return accounts.length > 0 ? accounts[0] : null;
}
private static Account[] getAccounts(final AccountManager manager)
throws OperationCanceledException, AuthenticatorException,
IOException {
final AccountManagerFuture<Account[]> future = manager
.getAccountsByTypeAndFeatures(ACCOUNT_TYPE, null, null, null);
final Account[] accounts = future.getResult();
if (accounts != null && accounts.length > 0)
return getPasswordAccessibleAccounts(manager, accounts);
else
return new Account[0];
}
/**
* Get default account where password can be retrieved
*
* @param context
* @return password accessible account or null if none
*/
public static Account getPasswordAccessibleAccount(final Context context) {
AccountManager manager = AccountManager.get(context);
Account[] accounts = manager.getAccountsByType(ACCOUNT_TYPE);
if (accounts == null || accounts.length == 0)
return null;
try {
accounts = getPasswordAccessibleAccounts(manager, accounts);
} catch (AuthenticatorConflictException e) {
return null;
}
return accounts != null && accounts.length > 0 ? accounts[0] : null;
}
private static Account[] getPasswordAccessibleAccounts(
final AccountManager manager, final Account[] candidates)
throws AuthenticatorConflictException {
final List<Account> accessible = new ArrayList<Account>(
candidates.length);
boolean exceptionThrown = false;
for (Account account : candidates)
try {
manager.getPassword(account);
accessible.add(account);
} catch (SecurityException ignored) {
exceptionThrown = true;
}
if (accessible.isEmpty() && exceptionThrown)
throw new AuthenticatorConflictException();
return accessible.toArray(new Account[accessible.size()]);
}
/**
* Get account used for authentication
*
* @param manager
* @param activity
* @return account
* @throws IOException
* @throws AccountsException
*/
public static Account getAccount(final AccountManager manager,
final Activity activity) throws IOException, AccountsException {
final boolean loggable = Log.isLoggable(TAG, DEBUG);
if (loggable)
Log.d(TAG, "Getting account");
if (activity == null)
throw new IllegalArgumentException("Activity cannot be null");
if (activity.isFinishing())
throw new OperationCanceledException();
Account[] accounts;
try {
if (!hasAuthenticator(manager))
throw new AuthenticatorConflictException();
while ((accounts = getAccounts(manager)).length == 0) {
if (loggable)
Log.d(TAG, "No GitHub accounts for activity=" + activity);
Bundle result = manager.addAccount(ACCOUNT_TYPE, null, null,
null, activity, null, null).getResult();
if (loggable)
Log.d(TAG,
"Added account "
+ result.getString(KEY_ACCOUNT_NAME));
}
} catch (OperationCanceledException e) {
Log.d(TAG, "Excepting retrieving account", e);
activity.finish();
throw e;
} catch (AccountsException e) {
Log.d(TAG, "Excepting retrieving account", e);
throw e;
} catch (AuthenticatorConflictException e) {
activity.runOnUiThread(new Runnable() {
public void run() {
showConflictMessage(activity);
}
});
throw e;
} catch (IOException e) {
Log.d(TAG, "Excepting retrieving account", e);
throw e;
}
if (loggable)
Log.d(TAG, "Returning account " + accounts[0].name);
return accounts[0];
}
/**
* Update account
*
* @param account
* @param activity
* @return true if account was updated, false otherwise
*/
public static boolean updateAccount(final Account account,
final Activity activity) {
int count = UPDATE_COUNT.get();
synchronized (UPDATE_COUNT) {
// Don't update the account if the account was successfully updated
// while the lock was being waited for
if (count != UPDATE_COUNT.get())
return true;
AccountManager manager = AccountManager.get(activity);
try {
if (!hasAuthenticator(manager))
throw new AuthenticatorConflictException();
manager.updateCredentials(account, ACCOUNT_TYPE, null,
activity, null, null).getResult();
UPDATE_COUNT.incrementAndGet();
return true;
} catch (OperationCanceledException e) {
Log.d(TAG, "Excepting retrieving account", e);
activity.finish();
return false;
} catch (AccountsException e) {
Log.d(TAG, "Excepting retrieving account", e);
return false;
} catch (AuthenticatorConflictException e) {
activity.runOnUiThread(new Runnable() {
public void run() {
showConflictMessage(activity);
}
});
return false;
} catch (IOException e) {
Log.d(TAG, "Excepting retrieving account", e);
return false;
}
}
}
/**
* Show conflict message about previously registered authenticator from
* another application
*
* @param activity
*/
private static void showConflictMessage(final Activity activity) {
AlertDialog dialog = LightAlertDialog.create(activity);
dialog.setTitle(activity.getString(string.authenticator_conflict_title));
dialog.setMessage(activity
.getString(string.authenticator_conflict_message));
dialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
activity.finish();
}
});
dialog.setButton(BUTTON_POSITIVE,
activity.getString(android.R.string.ok), new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
activity.finish();
}
});
dialog.show();
}
/**
* Is the given {@link Exception} due to a 401 Unauthorized API response?
*
* @param e
* @return true if 401, false otherwise
*/
public static boolean isUnauthorized(final Exception e) {
if (e instanceof RequestException)
return ((RequestException) e).getStatus() == HTTP_UNAUTHORIZED;
String message = null;
if (e instanceof IOException)
message = e.getMessage();
final Throwable cause = e.getCause();
if (cause instanceof IOException) {
String causeMessage = cause.getMessage();
if (!TextUtils.isEmpty(causeMessage))
message = causeMessage;
}
if (TextUtils.isEmpty(message))
return false;
if ("Received authentication challenge is null".equals(message))
return true;
if ("No authentication challenges found".equals(message))
return true;
return false;
}
}