| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124 |
- import 'package:shared_preferences/shared_preferences.dart';
- import 'package:dio/dio.dart';
- import 'package:flutter/material.dart';
-
- class AuthService extends ChangeNotifier {
- static const String _tokenKey = 'auth_token';
- static const String _userKey = 'user_info';
-
- String? _token;
- String? _userId;
- String? _userName;
- bool _isAuthenticated = false;
- bool _isLoading = false;
- final Dio _dio = Dio();
-
- String? get token => _token;
- String? get userId => _userId;
- String? get userName => _userName;
- bool get isAuthenticated => _isAuthenticated;
- bool get isLoading => _isLoading;
-
- AuthService() {
- _dio.options.baseUrl = 'http://your-api-domain.com/api';
- _dio.interceptors.add(
- InterceptorsWrapper(
- onRequest: (options, handler) {
- if (_token != null) {
- options.headers['Authorization'] = 'Bearer $_token';
- }
- handler.next(options);
- },
- ),
- );
- }
-
- Future<void> init() async {
- await loadStoredAuth();
- }
-
- Future<void> loadStoredAuth() async {
- try {
- final prefs = await SharedPreferences.getInstance();
- final token = prefs.getString(_tokenKey);
- final userJson = prefs.getString(_userKey);
-
- if (token != null && userJson != null) {
- _token = token;
- _parseUserInfo(userJson);
- _isAuthenticated = true;
- }
- } catch (e) {
- print('加载认证信息失败: $e');
- }
- notifyListeners();
- }
-
- void _parseUserInfo(String userJson) {
- try {
- // 这里解析用户信息,根据实际的API响应格式
- final user = userJson;
- _userId = 'user_id_from_json'; // 从JSON解析
- _userName = 'username_from_json'; // 从JSON解析
- } catch (e) {
- print('解析用户信息失败: $e');
- }
- }
-
- Future<bool> login(String username, String password) async {
- _isLoading = true;
- notifyListeners();
-
- try {
- final response = await _dio.post('/auth/login', data: {
- 'username': username,
- 'password': password,
- });
-
- if (response.statusCode == 200) {
- final data = response.data;
- _token = data['token'];
- _userId = data['user_id'];
- _userName = data['username'];
- _isAuthenticated = true;
-
- // 保存到本地存储
- final prefs = await SharedPreferences.getInstance();
- await prefs.setString(_tokenKey, _token!);
- await prefs.setString(_userKey, data.toString());
-
- notifyListeners();
- return true;
- } else {
- throw Exception('登录失败');
- }
- } catch (e) {
- print('登录错误: $e');
- return false;
- } finally {
- _isLoading = false;
- notifyListeners();
- }
- }
-
- Future<void> logout() async {
- try {
- // 调用登出API
- await _dio.post('/auth/logout');
- } catch (e) {
- print('登出API调用失败: $e');
- }
-
- // 清除本地数据
- _token = null;
- _userId = null;
- _userName = null;
- _isAuthenticated = false;
-
- final prefs = await SharedPreferences.getInstance();
- await prefs.remove(_tokenKey);
- await prefs.remove(_userKey);
-
- notifyListeners();
- }
- }
|