Skip to content

Commit 5461139

Browse files
feat: replace parameters with config object [#120] (#134)
* feat: replace parameters with config object [#120] fix: rename classes to make clearer what's going on [#120] fix: get readme up to date [#120] fix: mark auth_config as immutable [#120] fix: move oauthredirect back into constants [#120] fix: override config in clerkauthstate [#120] fix: move localizations away from dependence on materialapp [#120] fix: improvements to clerkerrorlistener [#120] fix: pr changes fix: move localization finding into clerkauthstate [#120] Revert "fix: move localization finding into clerkauthstate [#120]" This reverts commit c0a5d66. fix: move localization finding into authstate [#120] fix: rename auth as authstate in remaining places [#120] * fix: pr changes --------- Co-authored-by: Simon Lightfoot <[email protected]>
1 parent 936fa55 commit 5461139

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

48 files changed

+791
-765
lines changed

packages/clerk_auth/.gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,6 @@ pubspec.lock
2222
# Flutter auto-generated files
2323
.flutter-plugins
2424
.flutter-plugins-dependencies
25+
26+
# Persistor file
27+
clerk_sdk.json

packages/clerk_auth/README.md

+10-12
Original file line numberDiff line numberDiff line change
@@ -32,30 +32,28 @@ import 'package:clerk_auth/clerk_auth.dart';
3232
3333
Future<void> main() async {
3434
final auth = Auth(
35-
publishableKey: '<YOUR-PUBLISHABLE-KEY>',
35+
config: const AuthConfig(
36+
publishableKey: '<YOUR-PUBLISHABLE-KEY>',
37+
),
3638
persistor: await DefaultPersistor.create(
3739
storageDirectory: Directory.current,
3840
),
3941
);
4042
41-
Client client;
43+
await auth.initialize();
4244
43-
client = await auth.attemptSignIn(
45+
await auth.attemptSignIn(
4446
strategy: Strategy.password,
4547
identifier: '<USER-EMAIL>',
46-
);
47-
assert(client.signIn?.status == Status.needsFirstFactor);
48-
49-
client = await auth.attemptSignIn(
50-
strategy: Strategy.password,
5148
password: '<PASSWORD>',
5249
);
5350
54-
assert(client.signIn == null);
55-
assert(client.activeSession?.status == Status.active);
56-
assert(client.activeSession?.publicUserData.identifier.isNotEmpty == true);
57-
}
51+
print('Signed in as ${auth.user}');
52+
53+
await auth.signOut();
5854
55+
auth.terminate();
56+
}
5957
```
6058

6159
For more details see [Clerk Auth object](https://pub.dev/documentation/clerk_auth/latest/clerk_auth/Auth-class.html)

packages/clerk_auth/example/main.dart

+12-11
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,30 @@
1+
// ignore_for_file: avoid_print
2+
13
import 'dart:io';
24

35
import 'package:clerk_auth/clerk_auth.dart';
46

57
Future<void> main() async {
68
final auth = Auth(
7-
publishableKey: '<YOUR-PUBLISHABLE-KEY>',
9+
config: const AuthConfig(
10+
publishableKey: '<YOUR-PUBLISHABLE-KEY>',
11+
),
812
persistor: await DefaultPersistor.create(
913
storageDirectory: Directory.current,
1014
),
1115
);
1216

13-
Client client;
17+
await auth.initialize();
1418

15-
client = await auth.attemptSignIn(
19+
await auth.attemptSignIn(
1620
strategy: Strategy.password,
1721
identifier: '<USER-EMAIL>',
18-
);
19-
assert(client.signIn?.status == Status.needsFirstFactor);
20-
21-
client = await auth.attemptSignIn(
22-
strategy: Strategy.password,
2322
password: '<PASSWORD>',
2423
);
2524

26-
assert(client.signIn == null);
27-
assert(client.activeSession?.status == Status.active);
28-
assert(client.activeSession?.publicUserData.identifier.isNotEmpty == true);
25+
print('Signed in as ${auth.user}');
26+
27+
await auth.signOut();
28+
29+
auth.terminate();
2930
}

packages/clerk_auth/lib/clerk_auth.dart

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
/// Package that will allow you to authenticate and use Clerk from Dart code.
22
library clerk_auth;
33

4-
export 'src/clerk_api/api.dart' show ClerkLocalesLookup;
54
export 'src/clerk_api/telemetry.dart';
65
export 'src/clerk_auth/auth.dart';
6+
export 'src/clerk_auth/auth_config.dart';
77
export 'src/clerk_auth/auth_error.dart';
88
export 'src/clerk_auth/http_service.dart';
99
export 'src/clerk_auth/persistor.dart';

packages/clerk_auth/lib/src/clerk_api/api.dart

+18-48
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import 'dart:convert';
33
import 'dart:io' show File, HttpHeaders, HttpStatus;
44

55
import 'package:clerk_auth/src/clerk_api/token_cache.dart';
6+
import 'package:clerk_auth/src/clerk_auth/auth_config.dart';
67
import 'package:clerk_auth/src/clerk_auth/http_service.dart';
78
import 'package:clerk_auth/src/clerk_auth/persistor.dart';
89
import 'package:clerk_auth/src/clerk_constants.dart';
@@ -15,65 +16,36 @@ import 'package:http/http.dart' as http;
1516

1617
export 'package:clerk_auth/src/models/enums.dart' show SessionTokenPollMode;
1718

18-
/// Used by [Api] to locate the current user locale preference.
19-
typedef ClerkLocalesLookup = List<String> Function();
20-
2119
/// [Api] manages communication with the Clerk frontend API
2220
///
2321
class Api with Logging {
24-
Api._(
25-
this._tokenCache,
26-
this._domain,
27-
this._httpService,
28-
this._localesLookup,
29-
this._pollMode,
30-
);
31-
32-
/// Create an [Api] object for a given Publishable Key, or return the existing one
33-
/// if such already exists for that key. Requires a [publishableKey]
34-
/// found in the Clerk dashboard for you account. Additional arguments:
35-
///
36-
/// [persistor]: an optional instance of a [Persistor] which will keep track of
37-
/// tokens and expiry between app activations
38-
///
39-
/// [client]: an optional instance of [HttpService] to manage low-level communications
40-
/// with the back end. Injected for e.g. test mocking
41-
///
42-
/// [pollMode]: session token poll mode, default [SessionTokenPollMode.lazy],
43-
/// manages how to refresh the [sessionToken].
22+
/// Create an [Api] object
4423
///
45-
factory Api({
46-
required String publishableKey,
24+
Api({
25+
required AuthConfig config,
4726
required Persistor persistor,
4827
required HttpService httpService,
49-
required ClerkLocalesLookup localesLookup,
50-
SessionTokenPollMode pollMode = SessionTokenPollMode.lazy,
51-
}) =>
52-
Api._(
53-
TokenCache(
28+
}) : _config = config,
29+
_tokenCache = TokenCache(
5430
persistor: persistor,
55-
cacheId: publishableKey.hashCode,
31+
publishableKey: config.publishableKey,
5632
),
57-
_deriveDomainFrom(publishableKey),
58-
httpService,
59-
localesLookup,
60-
pollMode,
61-
);
33+
_httpService = httpService,
34+
_domain = _deriveDomainFrom(config.publishableKey),
35+
_testMode = config.isTestMode;
6236

37+
final AuthConfig _config;
6338
final TokenCache _tokenCache;
64-
final String _domain;
6539
final HttpService _httpService;
66-
final ClerkLocalesLookup _localesLookup;
67-
final SessionTokenPollMode _pollMode;
68-
late final String _nativeDeviceId;
40+
final String _domain;
41+
42+
bool _testMode;
6943
Timer? _pollTimer;
7044
bool _multiSessionMode = true;
71-
bool _testMode = ClerkConstants.isTestMode;
7245

7346
static const _kClerkAPIVersion = 'clerk-api-version';
7447
static const _kClerkClientId = 'x-clerk-client-id';
7548
static const _kClerkJsVersion = '_clerk_js_version';
76-
static const _kClerkNativeDeviceId = 'x-native-device-id';
7749
static const _kClerkSessionId = '_clerk_session_id';
7850
static const _kClientKey = 'client';
7951
static const _kErrorsKey = 'errors';
@@ -90,8 +62,7 @@ class Api with Logging {
9062
/// Initialise the API
9163
Future<void> initialize() async {
9264
await _tokenCache.initialize();
93-
_nativeDeviceId = 'PENDING'; // TODO get this value
94-
if (_pollMode == SessionTokenPollMode.hungry) {
65+
if (_config.sessionTokenPollMode == SessionTokenPollMode.hungry) {
9566
await _pollForSessionToken();
9667
}
9768
}
@@ -115,7 +86,7 @@ class Api with Logging {
11586
final body = json.decode(resp.body) as Map<String, dynamic>;
11687
final env = Environment.fromJson(body);
11788

118-
_testMode = env.config.testMode || ClerkConstants.isTestMode;
89+
_testMode = env.config.testMode && _config.isTestMode;
11990
_multiSessionMode = env.config.singleSessionMode == false;
12091

12192
return env;
@@ -492,7 +463,7 @@ class Api with Logging {
492463

493464
/// Update details pertaining to the current [User]
494465
///
495-
Future<ApiResponse> updateUser(User user, AuthConfig config) async {
466+
Future<ApiResponse> updateUser(User user, Config config) async {
496467
return await _fetchApiResponse(
497468
'/me',
498469
method: HttpMethod.patch,
@@ -902,7 +873,7 @@ class Api with Logging {
902873
}) {
903874
return {
904875
HttpHeaders.acceptHeader: 'application/json',
905-
HttpHeaders.acceptLanguageHeader: _localesLookup().join(', '),
876+
HttpHeaders.acceptLanguageHeader: _config.localesLookup().join(', '),
906877
HttpHeaders.contentTypeHeader: method.isGet
907878
? 'application/json'
908879
: 'application/x-www-form-urlencoded',
@@ -912,7 +883,6 @@ class Api with Logging {
912883
_kXFlutterSDKVersion: ClerkConstants.flutterSdkVersion,
913884
if (_testMode) //
914885
_kClerkClientId: _tokenCache.clientId,
915-
_kClerkNativeDeviceId: _nativeDeviceId,
916886
_kXMobile: '1',
917887
...?headers,
918888
};

packages/clerk_auth/lib/src/clerk_api/telemetry.dart

+22-40
Original file line numberDiff line numberDiff line change
@@ -2,71 +2,53 @@ import 'dart:async';
22
import 'dart:convert';
33
import 'dart:io';
44

5-
import 'package:clerk_auth/src/clerk_auth/http_service.dart';
6-
import 'package:clerk_auth/src/clerk_auth/persistor.dart';
7-
import 'package:clerk_auth/src/clerk_constants.dart';
8-
import 'package:clerk_auth/src/models/enums.dart';
5+
import 'package:clerk_auth/clerk_auth.dart';
96
import 'package:clerk_auth/src/models/telemetry/telemetric_event.dart';
10-
import 'package:clerk_auth/src/utils/logging.dart';
117

128
/// Telemetry
139
///
1410
class Telemetry with Logging {
15-
Telemetry._(
16-
this._publishableKey,
17-
this._persistor,
18-
this._httpService,
19-
this._sendTelemetryData,
20-
);
21-
2211
/// Create a [Telemetry] object
23-
factory Telemetry({
24-
required String publishableKey,
25-
required Persistor persistor,
26-
required HttpService httpService,
27-
required bool sendTelemetryData,
28-
}) {
29-
return Telemetry._(
30-
publishableKey,
31-
persistor,
32-
httpService,
33-
sendTelemetryData,
34-
);
35-
}
12+
Telemetry({
13+
required this.config,
14+
required this.persistor,
15+
required this.httpService,
16+
});
17+
18+
/// The config used to initialise this telemetry instance.
19+
final AuthConfig config;
20+
21+
/// The [Persistor] used for Telemetry to store its event queue.
22+
final Persistor persistor;
23+
24+
/// The [HttpService] used to send the telemetry events.
25+
final HttpService httpService;
3626

37-
final bool _sendTelemetryData;
38-
final String _publishableKey;
39-
final Persistor _persistor;
40-
final HttpService _httpService;
4127
late final InstanceType _instanceType;
28+
late final _telemetryEndpoint = Uri.parse(config.telemetryEndpoint);
4229
Timer? _timer;
4330
final _telemetricEventsQueue = <TelemetricEvent>[];
4431

4532
static const _kTelemetricEventQueueKey = 'telemetricEventQueue';
4633
static const _telemetricEventsQueueMaxLength = 2000;
47-
static const _telemetryPeriod =
48-
Duration(milliseconds: ClerkConstants.telemetryPeriod);
49-
static final _telemetryEndpoint = Uri.parse(ClerkConstants.telemetryEndpoint);
5034

5135
/// Are we telemetricising?
5236
bool get isEnabled =>
53-
_sendTelemetryData &&
54-
_instanceType.isDevelopment &&
55-
ClerkConstants.isTelemetryEnabled;
37+
config.telemetryPeriod.isNotZero && _instanceType.isDevelopment;
5638

5739
/// Initialise telemetry
5840
Future<void> initialize({required InstanceType instanceType}) async {
5941
_instanceType = instanceType;
6042
if (isEnabled) {
61-
final data = await _persistor.read<String>(_kTelemetricEventQueueKey);
43+
final data = await persistor.read<String>(_kTelemetricEventQueueKey);
6244
if (data case String data) {
6345
final jsonList = json.decode(data) as List<dynamic>;
6446
final eventList = jsonList.map(
6547
(data) => TelemetricEvent.fromJson(data as Map<String, dynamic>),
6648
);
6749
_telemetricEventsQueue.addAll(eventList);
6850
}
69-
_timer = Timer.periodic(_telemetryPeriod, _sendTelemetry);
51+
_timer = Timer.periodic(config.telemetryPeriod, _sendTelemetry);
7052
}
7153
}
7254

@@ -98,7 +80,7 @@ class Telemetry with Logging {
9880
if (excess > 0) {
9981
_telemetricEventsQueue.removeRange(0, excess);
10082
}
101-
_persistor.write(
83+
persistor.write(
10284
_kTelemetricEventQueueKey,
10385
json.encode(_telemetricEventsQueue),
10486
);
@@ -108,7 +90,7 @@ class Telemetry with Logging {
10890
return {
10991
'event': event.event,
11092
'it': _instanceType.toString(),
111-
'pk': _publishableKey,
93+
'pk': config.publishableKey,
11294
'cv': ClerkConstants.clerkApiVersion,
11395
'sdk': ClerkConstants.sdkName,
11496
'sdkv': ClerkConstants.flutterSdkVersion,
@@ -123,7 +105,7 @@ class Telemetry with Logging {
123105
final events = [..._telemetricEventsQueue];
124106
if (events.isNotEmpty) {
125107
_telemetricEventsQueue.clear();
126-
final resp = await _httpService.send(
108+
final resp = await httpService.send(
127109
HttpMethod.post,
128110
_telemetryEndpoint,
129111
body: json.encode({

packages/clerk_auth/lib/src/clerk_api/token_cache.dart

+5-8
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,7 @@
11
import 'dart:convert';
22
import 'dart:io';
33

4-
import 'package:clerk_auth/src/clerk_auth/persistor.dart';
5-
import 'package:clerk_auth/src/models/client/client.dart';
6-
import 'package:clerk_auth/src/models/client/organization.dart';
7-
import 'package:clerk_auth/src/models/client/session.dart';
8-
import 'package:clerk_auth/src/models/client/session_token.dart';
4+
import 'package:clerk_auth/clerk_auth.dart';
95
import 'package:http/http.dart' as http;
106

117
/// A store for authentication tokens and IDs from the
@@ -18,9 +14,10 @@ class TokenCache {
1814
///
1915
TokenCache({
2016
required Persistor persistor,
21-
required int cacheId,
22-
}) : _persistor = persistor,
23-
_cacheId = cacheId;
17+
required String publishableKey,
18+
}) //
19+
: _persistor = persistor,
20+
_cacheId = publishableKey.hashCode;
2421

2522
final Persistor _persistor;
2623
final int _cacheId;

0 commit comments

Comments
 (0)