71 lines
1.7 KiB
Dart
71 lines
1.7 KiB
Dart
import 'package:firebase_auth/firebase_auth.dart';
|
|
import 'package:firebase_database/firebase_database.dart';
|
|
|
|
class AuthService {
|
|
final FirebaseAuth _auth = FirebaseAuth.instance;
|
|
|
|
final FirebaseDatabase _database = FirebaseDatabase.instance;
|
|
|
|
User? get currentUser => _auth.currentUser;
|
|
|
|
// ================= LOGIN =================
|
|
|
|
Future<UserCredential> login({
|
|
required String email,
|
|
required String password,
|
|
}) async {
|
|
return await _auth.signInWithEmailAndPassword(
|
|
email: email,
|
|
password: password,
|
|
);
|
|
}
|
|
|
|
// ================= REGISTER =================
|
|
|
|
Future<UserCredential> register({
|
|
required String name,
|
|
required String email,
|
|
required String password,
|
|
}) async {
|
|
UserCredential credential = await _auth.createUserWithEmailAndPassword(
|
|
email: email,
|
|
password: password,
|
|
);
|
|
|
|
final uid = credential.user!.uid;
|
|
|
|
await _database.ref('users').child(uid).set({
|
|
'uid': uid,
|
|
'name': name,
|
|
'email': email,
|
|
'created_at': DateTime.now().toIso8601String(),
|
|
});
|
|
|
|
return credential;
|
|
}
|
|
|
|
// ================= LOGOUT =================
|
|
|
|
Future<void> logout() async {
|
|
await _auth.signOut();
|
|
}
|
|
|
|
// ================= GET USER =================
|
|
|
|
Future<Map<String, dynamic>?> getUserData() async {
|
|
if (_auth.currentUser == null) {
|
|
return null;
|
|
}
|
|
|
|
final uid = _auth.currentUser!.uid;
|
|
|
|
final snapshot = await _database.ref('users').child(uid).get();
|
|
|
|
if (!snapshot.exists) {
|
|
return null;
|
|
}
|
|
|
|
return Map<String, dynamic>.from(snapshot.value as Map<dynamic, dynamic>);
|
|
}
|
|
}
|