87 lines
2.3 KiB
Dart
87 lines
2.3 KiB
Dart
import 'dart:convert';
|
|
import 'package:dio/dio.dart';
|
|
import '../../../core/api/api_client.dart';
|
|
import '../../../core/storage/token_store.dart';
|
|
|
|
class AppUser {
|
|
final String id;
|
|
final String phone;
|
|
final String? name;
|
|
final String role;
|
|
|
|
AppUser({required this.id, required this.phone, this.name, required this.role});
|
|
|
|
factory AppUser.fromJson(Map<String, dynamic> j) => AppUser(
|
|
id: j['id'] as String,
|
|
phone: (j['phone'] ?? '') as String,
|
|
name: j['name'] as String?,
|
|
role: (j['role'] ?? 'rider') as String,
|
|
);
|
|
|
|
Map<String, dynamic> toJson() => {
|
|
'id': id,
|
|
'phone': phone,
|
|
'name': name,
|
|
'role': role,
|
|
};
|
|
}
|
|
|
|
class AuthRepository {
|
|
final ApiClient _api;
|
|
final TokenStore _store;
|
|
|
|
AuthRepository(this._api, this._store);
|
|
|
|
Future<void> sendOtp(String phone) async {
|
|
await _api.dio.post('/auth/send-otp', data: {'phone': phone});
|
|
}
|
|
|
|
Future<AppUser> verify(String phone, String code) async {
|
|
final r = await _api.dio.post(
|
|
'/auth/verify-otp',
|
|
data: {'phone': phone, 'code': code},
|
|
);
|
|
await _store.save(
|
|
r.data['access_token'] as String,
|
|
r.data['refresh_token'] as String,
|
|
);
|
|
final user = AppUser.fromJson(Map<String, dynamic>.from(r.data['user'] as Map));
|
|
await _store.saveUser(jsonEncode(user.toJson()));
|
|
return user;
|
|
}
|
|
|
|
Future<AppUser?> getCachedUser() async {
|
|
final raw = await _store.readUser();
|
|
if (raw == null || raw.isEmpty) return null;
|
|
try {
|
|
final map = jsonDecode(raw) as Map<String, dynamic>;
|
|
return AppUser.fromJson(map);
|
|
} catch (_) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
Future<bool> hasSavedToken() => _store.hasToken();
|
|
|
|
Future<AppUser?> me() async {
|
|
try {
|
|
final r = await _api.dio.get('/users/me');
|
|
final user = AppUser.fromJson(Map<String, dynamic>.from(r.data as Map));
|
|
await _store.saveUser(jsonEncode(user.toJson()));
|
|
return user;
|
|
} on DioException {
|
|
return getCachedUser();
|
|
}
|
|
}
|
|
|
|
Future<void> logout() => _store.clear();
|
|
|
|
Future<AppUser> updateName(String name) async {
|
|
final r = await _api.dio.patch('/users/me', data: {'name': name});
|
|
final user = AppUser.fromJson(Map<String, dynamic>.from(r.data as Map));
|
|
await _store.saveUser(jsonEncode(user.toJson()));
|
|
return user;
|
|
}
|
|
}
|
|
|