aslan-flutter/lib/chatvibe_managers/authentication_manager.dart
2026-07-01 18:25:58 +08:00

99 lines
3.2 KiB
Dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:aslan/chatvibe_core/routes/at_routes.dart';
import 'package:aslan/chatvibe_core/routes/at_fluro_navigator.dart';
import 'package:aslan/chatvibe_core/utilities/at_google_auth_utils.dart';
import 'package:aslan/chatvibe_core/utilities/at_loading_manager.dart';
import 'package:aslan/chatvibe_core/utilities/at_version_utils.dart';
import 'package:aslan/chatvibe_data/sources/local/user_manager.dart';
import 'package:aslan/chatvibe_data/sources/repositories/user_repository_impl.dart';
import 'package:aslan/chatvibe_domain/models/res/login_res.dart';
import '../chatvibe_data/models/enum/at_auth_type.dart';
class ChatVibeAuthenticationManager extends ChangeNotifier {
String authType = "";
String uid = "";
User? _user;
User? get user => _user;
bool get isSignedIn => _user != null;
ChatVibeAuthenticationManager() {
_init();
}
Future<void> _init() async {
await ATGoogleAuthService.prepareFunction();
await _checkExistingSession();
}
Future<void> _checkExistingSession() async {
final user = await ATGoogleAuthService.signInSilently();
_user = user;
notifyListeners();
}
Future<void> signIn(BuildContext context, String authType) async {
if (authType == ATAuthType.GOOGLE.name) {
this.authType = authType;
try {
_user ??= await ATGoogleAuthService.signInWithGoogleFunction();
uid = _user!.uid;
ATLoadingManager.exhibitOperation();
if (uid.isNotEmpty) {
Future.wait([
AccountRepository().loginForChannel(authType, uid),
ATVersionUtils.checkReview(),
]).then((res) {
var user = (res[0] as ChatVibeLoginRes);
AccountStorage().setCurrentUser(user);
ATLoadingManager.veilRoutine();
notifyListeners();
ATNavigatorUtils.push(context, ATRoutes.home, replace: true);
});
}
} catch (e) {
ATLoadingManager.veilRoutine();
rethrow;
}
} else if (authType == ATAuthType.APPLE.name) {
this.authType = authType;
try {
final appleCredential = await SignInWithApple.getAppleIDCredential(
scopes: [
AppleIDAuthorizationScopes.fullName, // 请求姓名权限
],
);
uid = appleCredential.userIdentifier ?? "";
ATLoadingManager.exhibitOperation();
if (uid.isNotEmpty) {
Future.wait([
AccountRepository().loginForChannel(authType, uid),
ATVersionUtils.checkReview(),
]).then((res) {
var user = (res[0] as ChatVibeLoginRes);
AccountStorage().setCurrentUser(user);
ATLoadingManager.veilRoutine();
notifyListeners();
ATNavigatorUtils.push(context, ATRoutes.home, replace: true);
});
}
} catch (e) {
ATLoadingManager.veilRoutine();
rethrow;
}
}
}
Future<void> signOut() async {
await ATGoogleAuthService.signOutMethod();
_user = null;
notifyListeners();
}
}