auth.dart 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import 'package:firebase_auth/firebase_auth.dart' as firebase_auth;
  2. import '/models/user.dart';
  3. class AuthService {
  4. final firebase_auth.FirebaseAuth _auth = firebase_auth.FirebaseAuth.instance;
  5. // Convert a Firebase User to a custom User
  6. User? _userFromFirebase(firebase_auth.User? user) {
  7. return user != null
  8. ? User(
  9. uid: user.uid,
  10. email: '',
  11. phoneNumber: '',
  12. icNumber: '',
  13. password: '',
  14. // carID: '',
  15. // carBrand: '',
  16. // carColor: ''
  17. )
  18. : null;
  19. }
  20. // Auth change user stream
  21. Stream<User?> get user {
  22. return _auth.authStateChanges().map(_userFromFirebase);
  23. }
  24. // Sign in anonymously
  25. Future<User?> signInAnonymously() async {
  26. try {
  27. firebase_auth.UserCredential authResult = await _auth.signInAnonymously();
  28. User? user = _userFromFirebase(authResult.user);
  29. if (user != null) {
  30. print('User signed in anonymously with UID: ${user.uid}');
  31. }
  32. return user;
  33. } catch (e) {
  34. print('Error signing in anonymously: $e');
  35. return null;
  36. }
  37. }
  38. // Sign in with email and password
  39. Future<User?> signInWithEmailAndPassword(
  40. String email, String password) async {
  41. try {
  42. firebase_auth.UserCredential authResult =
  43. await _auth.signInWithEmailAndPassword(
  44. email: email,
  45. password: password,
  46. );
  47. return _userFromFirebase(authResult.user);
  48. } catch (e) {
  49. print('Error signing in with email/password: $e');
  50. return null;
  51. }
  52. }
  53. // Register with email and password
  54. Future<User?> registerWithEmailAndPassword(
  55. String email, String password) async {
  56. try {
  57. firebase_auth.UserCredential authResult =
  58. await _auth.createUserWithEmailAndPassword(
  59. email: email,
  60. password: password,
  61. );
  62. return _userFromFirebase(authResult.user);
  63. } catch (e) {
  64. print('Error registering with email/password: $e');
  65. return null;
  66. }
  67. }
  68. // Sign out method
  69. Future<void> signOut() async {
  70. try {
  71. await _auth.signOut();
  72. } catch (e) {
  73. print('Error signing out: $e');
  74. }
  75. }
  76. }