109 lines
2.9 KiB
Dart
109 lines
2.9 KiB
Dart
import 'package:firebase_auth/firebase_auth.dart';
|
|
import 'package:firebase_core/firebase_core.dart';
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:google_sign_in/google_sign_in.dart';
|
|
|
|
///谷歌授权登录
|
|
class SCGoogleAuthService {
|
|
static final GoogleSignIn _g = GoogleSignIn(scopes: ['email', 'profile']);
|
|
|
|
// 获取当前用户
|
|
static User? get currentUser => FirebaseAuth.instance.currentUser;
|
|
|
|
// 检查登录状态
|
|
static bool get isSignedIn => currentUser != null;
|
|
|
|
// 初始化Firebase
|
|
static Future<void> initialize() async {
|
|
if (Firebase.apps.isNotEmpty) {
|
|
return;
|
|
}
|
|
await Firebase.initializeApp();
|
|
}
|
|
|
|
// 谷歌登录
|
|
static Future<User?> signInWithGoogle() async {
|
|
try {
|
|
await initialize();
|
|
// 触发谷歌登录
|
|
final GoogleSignInAccount? googleAccount = await _g.signIn();
|
|
if (googleAccount == null) return null;
|
|
|
|
// 获取认证信息
|
|
final GoogleSignInAuthentication googleAuth =
|
|
await googleAccount.authentication;
|
|
|
|
// 创建Firebase凭证
|
|
final OAuthCredential credential = GoogleAuthProvider.credential(
|
|
accessToken: googleAuth.accessToken,
|
|
idToken: googleAuth.idToken,
|
|
);
|
|
|
|
// 使用凭证登录Firebase
|
|
final UserCredential userCredential = await FirebaseAuth.instance
|
|
.signInWithCredential(credential);
|
|
|
|
return userCredential.user;
|
|
} catch (e) {
|
|
debugPrint('Google sign-in error: $e');
|
|
rethrow; // 抛出异常让调用者处理
|
|
}
|
|
}
|
|
|
|
// 静默登录(检查现有会话)
|
|
static Future<User?> signInSilently() async {
|
|
try {
|
|
await initialize();
|
|
// 尝试静默登录
|
|
final GoogleSignInAccount? googleAccount = await _g.signInSilently();
|
|
|
|
if (googleAccount == null) return null;
|
|
|
|
// 获取认证信息
|
|
final GoogleSignInAuthentication googleAuth =
|
|
await googleAccount.authentication;
|
|
|
|
// 创建Firebase凭证
|
|
final OAuthCredential credential = GoogleAuthProvider.credential(
|
|
accessToken: googleAuth.accessToken,
|
|
idToken: googleAuth.idToken,
|
|
);
|
|
|
|
// 使用凭证登录Firebase
|
|
final UserCredential userCredential = await FirebaseAuth.instance
|
|
.signInWithCredential(credential);
|
|
|
|
return userCredential.user;
|
|
} catch (e) {
|
|
debugPrint('Silent sign-in error: $e');
|
|
return null;
|
|
}
|
|
}
|
|
|
|
// 登出
|
|
static Future<void> signOut() async {
|
|
try {
|
|
await initialize();
|
|
await _g.signOut();
|
|
await FirebaseAuth.instance.signOut();
|
|
} catch (e) {
|
|
debugPrint('Sign out error: $e');
|
|
rethrow;
|
|
}
|
|
}
|
|
|
|
// 获取用户信息
|
|
static Map<String, dynamic>? getUserInfo() {
|
|
final user = currentUser;
|
|
if (user == null) return null;
|
|
|
|
return {
|
|
'uid': user.uid,
|
|
'name': user.displayName,
|
|
'email': user.email,
|
|
'photoUrl': user.photoURL,
|
|
'isEmailVerified': user.emailVerified,
|
|
};
|
|
}
|
|
}
|