-
Notifications
You must be signed in to change notification settings - Fork 914
Expand file tree
/
Copy pathoauth2_utils.dart
More file actions
289 lines (259 loc) · 9.65 KB
/
oauth2_utils.dart
File metadata and controls
289 lines (259 loc) · 9.65 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
import 'dart:async';
import 'dart:io';
import 'package:oauth2/oauth2.dart' as oauth2;
import '../../models/auth/auth_oauth2_model.dart';
import '../../services/http_client_manager.dart';
import '../../services/oauth_callback_server.dart';
import '../platform_utils.dart';
/// Advanced OAuth2 authorization code grant handler that returns both the client and server
/// for cases where you need manual control over the callback server lifecycle.
///
/// Returns a tuple of (oauth2.Client, OAuthCallbackServer?) where the server is null for mobile platforms.
/// The server should be stopped by the caller to clean up resources.
Future<(oauth2.Client, OAuthCallbackServer?)> oAuth2AuthorizationCodeGrant({
required String identifier,
required String secret,
required Uri authorizationEndpoint,
required Uri tokenEndpoint,
required Uri redirectUrl,
required File? credentialsFile,
String? state,
String? scope,
}) async {
// Check for existing credentials first
if (credentialsFile != null && await credentialsFile.exists()) {
try {
final json = await credentialsFile.readAsString();
final credentials = oauth2.Credentials.fromJson(json);
if (credentials.accessToken.isNotEmpty && !credentials.isExpired) {
return (
oauth2.Client(credentials, identifier: identifier, secret: secret),
null,
);
}
} catch (e) {
// Ignore credential reading errors and continue with fresh authentication
}
}
// Create a unique request ID for this OAuth flow
final requestId = 'oauth2-${DateTime.now().millisecondsSinceEpoch}';
final httpClientManager = HttpClientManager();
final baseClient = httpClientManager.createClientWithJsonAccept(requestId);
OAuthCallbackServer? callbackServer;
Uri actualRedirectUrl = redirectUrl;
try {
// Use localhost callback server for desktop platforms
if (PlatformUtils.shouldUseLocalhostCallback) {
callbackServer = OAuthCallbackServer();
final localhostUrl = await callbackServer.start();
actualRedirectUrl = Uri.parse(localhostUrl);
}
final grant = oauth2.AuthorizationCodeGrant(
identifier,
authorizationEndpoint,
tokenEndpoint,
secret: secret,
httpClient: baseClient,
);
final authorizationUrl = grant.getAuthorizationUrl(
actualRedirectUrl,
scopes: scope != null ? [scope] : null,
state: state,
);
String callbackUri;
if (PlatformUtils.shouldUseLocalhostCallback && callbackServer != null) {
// For desktop: Open the authorization URL in the default browser
// and wait for the callback on the localhost server with a 3-minute timeout
await _openUrlInBrowser(authorizationUrl.toString());
try {
callbackUri = await callbackServer.waitForCallback(
timeout: const Duration(minutes: 3),
);
// Convert the relative callback to full URL
callbackUri =
'http://localhost${Uri.parse(callbackUri).path}${Uri.parse(callbackUri).query.isNotEmpty ? '?${Uri.parse(callbackUri).query}' : ''}';
} on TimeoutException {
throw Exception(
'OAuth authorization timed out after 3 minutes. '
'Please try again and complete the authorization in your browser. '
'If you closed the browser tab, please restart the OAuth flow.',
);
} catch (e) {
// Handle custom exceptions like browser tab closure
final errorMessage = e.toString();
if (errorMessage.contains('Browser tab was closed')) {
throw Exception(
'OAuth authorization was cancelled because the browser tab was closed. '
'Please try again and complete the authorization process without closing the browser tab.',
);
} else if (errorMessage.contains('OAuth callback cancelled')) {
throw Exception(
'OAuth authorization was cancelled. Please try again if you want to complete the authentication.',
);
} else {
throw Exception('OAuth authorization failed: $errorMessage');
}
}
} else {
throw UnsupportedError(
'OAuth authorization code grant is not supported in pure Dart CLI context. '
'Mobile platforms require flutter_web_auth_2 which is a Flutter dependency.',
);
}
// Parse the callback URI and handle the authorization response
final callbackUriParsed = Uri.parse(callbackUri);
final client = await grant.handleAuthorizationResponse(
callbackUriParsed.queryParameters,
);
if (credentialsFile != null) {
await credentialsFile.writeAsString(client.credentials.toJson());
}
return (client, callbackServer);
} catch (e) {
// Clean up the callback server immediately on error
if (callbackServer != null) {
try {
await callbackServer.stop();
} catch (serverError) {
// Ignore server cleanup errors
}
}
// Re-throw the original error
rethrow;
} finally {
// Clean up HTTP client
httpClientManager.closeClient(requestId);
}
}
Future<oauth2.Client> oAuth2ClientCredentialsGrantHandler({
required AuthOAuth2Model oauth2Model,
required File? credentialsFile,
}) async {
// Try to use saved credentials
if (credentialsFile != null && await credentialsFile.exists()) {
try {
final json = await credentialsFile.readAsString();
final credentials = oauth2.Credentials.fromJson(json);
if (credentials.accessToken.isNotEmpty && !credentials.isExpired) {
return oauth2.Client(
credentials,
identifier: oauth2Model.clientId,
secret: oauth2Model.clientSecret,
);
}
} catch (e) {
// Ignore credential reading errors and continue with fresh authentication
}
}
// Create a unique request ID for this OAuth flow
final requestId = 'oauth2-client-${DateTime.now().millisecondsSinceEpoch}';
final httpClientManager = HttpClientManager();
final baseClient = httpClientManager.createClientWithJsonAccept(requestId);
try {
// Otherwise, perform the client credentials grant
final client = await oauth2.clientCredentialsGrant(
Uri.parse(oauth2Model.accessTokenUrl),
oauth2Model.clientId,
oauth2Model.clientSecret,
scopes: oauth2Model.scope != null ? [oauth2Model.scope!] : null,
basicAuth: false,
httpClient: baseClient,
);
try {
if (credentialsFile != null) {
await credentialsFile.writeAsString(client.credentials.toJson());
}
} catch (e) {
// Ignore credential saving errors
}
// Clean up the HTTP client
httpClientManager.closeClient(requestId);
return client;
} catch (e) {
// Clean up the HTTP client on error
httpClientManager.closeClient(requestId);
rethrow;
}
}
Future<oauth2.Client> oAuth2ResourceOwnerPasswordGrantHandler({
required AuthOAuth2Model oauth2Model,
required File? credentialsFile,
}) async {
// Try to use saved credentials
if (credentialsFile != null && await credentialsFile.exists()) {
try {
final json = await credentialsFile.readAsString();
final credentials = oauth2.Credentials.fromJson(json);
if (credentials.accessToken.isNotEmpty && !credentials.isExpired) {
return oauth2.Client(
credentials,
identifier: oauth2Model.clientId,
secret: oauth2Model.clientSecret,
);
}
} catch (e) {
// Ignore credential reading errors and continue with fresh authentication
}
}
if ((oauth2Model.username == null || oauth2Model.username!.isEmpty) ||
(oauth2Model.password == null || oauth2Model.password!.isEmpty)) {
throw Exception("Username or Password cannot be empty");
}
// Create a unique request ID for this OAuth flow
final requestId = 'oauth2-password-${DateTime.now().millisecondsSinceEpoch}';
final httpClientManager = HttpClientManager();
final baseClient = httpClientManager.createClientWithJsonAccept(requestId);
try {
// Otherwise, perform the owner password grant
final client = await oauth2.resourceOwnerPasswordGrant(
Uri.parse(oauth2Model.accessTokenUrl),
oauth2Model.username!,
oauth2Model.password!,
identifier: oauth2Model.clientId,
secret: oauth2Model.clientSecret,
scopes: oauth2Model.scope != null ? [oauth2Model.scope!] : null,
basicAuth: false,
httpClient: baseClient,
);
try {
if (credentialsFile != null) {
await credentialsFile.writeAsString(client.credentials.toJson());
}
} catch (e) {
// Ignore credential saving errors
}
// Clean up the HTTP client
httpClientManager.closeClient(requestId);
return client;
} catch (e) {
// Clean up the HTTP client on error
httpClientManager.closeClient(requestId);
rethrow;
}
}
/// Opens a URL in the default system browser.
/// This is used for desktop platforms where we want to open the OAuth authorization URL
/// in the user's default browser and use localhost callback server to capture the response.
Future<void> _openUrlInBrowser(String url) async {
try {
if (PlatformUtils.isDesktop) {
Process? process;
if (Platform.isMacOS) {
process = await Process.start('open', [url]);
} else if (Platform.isWindows) {
process = await Process.start('rundll32', [
'url.dll,FileProtocolHandler',
url,
]);
} else if (Platform.isLinux) {
process = await Process.start('xdg-open', [url]);
}
if (process != null) {
await process.exitCode; // Wait for the process to complete
}
}
} catch (e) {
// Fallback: throw an exception so the calling code can handle it
throw Exception('Failed to open authorization URL in browser: $e');
}
}