Skip to content

Commit bb67975

Browse files
committed
fix/refactor/simplify powersync auth setup
1 parent 9332bb1 commit bb67975

File tree

5 files changed

+19
-54
lines changed

5 files changed

+19
-54
lines changed

lib/api_client.dart

Lines changed: 0 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -14,32 +14,6 @@ class ApiClient {
1414

1515
const ApiClient(this.baseUrl);
1616

17-
Future<Map<String, dynamic>> authenticate(String username, String password) async {
18-
final response = await http.post(
19-
Uri.parse('$baseUrl/api/v2/login/'),
20-
headers: {'Content-Type': 'application/json'},
21-
body: json.encode({'username': username, 'password': password}),
22-
);
23-
if (response.statusCode == 200) {
24-
log.log(Level.ALL, response.body);
25-
return json.decode(response.body);
26-
}
27-
throw Exception('Failed to authenticate');
28-
}
29-
30-
Future<Map<String, dynamic>> getWgerJWTToken() async {
31-
final response = await http.post(
32-
Uri.parse('$baseUrl/api/v2/token'),
33-
headers: {HttpHeaders.contentTypeHeader: 'application/json'},
34-
body: json.encode({'username': 'admin', 'password': 'adminadmin'}), // FIXME
35-
);
36-
if (response.statusCode == 200) {
37-
log.log(Level.ALL, response.body);
38-
return json.decode(response.body);
39-
}
40-
throw Exception('Failed to fetch token');
41-
}
42-
4317
/// Returns a powersync JWT token token
4418
///
4519
/// Note that at the moment we use the permanent API token for authentication

lib/main.dart

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -77,11 +77,6 @@ void main() async {
7777
// Needs to be called before runApp
7878
WidgetsFlutterBinding.ensureInitialized();
7979

80-
await openDatabase();
81-
82-
final loggedIn = await isLoggedIn();
83-
print('main(): is logged in $loggedIn');
84-
8580
// Locator to initialize exerciseDB
8681
await ServiceLocator().configure();
8782
print('running myapp');

lib/powersync.dart

Lines changed: 4 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ import 'package:logging/logging.dart';
33
import 'package:path/path.dart';
44
import 'package:path_provider/path_provider.dart';
55
import 'package:powersync/powersync.dart';
6-
import 'package:shared_preferences/shared_preferences.dart';
76
import 'package:wger/api_client.dart';
87

98
import './app_config.dart';
@@ -37,6 +36,7 @@ class DjangoConnector extends PowerSyncBackendConnector {
3736
// https://docs.powersync.com/usage/installation/authentication-setup/custom
3837
// final wgerSession = await apiClient.getWgerJWTToken();
3938
final session = await apiClient.getPowersyncToken();
39+
// note: we don't set userId and expires property here. not sure if needed
4040
return PowerSyncCredentials(endpoint: AppConfig.powersyncUrl, token: session['token']);
4141
}
4242

@@ -86,37 +86,24 @@ late final PowerSyncDatabase db;
8686
// Hacky flag to ensure the database is only initialized once, better to do this with listeners
8787
bool _dbInitialized = false;
8888

89-
/// id of the user currently logged in
90-
Future<String?> getUserId() async {
91-
final prefs = await SharedPreferences.getInstance();
92-
return prefs.getString('id');
93-
}
94-
95-
Future<bool> isLoggedIn() async {
96-
final userId = await getUserId();
97-
return userId != null;
98-
}
99-
10089
Future<String> getDatabasePath() async {
10190
final dir = await getApplicationSupportDirectory();
10291
return join(dir.path, 'powersync-demo.db');
10392
}
10493

10594
// opens the database and connects if logged in
106-
Future<void> openDatabase() async {
95+
Future<void> openDatabase(bool connect) async {
10796
// Open the local database
10897
if (!_dbInitialized) {
10998
db = PowerSyncDatabase(schema: schema, path: await getDatabasePath(), logger: attachedLogger);
11099
await db.initialize();
111100
_dbInitialized = true;
112101
}
113102

114-
DjangoConnector? currentConnector;
115-
116-
if (await isLoggedIn()) {
103+
if (connect) {
117104
// If the user is already logged in, connect immediately.
118105
// Otherwise, connect once logged in.
119-
currentConnector = DjangoConnector(db);
106+
final currentConnector = DjangoConnector(db);
120107
db.connect(connector: currentConnector);
121108

122109
// TODO: should we respond to login state changing? like here:

lib/providers/auth.dart

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,7 @@ class AuthProvider with ChangeNotifier {
182182
}
183183

184184
// Log user in
185+
// should we update the backend to just include a powersync token also?
185186
token = responseData['token'];
186187
notifyListeners();
187188

lib/screens/home_tabs_screen.dart

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,8 @@ class _HomeTabsScreenState extends State<HomeTabsScreen> with SingleTickerProvid
5454
void initState() {
5555
super.initState();
5656

57-
final authProvider = context.read<AuthProvider>();
58-
print('auth provider says surverurl is ${authProvider.serverUrl}');
57+
// do we need to await this? or if it's async, how do we handle failures?
58+
_setupPowersync();
5959

6060
// Loading data here, since the build method can be called more than once
6161
_initialData = _loadEntries();
@@ -75,19 +75,27 @@ class _HomeTabsScreenState extends State<HomeTabsScreen> with SingleTickerProvid
7575
const GalleryScreen(),
7676
];
7777

78-
/// Load initial data from the server
79-
Future<void> _loadEntries() async {
78+
Future<void> _setupPowersync() async {
79+
final authProvider = context.read<AuthProvider>();
80+
print('auth provider says surverurl is ${authProvider.serverUrl}');
81+
await openDatabase(false);
82+
8083
final connector = DjangoConnector(db);
8184
try {
85+
// TODO: should we cache these credentials? that's what their demo does?
86+
// we could maybe get the initial token from the /api/v2/login call
8287
final credentials = await connector.fetchCredentials();
8388
print('----------');
8489
print(credentials);
8590
print('----------');
91+
await openDatabase(true);
8692
} catch (e) {
8793
print('fail' + e.toString());
8894
}
89-
final loggedIn = await isLoggedIn();
90-
print('_loadEntries(): is logged in $loggedIn');
95+
}
96+
97+
/// Load initial data from the server
98+
Future<void> _loadEntries() async {
9199
final authProvider = context.read<AuthProvider>();
92100

93101
if (!authProvider.dataInit) {

0 commit comments

Comments
 (0)