2024-04-30 19:25:16 +02:00
|
|
|
import 'package:cloud_firestore/cloud_firestore.dart';
|
2024-04-29 14:36:25 +02:00
|
|
|
import 'package:firebase_auth/firebase_auth.dart';
|
|
|
|
|
|
|
|
class AuthService {
|
2024-04-30 19:25:16 +02:00
|
|
|
// instance of auth and firestore
|
2024-04-29 14:36:25 +02:00
|
|
|
final FirebaseAuth _auth = FirebaseAuth.instance;
|
2024-04-30 19:25:16 +02:00
|
|
|
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
|
|
|
|
|
|
|
|
// get current user
|
|
|
|
User? getCurrentUser() {
|
|
|
|
return _auth.currentUser;
|
|
|
|
}
|
2024-04-29 14:36:25 +02:00
|
|
|
|
2024-04-30 22:28:14 +02:00
|
|
|
// sign in
|
2024-04-29 14:36:25 +02:00
|
|
|
Future<UserCredential> signInWithEmailPassword(String email, password) async {
|
|
|
|
try {
|
|
|
|
UserCredential userCredential = await _auth.signInWithEmailAndPassword(
|
|
|
|
email: email,
|
|
|
|
password: password,
|
|
|
|
);
|
2024-04-30 19:25:16 +02:00
|
|
|
|
2024-04-29 14:36:25 +02:00
|
|
|
return userCredential;
|
|
|
|
} on FirebaseAuthException catch (e) {
|
|
|
|
throw Exception(e.code);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// sign up (register)
|
|
|
|
Future<UserCredential> signUpWithEmailPassword(String email, password) async {
|
|
|
|
try {
|
2024-04-30 19:25:16 +02:00
|
|
|
// create user
|
2024-04-29 14:36:25 +02:00
|
|
|
UserCredential userCredential =
|
|
|
|
await _auth.createUserWithEmailAndPassword(
|
|
|
|
email: email,
|
|
|
|
password: password,
|
|
|
|
);
|
2024-04-30 19:25:16 +02:00
|
|
|
|
|
|
|
// save user info in a document
|
|
|
|
_firestore.collection("Users").doc(userCredential.user!.uid).set(
|
|
|
|
{
|
|
|
|
'uid': userCredential.user!.uid,
|
|
|
|
'email': email,
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
2024-04-29 14:36:25 +02:00
|
|
|
return userCredential;
|
|
|
|
} on FirebaseAuthException catch (e) {
|
|
|
|
throw Exception(e.code);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// sign out
|
|
|
|
Future<void> signOut() async {
|
|
|
|
return await _auth.signOut();
|
|
|
|
}
|
|
|
|
|
|
|
|
// errors
|
|
|
|
}
|