42 lines
1.3 KiB
Dart
42 lines
1.3 KiB
Dart
import 'dart:convert';
|
|
import 'package:http/http.dart' as http;
|
|
import 'token_storage.dart';
|
|
|
|
class AuthRepository {
|
|
final String baseUrl;
|
|
final TokenStorage tokens;
|
|
AuthRepository(this.baseUrl, this.tokens);
|
|
|
|
Future<void> register(String email, String password) async {
|
|
final res = await http.post(Uri.parse('$baseUrl/auth/register'),
|
|
headers: {'Content-Type': 'application/json'},
|
|
body: jsonEncode({'email': email, 'password': password}));
|
|
if (res.statusCode != 201) {
|
|
throw Exception('Register failed: ${res.body}');
|
|
}
|
|
}
|
|
|
|
Future<void> login(String email, String password) async {
|
|
final res = await http.post(Uri.parse('$baseUrl/auth/login'),
|
|
headers: {'Content-Type': 'application/json'},
|
|
body: jsonEncode({'email': email, 'password': password}));
|
|
if (res.statusCode == 200) {
|
|
final m = jsonDecode(res.body) as Map<String, dynamic>;
|
|
await tokens.save(
|
|
m['access_token'] as String, m['refresh_token'] as String);
|
|
} else {
|
|
throw Exception('Login failed: ${res.body}');
|
|
}
|
|
}
|
|
|
|
Future<void> logout() async {
|
|
final r = await tokens.refresh;
|
|
if (r != null) {
|
|
await http.post(Uri.parse('$baseUrl/auth/logout'),
|
|
headers: {'Content-Type': 'application/json'},
|
|
body: jsonEncode({'refresh_token': r}));
|
|
}
|
|
await tokens.clear();
|
|
}
|
|
}
|