55 lines
1.7 KiB
Dart
55 lines
1.7 KiB
Dart
import 'package:flutter_web_auth_2/flutter_web_auth_2.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
import '../config/api_config.dart';
|
|
|
|
class AuthService {
|
|
static const String _tokenKey = 'access_token';
|
|
static const String _accountKey = 'selected_account';
|
|
|
|
Future<String?> getStoredToken() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
return prefs.getString(_tokenKey);
|
|
}
|
|
|
|
Future<String?> getStoredAccount() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
return prefs.getString(_accountKey);
|
|
}
|
|
|
|
Future<String?> login() async {
|
|
final result = await FlutterWebAuth2.authenticate(
|
|
url: '${ApiConfig.baseUrl}/login?redirect_uri=${Uri.encodeComponent('myice://callback')}',
|
|
callbackUrlScheme: 'myice',
|
|
);
|
|
|
|
final uri = Uri.parse(result);
|
|
// Check for authorization errors first
|
|
final error = uri.queryParameters['error'];
|
|
if (error != null) {
|
|
throw Exception('Authorization failed: $error');
|
|
}
|
|
// Extract token from fragment (#access_token=...)
|
|
final fragment = uri.fragment;
|
|
final params = Uri.splitQueryString(fragment);
|
|
final token = params['access_token'];
|
|
|
|
if (token != null) {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
await prefs.setString(_tokenKey, token);
|
|
}
|
|
|
|
return token;
|
|
}
|
|
|
|
Future<void> setAccount(String account) async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
await prefs.setString(_accountKey, account);
|
|
}
|
|
|
|
Future<void> logout() async {
|
|
final prefs = await SharedPreferences.getInstance();
|
|
await prefs.remove(_tokenKey);
|
|
await prefs.remove(_accountKey);
|
|
}
|
|
}
|