feat: migrate Firebase → NestJS REST API backend
Replace all Firebase SDK (Auth, Firestore, Storage) with HTTP calls to backend.prosapp.co/api/v1: - New ApiService singleton (JWT token, GET/POST/PATCH/DELETE/upload) - auth_provider: Firebase Auth → /auth/login, /auth/register, /auth/phone/* - services_provider + calendar_services_provider → /services endpoints - professional_provider + professionals_provider → /professional-info, /users/professionals - profile_form_provider + professional_form_provider → /users/me, /storage/upload - cities/professions/settings providers → /cities, /professions, /settings - firebase_chat_repository → polling via /chats endpoints (3s interval) - firebase_score_repository → polling via /comments endpoints (10s interval) - professional_detail_provider → /users/:id + /professional-info/:id - dashboard_view: Firestore.add → POST /services - chat_view + rating_view: FirebaseAuth.uid → AuthProvider.user.id - Models: Timestamp → String for createdAt fields - google_fonts upgraded to ^8.1.0 (Dart 3.12 compat) - Remove firebase_core, firebase_auth, cloud_firestore, firebase_storage from pubspec Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
15175c1b91
commit
60216fd0e3
@@ -1,13 +1,9 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:cloud_firestore/cloud_firestore.dart';
|
||||
import 'package:firebase_auth/firebase_auth.dart';
|
||||
import 'package:prosapp_web_app/models/comment_entity.dart';
|
||||
import 'package:prosapp_web_app/models/profesional.dart';
|
||||
|
||||
import 'package:prosapp_web_app/models/usuario.dart';
|
||||
import 'package:prosapp_web_app/providers/professional_provider.dart';
|
||||
import 'package:prosapp_web_app/providers/services_provider.dart';
|
||||
import 'package:prosapp_web_app/router/router.dart';
|
||||
import 'package:prosapp_web_app/services/api_service.dart';
|
||||
import 'package:prosapp_web_app/services/navigation_service.dart';
|
||||
import 'package:prosapp_web_app/services/notifications_service.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
@@ -16,14 +12,10 @@ enum AuthStatus { checking, authenticated, notAuthenticated }
|
||||
|
||||
class AuthProvider extends ChangeNotifier {
|
||||
Usuario? user;
|
||||
Profesional? professional;
|
||||
double userAverageScore = 0.0;
|
||||
|
||||
AuthStatus authStatus = AuthStatus.checking;
|
||||
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
|
||||
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
|
||||
|
||||
String? _verificationId;
|
||||
final _api = ApiService.instance;
|
||||
|
||||
AuthProvider() {
|
||||
isAuthenticated();
|
||||
@@ -31,81 +23,59 @@ class AuthProvider extends ChangeNotifier {
|
||||
|
||||
Future<void> login(String email, String password) async {
|
||||
try {
|
||||
await _firebaseAuth.signInWithEmailAndPassword(
|
||||
email: email, password: password);
|
||||
|
||||
final userData = await _firestore
|
||||
.collection('users')
|
||||
.doc(_firebaseAuth.currentUser!.uid)
|
||||
.get();
|
||||
user = Usuario.fromDocument(userData.data()!);
|
||||
|
||||
final data = await _api.post('/auth/login', {'email': email, 'password': password});
|
||||
await _api.saveToken(data['token'] as String);
|
||||
user = Usuario.fromDocument(data['user'] as Map<String, dynamic>);
|
||||
userAverageScore = await _loadAverageScore(user!.id);
|
||||
authStatus = AuthStatus.authenticated;
|
||||
|
||||
notifyListeners();
|
||||
|
||||
NavigationService.replaceTo(Flurorouter.dashboardRoute);
|
||||
} catch (e) {
|
||||
authStatus = AuthStatus.notAuthenticated;
|
||||
notifyListeners();
|
||||
|
||||
NotificationsService.showSnackBarError(
|
||||
'Usuario o contraseña incorrectos');
|
||||
NotificationsService.showSnackBarError('Usuario o contraseña incorrectos');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> verifyPhoneNumberForLink(String phoneNumber) async {
|
||||
Future<void> register(String email, String password, String name) async {
|
||||
try {
|
||||
await _firebaseAuth.verifyPhoneNumber(
|
||||
phoneNumber: phoneNumber,
|
||||
timeout: const Duration(seconds: 60),
|
||||
verificationCompleted: (PhoneAuthCredential credential) async {
|
||||
if (_firebaseAuth.currentUser != null) {
|
||||
// Vincula el número de teléfono a la cuenta actual
|
||||
await _firebaseAuth.currentUser!.linkWithCredential(credential);
|
||||
NotificationsService.showSnackbar('Número vinculado exitosamente');
|
||||
authStatus = AuthStatus.authenticated;
|
||||
notifyListeners();
|
||||
}
|
||||
},
|
||||
verificationFailed: (FirebaseAuthException e) {
|
||||
NotificationsService.showSnackBarError(
|
||||
'Error en la verificación del teléfono: ${e.message}');
|
||||
},
|
||||
codeSent: (String verificationId, int? resendToken) {
|
||||
_verificationId = verificationId;
|
||||
notifyListeners();
|
||||
},
|
||||
codeAutoRetrievalTimeout: (String verificationId) {
|
||||
_verificationId = verificationId;
|
||||
},
|
||||
);
|
||||
final data = await _api.post('/auth/register', {
|
||||
'email': email,
|
||||
'password': password,
|
||||
'name': name.trim(),
|
||||
});
|
||||
await _api.saveToken(data['token'] as String);
|
||||
user = Usuario.fromDocument(data['user'] as Map<String, dynamic>);
|
||||
authStatus = AuthStatus.authenticated;
|
||||
notifyListeners();
|
||||
NavigationService.replaceTo(Flurorouter.dashboardRoute);
|
||||
} catch (e) {
|
||||
authStatus = AuthStatus.notAuthenticated;
|
||||
notifyListeners();
|
||||
NotificationsService.showSnackBarError('Email ya registrado');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> verifyPhoneNumber(String phoneNumber) async {
|
||||
try {
|
||||
await _api.post('/auth/phone/send', {'phone': phoneNumber});
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
NotificationsService.showSnackBarError('Error al enviar OTP');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> linkPhoneWithOTP(String smsCode) async {
|
||||
Future<void> signInWithOTP(String phoneNumber, String smsCode) async {
|
||||
try {
|
||||
final credential = PhoneAuthProvider.credential(
|
||||
verificationId: _verificationId!,
|
||||
smsCode: smsCode,
|
||||
);
|
||||
|
||||
if (_firebaseAuth.currentUser != null) {
|
||||
await _firebaseAuth.currentUser!.linkWithCredential(credential);
|
||||
|
||||
await FirebaseFirestore.instance
|
||||
.collection('users')
|
||||
.doc(_firebaseAuth.currentUser!.uid)
|
||||
.update({'phone': _firebaseAuth.currentUser!.phoneNumber});
|
||||
|
||||
NotificationsService.showSnackbar('Número vinculado exitosamente');
|
||||
|
||||
authStatus = AuthStatus.authenticated;
|
||||
notifyListeners();
|
||||
NavigationService.replaceTo(Flurorouter.profileRoute);
|
||||
}
|
||||
final data = await _api.post('/auth/phone/verify', {
|
||||
'phone': phoneNumber,
|
||||
'code': smsCode,
|
||||
});
|
||||
await _api.saveToken(data['token'] as String);
|
||||
user = Usuario.fromDocument(data['user'] as Map<String, dynamic>);
|
||||
authStatus = AuthStatus.authenticated;
|
||||
notifyListeners();
|
||||
NavigationService.replaceTo(Flurorouter.dashboardRoute);
|
||||
} catch (e) {
|
||||
authStatus = AuthStatus.notAuthenticated;
|
||||
notifyListeners();
|
||||
@@ -113,63 +83,59 @@ class AuthProvider extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> register(String email, String password, String name) async {
|
||||
Future<void> verifyPhoneNumberForLink(String phoneNumber) async {
|
||||
try {
|
||||
UserCredential userCredential =
|
||||
await _firebaseAuth.createUserWithEmailAndPassword(
|
||||
email: email,
|
||||
password: password,
|
||||
);
|
||||
|
||||
User? user = userCredential.user;
|
||||
if (user != null) {
|
||||
await _firestore.collection('users').doc(user.uid).set({
|
||||
'birthday': "",
|
||||
'city': "",
|
||||
'email': user.email,
|
||||
'gender': "",
|
||||
'id': user.uid,
|
||||
'name': name.trim(),
|
||||
'nickname': name.trim().toLowerCase(),
|
||||
'phone': "",
|
||||
'picture': "",
|
||||
'professional_state': 0,
|
||||
'token': "",
|
||||
});
|
||||
|
||||
authStatus = AuthStatus.authenticated;
|
||||
notifyListeners();
|
||||
|
||||
NavigationService.replaceTo(Flurorouter.dashboardRoute);
|
||||
}
|
||||
} catch (e) {
|
||||
authStatus = AuthStatus.notAuthenticated;
|
||||
await _api.post('/auth/phone/link/send', {'phone': phoneNumber});
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
NotificationsService.showSnackBarError('Error al enviar OTP');
|
||||
}
|
||||
}
|
||||
|
||||
NotificationsService.showSnackBarError('Email ya registrado');
|
||||
Future<void> linkPhoneWithOTP(String phoneNumber, String smsCode) async {
|
||||
try {
|
||||
await _api.post('/auth/phone/link/verify', {
|
||||
'phone': phoneNumber,
|
||||
'code': smsCode,
|
||||
});
|
||||
user = await _fetchMe();
|
||||
NotificationsService.showSnackbar('Número vinculado exitosamente');
|
||||
authStatus = AuthStatus.authenticated;
|
||||
notifyListeners();
|
||||
NavigationService.replaceTo(Flurorouter.profileRoute);
|
||||
} catch (e) {
|
||||
NotificationsService.showSnackBarError('Error en la verificación OTP');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> addEmailAndPassword(String email, String password) async {
|
||||
try {
|
||||
await _api.patch('/users/me', {'email': email, 'password': password});
|
||||
user = await _fetchMe();
|
||||
notifyListeners();
|
||||
NotificationsService.showSnackbar('Email y contraseña añadidos exitosamente');
|
||||
NavigationService.replaceTo(Flurorouter.profileRoute);
|
||||
} catch (e) {
|
||||
NotificationsService.showSnackBarError('Error al añadir email');
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> isAuthenticated() async {
|
||||
final User? firebaseUser = _firebaseAuth.currentUser;
|
||||
|
||||
if (firebaseUser == null) {
|
||||
final token = await _api.getToken();
|
||||
if (token == null) {
|
||||
authStatus = AuthStatus.notAuthenticated;
|
||||
notifyListeners();
|
||||
return false;
|
||||
}
|
||||
final userData =
|
||||
await _firestore.collection('users').doc(firebaseUser.uid).get();
|
||||
|
||||
if (userData.exists) {
|
||||
user = Usuario.fromDocument(userData.data()!);
|
||||
|
||||
userAverageScore = await _getUserAverageScore(user!.id);
|
||||
|
||||
try {
|
||||
final data = await _api.get('/auth/me');
|
||||
user = Usuario.fromDocument(data as Map<String, dynamic>);
|
||||
userAverageScore = await _loadAverageScore(user!.id);
|
||||
authStatus = AuthStatus.authenticated;
|
||||
notifyListeners();
|
||||
return true;
|
||||
} else {
|
||||
} catch (e) {
|
||||
await _api.deleteToken();
|
||||
authStatus = AuthStatus.notAuthenticated;
|
||||
notifyListeners();
|
||||
return false;
|
||||
@@ -177,158 +143,32 @@ class AuthProvider extends ChangeNotifier {
|
||||
}
|
||||
|
||||
Future<void> logout() async {
|
||||
await _firebaseAuth.signOut();
|
||||
await _api.deleteToken();
|
||||
authStatus = AuthStatus.notAuthenticated;
|
||||
user = null;
|
||||
notifyListeners();
|
||||
|
||||
Provider.of<ServicesProvider>(
|
||||
NavigationService.navigatorKey.currentContext!,
|
||||
listen: false)
|
||||
.logout();
|
||||
Provider.of<ProfessionalProvider>(
|
||||
NavigationService.navigatorKey.currentContext!,
|
||||
listen: false)
|
||||
.logout();
|
||||
final ctx = NavigationService.navigatorKey.currentContext!;
|
||||
Provider.of<ServicesProvider>(ctx, listen: false).logout();
|
||||
Provider.of<ProfessionalProvider>(ctx, listen: false).logout();
|
||||
|
||||
NavigationService.replaceTo(Flurorouter.phoneLoginRoute);
|
||||
}
|
||||
|
||||
void refreshUser() {
|
||||
isAuthenticated();
|
||||
void refreshUser() => isAuthenticated();
|
||||
|
||||
Future<Usuario> _fetchMe() async {
|
||||
final data = await _api.get('/auth/me');
|
||||
return Usuario.fromDocument(data as Map<String, dynamic>);
|
||||
}
|
||||
|
||||
Future<void> verifyPhoneNumber(String phoneNumber) async {
|
||||
Future<double> _loadAverageScore(String userId) async {
|
||||
try {
|
||||
await _firebaseAuth.verifyPhoneNumber(
|
||||
phoneNumber: phoneNumber,
|
||||
timeout: const Duration(seconds: 60),
|
||||
verificationCompleted: (PhoneAuthCredential credential) async {
|
||||
await _firebaseAuth.signInWithCredential(credential);
|
||||
authStatus = AuthStatus.authenticated;
|
||||
notifyListeners();
|
||||
NavigationService.replaceTo(Flurorouter.dashboardRoute);
|
||||
},
|
||||
verificationFailed: (FirebaseAuthException e) {
|
||||
NotificationsService.showSnackBarError(
|
||||
'La verificación del teléfono falló: ${e.message}');
|
||||
},
|
||||
codeSent: (String verificationId, int? resendToken) {
|
||||
_verificationId = verificationId;
|
||||
notifyListeners();
|
||||
},
|
||||
codeAutoRetrievalTimeout: (String verificationId) {
|
||||
_verificationId = verificationId;
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
NotificationsService.showSnackBarError('Error al enviar OTP');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> signInWithOTP(String smsCode) async {
|
||||
try {
|
||||
final credential = PhoneAuthProvider.credential(
|
||||
verificationId: _verificationId!,
|
||||
smsCode: smsCode,
|
||||
);
|
||||
await _firebaseAuth.signInWithCredential(credential);
|
||||
|
||||
User? currentUser = _firebaseAuth.currentUser;
|
||||
|
||||
if (currentUser != null) {
|
||||
final userData =
|
||||
await _firestore.collection('users').doc(currentUser.uid).get();
|
||||
|
||||
if (userData.exists) {
|
||||
user = Usuario.fromDocument(userData.data()!);
|
||||
} else {
|
||||
await _firestore.collection('users').doc(currentUser.uid).set({
|
||||
'birthday': "",
|
||||
'city': "",
|
||||
'email': "",
|
||||
'gender': "",
|
||||
'id': currentUser.uid,
|
||||
'name': "",
|
||||
'nickname': "",
|
||||
'phone': currentUser.phoneNumber,
|
||||
'picture': "",
|
||||
'professional_state': 0,
|
||||
'token': "",
|
||||
});
|
||||
|
||||
final newUserData =
|
||||
await _firestore.collection('users').doc(currentUser.uid).get();
|
||||
user = Usuario.fromDocument(newUserData.data()!);
|
||||
}
|
||||
|
||||
authStatus = AuthStatus.authenticated;
|
||||
notifyListeners();
|
||||
|
||||
NavigationService.replaceTo(Flurorouter.dashboardRoute);
|
||||
}
|
||||
} catch (e) {
|
||||
authStatus = AuthStatus.notAuthenticated;
|
||||
notifyListeners();
|
||||
NotificationsService.showSnackBarError('Error en la verificación OTP');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> addEmailAndPassword(String email, String password) async {
|
||||
try {
|
||||
final User? currentUser = _firebaseAuth.currentUser;
|
||||
|
||||
if (currentUser != null) {
|
||||
await currentUser.updateEmail(email);
|
||||
|
||||
await currentUser.updatePassword(password);
|
||||
|
||||
await _firestore.collection('users').doc(currentUser.uid).update({
|
||||
'email': email,
|
||||
});
|
||||
|
||||
notifyListeners();
|
||||
|
||||
NotificationsService.showSnackbar(
|
||||
'Email y contraseña añadidos exitosamente');
|
||||
|
||||
NavigationService.replaceTo(Flurorouter.profileRoute);
|
||||
}
|
||||
} catch (e) {
|
||||
if (e is FirebaseAuthException && e.code == 'email-already-in-use') {
|
||||
NotificationsService.showSnackBarError('El correo ya existe');
|
||||
}
|
||||
|
||||
if (e is FirebaseAuthException && e.code == 'invalid-email') {
|
||||
NotificationsService.showSnackBarError('El correo no es vßlido');
|
||||
}
|
||||
|
||||
if (e is FirebaseAuthException && e.code == 'weak-password') {
|
||||
NotificationsService.showSnackBarError(
|
||||
'La contraseña debe tener al menos 6 caracteres');
|
||||
}
|
||||
|
||||
if (e is FirebaseAuthException && e.code == 'requires-recent-login') {
|
||||
NotificationsService.showSnackBarError(
|
||||
'Debes iniciar sesión recientemente antes de agregar email y contraseña');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<double> _getUserAverageScore(String userId) async {
|
||||
final querySnapshot = await FirebaseFirestore.instance
|
||||
.collection('comments')
|
||||
.where('destination_id', isEqualTo: userId)
|
||||
.where('is_from_user', isEqualTo: false)
|
||||
.get();
|
||||
|
||||
if (querySnapshot.docs.isEmpty) {
|
||||
final data = await _api.get('/comments/reputation/$userId');
|
||||
final rep = data as Map<String, dynamic>;
|
||||
return (rep['average'] as num?)?.toDouble() ?? 0.0;
|
||||
} catch (_) {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
final scores = querySnapshot.docs
|
||||
.map((e) => CommentEntity.fromDocument(e.data()).score)
|
||||
.toList();
|
||||
final averageScore = scores.reduce((a, b) => a + b) / scores.length;
|
||||
return averageScore;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user