智慧水务管理系统 - 精河县供水工程综合管理平台

auth_service.dart 3.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. import 'package:shared_preferences/shared_preferences.dart';
  2. import 'package:dio/dio.dart';
  3. import 'package:flutter/material.dart';
  4. class AuthService extends ChangeNotifier {
  5. static const String _tokenKey = 'auth_token';
  6. static const String _userKey = 'user_info';
  7. String? _token;
  8. String? _userId;
  9. String? _userName;
  10. bool _isAuthenticated = false;
  11. bool _isLoading = false;
  12. final Dio _dio = Dio();
  13. String? get token => _token;
  14. String? get userId => _userId;
  15. String? get userName => _userName;
  16. bool get isAuthenticated => _isAuthenticated;
  17. bool get isLoading => _isLoading;
  18. AuthService() {
  19. _dio.options.baseUrl = 'http://your-api-domain.com/api';
  20. _dio.interceptors.add(
  21. InterceptorsWrapper(
  22. onRequest: (options, handler) {
  23. if (_token != null) {
  24. options.headers['Authorization'] = 'Bearer $_token';
  25. }
  26. handler.next(options);
  27. },
  28. ),
  29. );
  30. }
  31. Future<void> init() async {
  32. await loadStoredAuth();
  33. }
  34. Future<void> loadStoredAuth() async {
  35. try {
  36. final prefs = await SharedPreferences.getInstance();
  37. final token = prefs.getString(_tokenKey);
  38. final userJson = prefs.getString(_userKey);
  39. if (token != null && userJson != null) {
  40. _token = token;
  41. _parseUserInfo(userJson);
  42. _isAuthenticated = true;
  43. }
  44. } catch (e) {
  45. print('加载认证信息失败: $e');
  46. }
  47. notifyListeners();
  48. }
  49. void _parseUserInfo(String userJson) {
  50. try {
  51. // 这里解析用户信息,根据实际的API响应格式
  52. final user = userJson;
  53. _userId = 'user_id_from_json'; // 从JSON解析
  54. _userName = 'username_from_json'; // 从JSON解析
  55. } catch (e) {
  56. print('解析用户信息失败: $e');
  57. }
  58. }
  59. Future<bool> login(String username, String password) async {
  60. _isLoading = true;
  61. notifyListeners();
  62. try {
  63. final response = await _dio.post('/auth/login', data: {
  64. 'username': username,
  65. 'password': password,
  66. });
  67. if (response.statusCode == 200) {
  68. final data = response.data;
  69. _token = data['token'];
  70. _userId = data['user_id'];
  71. _userName = data['username'];
  72. _isAuthenticated = true;
  73. // 保存到本地存储
  74. final prefs = await SharedPreferences.getInstance();
  75. await prefs.setString(_tokenKey, _token!);
  76. await prefs.setString(_userKey, data.toString());
  77. notifyListeners();
  78. return true;
  79. } else {
  80. throw Exception('登录失败');
  81. }
  82. } catch (e) {
  83. print('登录错误: $e');
  84. return false;
  85. } finally {
  86. _isLoading = false;
  87. notifyListeners();
  88. }
  89. }
  90. Future<void> logout() async {
  91. try {
  92. // 调用登出API
  93. await _dio.post('/auth/logout');
  94. } catch (e) {
  95. print('登出API调用失败: $e');
  96. }
  97. // 清除本地数据
  98. _token = null;
  99. _userId = null;
  100. _userName = null;
  101. _isAuthenticated = false;
  102. final prefs = await SharedPreferences.getInstance();
  103. await prefs.remove(_tokenKey);
  104. await prefs.remove(_userKey);
  105. notifyListeners();
  106. }
  107. }