63 lines
1.7 KiB
Dart
63 lines
1.7 KiB
Dart
import 'package:firebase_auth/firebase_auth.dart';
|
|
import 'package:cloud_firestore/cloud_firestore.dart';
|
|
import '../models/user_model.dart';
|
|
|
|
class AuthService {
|
|
FirebaseAuth get _auth => FirebaseAuth.instance;
|
|
FirebaseFirestore get _db => FirebaseFirestore.instance;
|
|
|
|
Stream<User?> get userStream {
|
|
try {
|
|
return _auth.authStateChanges();
|
|
} catch (_) {
|
|
return const Stream.empty();
|
|
}
|
|
}
|
|
|
|
Future<UserModel?> login(String email, String password) async {
|
|
try {
|
|
UserCredential result = await _auth.signInWithEmailAndPassword(
|
|
email: email,
|
|
password: password
|
|
);
|
|
User? user = result.user;
|
|
if (user != null) {
|
|
// Ensure user document exists in Firestore (optional but helpful for names)
|
|
var doc = await _db.collection('users').doc(user.uid).get();
|
|
if (!doc.exists) {
|
|
await _db.collection('users').doc(user.uid).set({
|
|
'name': user.displayName ?? user.email!.split('@')[0],
|
|
'email': user.email,
|
|
'createdAt': FieldValue.serverTimestamp(),
|
|
});
|
|
}
|
|
return await getUser(user.uid);
|
|
}
|
|
return null;
|
|
} catch (e) {
|
|
rethrow;
|
|
}
|
|
}
|
|
|
|
Future<void> logout() async {
|
|
await _auth.signOut();
|
|
}
|
|
|
|
Future<UserModel?> getUser(String uid) async {
|
|
try {
|
|
var doc = await _db.collection('users').doc(uid).get();
|
|
if (doc.exists) {
|
|
return UserModel.fromMap(doc.id, doc.data()!);
|
|
}
|
|
return null;
|
|
} catch (e) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
Stream<List<UserModel>> getUsers() {
|
|
return _db.collection('users').snapshots().map((snapshot) =>
|
|
snapshot.docs.map((doc) => UserModel.fromMap(doc.id, doc.data())).toList());
|
|
}
|
|
}
|