AuthService.dart 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import 'package:cloud_firestore/cloud_firestore.dart';
  2. import 'package:firebase_auth/firebase_auth.dart';
  3. import 'package:physigo/Services/DatabaseManager.dart';
  4. import 'package:physigo/Services/logged_in_user.dart';
  5. import 'package:location/location.dart';
  6. class AuthenticationServices {
  7. static final FirebaseAuth _auth = FirebaseAuth.instance;
  8. static LoggedInUser? user;
  9. //Register a user
  10. static Future createNewUser(bool anonymous, String birth, String name, String email, String password,
  11. String phone, String sharedID, String surname) async {
  12. try {
  13. UserCredential result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
  14. User? user = result.user;
  15. LocationData userLocation = await Location.instance.getLocation();
  16. GeoPoint userGeoPoint = GeoPoint(userLocation.latitude!, userLocation.longitude!);
  17. await DatabaseManager("total_points").createUserData(userGeoPoint, anonymous, birth, DateTime.now(), DateTime.utc(1970, 1, 1),
  18. email, name, phone, sharedID, surname, 0, DateTime.now(), 'null', user!.uid);
  19. return user;
  20. } catch (e) {
  21. print(e.toString());
  22. }
  23. }
  24. //LogIn with user
  25. static Future loginUser(String email, String password) async {
  26. try {
  27. UserCredential result = await _auth.signInWithEmailAndPassword(email: email, password: password);
  28. await getCurrentUser();
  29. return result.user;
  30. } catch (e) {
  31. print(e.toString());
  32. }
  33. }
  34. static Future<LoggedInUser?> getCurrentUser() async {
  35. if (user != null) {
  36. return user;
  37. }
  38. if (_auth.currentUser == null) {
  39. return null;
  40. }
  41. var querySnapshot = await FirebaseFirestore.instance
  42. .collection('profileInfo')
  43. .where('mail', isEqualTo: _auth.currentUser?.email)
  44. .get();
  45. user = LoggedInUser.fromMap(querySnapshot.docs.first.data());
  46. return user;
  47. }
  48. static Future<int> getPlace() async {
  49. var users = await FirebaseFirestore.instance
  50. .collection('Users')
  51. .where("total_points", isGreaterThan: user!.totalPoints)
  52. .get();
  53. return users.docs.length + 1;
  54. }
  55. }