58 lines
1.6 KiB
Dart
58 lines
1.6 KiB
Dart
import 'package:daily_ledger/helper/AuthServices.dart';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
class AuthProvider with ChangeNotifier {
|
|
final AuthService _authService = AuthService();
|
|
String? _token;
|
|
String? _refreshToken;
|
|
|
|
String? get token => _token;
|
|
|
|
bool get isAuth {
|
|
return token != null;
|
|
}
|
|
|
|
Future<void> login(String username, String password) async {
|
|
final response = await _authService.login(username, password);
|
|
if (response['access'] != null) {
|
|
_token = response['access'];
|
|
_refreshToken =
|
|
response['refresh']; // Assuming refresh token is also returned
|
|
await _saveTokens(_token!, _refreshToken!);
|
|
notifyListeners();
|
|
} else {
|
|
throw Exception('Failed to log in');
|
|
}
|
|
}
|
|
|
|
Future<void> logout() async {
|
|
_token = null;
|
|
_refreshToken = null;
|
|
await _clearTokens();
|
|
notifyListeners();
|
|
}
|
|
|
|
Future<void> _saveTokens(String token, String refreshToken) async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
await prefs.setString('token', token);
|
|
await prefs.setString('refreshToken', refreshToken);
|
|
}
|
|
|
|
Future<void> _clearTokens() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
await prefs.remove('token');
|
|
await prefs.remove('refreshToken');
|
|
}
|
|
|
|
Future<void> autoLogin() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
if (prefs.containsKey('token')) {
|
|
_token = prefs.getString('token');
|
|
_refreshToken =
|
|
prefs.getString('refreshToken'); // Load refresh token if needed
|
|
notifyListeners();
|
|
}
|
|
}
|
|
}
|