auth phone and re auth phone

This commit is contained in:
Felipe
2024-03-12 20:02:00 -05:00
parent 13896f2b6d
commit 312cc3d863
16 changed files with 1049 additions and 178 deletions
+166 -4
View File
@@ -1,3 +1,6 @@
import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart'; import 'package:equatable/equatable.dart';
import 'package:user_repository/user_repository.dart'; import 'package:user_repository/user_repository.dart';
@@ -7,6 +10,9 @@ part 'auth_state.dart';
class AuthBloc extends Bloc<AuthEvent, AuthState> { class AuthBloc extends Bloc<AuthEvent, AuthState> {
final UserRepository _userRepository; final UserRepository _userRepository;
final PhoneVerificationService phoneVerificationService =
PhoneVerificationService();
String? _verificationId;
AuthBloc({required UserRepository userRepository}) AuthBloc({required UserRepository userRepository})
: _userRepository = userRepository, : _userRepository = userRepository,
@@ -14,6 +20,9 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
on<AuthEventLoginOAuth>(_onAuthEventLoginOAuth); on<AuthEventLoginOAuth>(_onAuthEventLoginOAuth);
on<AuthEventVerifyOAuth>(_onAuthEventVerifyOAuth); on<AuthEventVerifyOAuth>(_onAuthEventVerifyOAuth);
on<AuthEventAddEmailAndPassword>(_onAuthEventAddEmailAndPassword); on<AuthEventAddEmailAndPassword>(_onAuthEventAddEmailAndPassword);
on<AuthEventUpdatePassword>(_updatePassword);
on<LinkWithPhoneNumber>(_linkWithPhoneNumber);
on<LinkWithPhoneNumberOtp>(_linkWithPhoneNumberOtp);
} }
void _onAuthEventLoginOAuth( void _onAuthEventLoginOAuth(
@@ -39,10 +48,6 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
} else { } else {
emit(const AuthStateVerifyOAuth(true)); emit(const AuthStateVerifyOAuth(true));
} }
(isVerified)
? emit(AuthStateSuccess())
: emit(const AuthStateVerifyOAuth(true));
} catch (e) { } catch (e) {
emit(const AuthStateFailure()); emit(const AuthStateFailure());
} }
@@ -69,4 +74,161 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
emit(const AuthStateFailure()); emit(const AuthStateFailure());
} }
} }
void _updatePassword(
AuthEventUpdatePassword event, Emitter<AuthState> emit) async {
emit(AuthStateProcess());
try {
final error = await _userRepository.updatePassword(
event.actualPassword, event.password);
if (error == null) {
emit(AuthStateSuccess());
} else {
switch (error) {
case UpdatePassworErros.credentialsWrong:
emit(const AuthStateFailure(message: "Contraseña incorrecta"));
break;
case UpdatePassworErros.userNotFound:
emit(const AuthStateFailure(message: "Usuario no encontrado"));
break;
case UpdatePassworErros.unknown:
emit(const AuthStateFailure(message: "Error inesperado. 🥸"));
break;
}
}
} catch (e) {
emit(const AuthStateFailure(message: "Error inesperado. 🥸"));
}
}
void _linkWithPhoneNumber(
LinkWithPhoneNumber event, Emitter<AuthState> emit) async {
emit(AuthStateProcess());
try {
await for (PhoneAuthEvent event
in phoneVerificationService.verifyPhoneNumber(event.phoneNumber)) {
switch (event.type) {
case PhoneAuthEventType.verificationCompleted:
AuthCredential credential = event.data;
print('Verificación completada. Credencial: $credential');
break;
case PhoneAuthEventType.verificationFailed:
FirebaseAuthException exception = event.data;
print('Verificación fallida. Excepción: $exception');
emit(AuthStateFailure(message: "Error inesperado. 🥸 $exception"));
return; // Detener la ejecución aquí
case PhoneAuthEventType.codeAutoRetrievalTimeout:
String verificationId = event.data;
print(
'Tiempo de espera agotado para recuperar el código. ID: $verificationId');
emit(const AuthStateFailure(
message: "Tiempo de espera agotado. 🥸",
));
break;
case PhoneAuthEventType.codeSent:
Map<String, dynamic> eventData = event.data;
String verificationId = eventData['verificationId'];
int? resendToken = eventData['resendToken'];
print(
'Código enviado. ID: $verificationId, resendToken: $resendToken');
_verificationId = verificationId;
emit(const AuthStateVerifyOAuth(false));
break;
}
}
} catch (e) {
emit(const AuthStateFailure(message: "Error inesperado. PUTA 🥸"));
}
}
void _linkWithPhoneNumber3(
LinkWithPhoneNumber event, Emitter<AuthState> emit) async {
emit(AuthStateProcess());
try {
StreamSubscription<PhoneAuthEvent> subscription = phoneVerificationService
.verifyPhoneNumber(event.phoneNumber)
.listen((event) async {
switch (event.type) {
case PhoneAuthEventType.verificationCompleted:
AuthCredential credential = event.data;
print('Verificación completada. Credencial: $credential');
break;
case PhoneAuthEventType.verificationFailed:
FirebaseAuthException exception = event.data;
print('Verificación fallida. Excepción: $exception');
break;
case PhoneAuthEventType.codeAutoRetrievalTimeout:
String verificationId = event.data;
print(
'Tiempo de espera agotado para recuperar el código. ID: $verificationId');
break;
case PhoneAuthEventType.codeSent:
Map<String, dynamic> eventData = event.data;
String verificationId = eventData['verificationId'];
int? resendToken = eventData['resendToken'];
print(
'Código enviado. ID: $verificationId, resendToken: $resendToken');
_verificationId = verificationId;
emit(const AuthStateVerifyOAuth(false));
break;
}
if (event.type == PhoneAuthEventType.verificationFailed) {
// Detener la suscripción si la verificación falla
// subscription.cancel();
emit(const AuthStateFailure(message: "Error inesperado. 🥸"));
}
});
// await _userRepository
} catch (e) {
emit(const AuthStateFailure(message: "Error inesperado. PUTA 🥸"));
}
}
void _linkWithPhoneNumberOtp(
LinkWithPhoneNumberOtp event, Emitter<AuthState> emit) async {
emit(AuthStateProcess());
try {
final bool isVerified = await _userRepository.linkWithOTP(
event.phoneNumber, _verificationId!, event.code);
if (isVerified) {
emit(AuthStateSuccess());
} else {
emit(const AuthStateVerifyOAuth(true));
}
} catch (e) {
if (e is FirebaseAuthException) {
switch (e.code) {
case "invalid-verification-code":
emit(const AuthStateFailure(
message: "Código de verificación incorrecto. 🥸",
));
break;
case "provider-already-linked":
emit(const AuthStateFailure(
message: "Cuenta ya vinculada. 🥸",
));
break;
case "credential-already-in-use":
emit(const AuthStateFailure(
message:
"Este numero ya se encuentra registrado con otra cuenta. 🥸",
));
break;
default:
emit(AuthStateFailure(message: "Error inesperado. 🥸 $e"));
break;
}
} else {
emit(AuthStateFailure(message: "Error inesperado. 🥸 $e"));
}
}
}
} }
+36
View File
@@ -31,3 +31,39 @@ class AuthEventAddEmailAndPassword extends AuthEvent {
@override @override
List<Object> get props => [email, password]; List<Object> get props => [email, password];
} }
class AuthEventUpdatePassword extends AuthEvent {
final String email;
final String actualPassword;
final String password;
const AuthEventUpdatePassword({
required this.email,
required this.actualPassword,
required this.password,
});
@override
List<Object> get props => [password];
}
class LinkWithPhoneNumber extends AuthEvent {
final String phoneNumber;
const LinkWithPhoneNumber({required this.phoneNumber});
@override
List<Object> get props => [phoneNumber];
}
class LinkWithPhoneNumberOtp extends AuthEvent {
final String phoneNumber;
final String code;
const LinkWithPhoneNumberOtp({
required this.phoneNumber,
required this.code,
});
@override
List<Object> get props => [phoneNumber, code];
}
@@ -8,15 +8,13 @@ import 'package:user_repository/user_repository.dart';
part 'authentication_event.dart'; part 'authentication_event.dart';
part 'authentication_state.dart'; part 'authentication_state.dart';
class AuthenticationBloc class AuthenticationBloc extends Bloc<AuthenticationEvent, AuthenticationState> {
extends Bloc<AuthenticationEvent, AuthenticationState> {
final UserRepository userRepository; final UserRepository userRepository;
late final StreamSubscription<MyUser?> _userSubscription; late final StreamSubscription<MyUser?> _userSubscription;
AuthenticationBloc({required UserRepository myUserRepository}) AuthenticationBloc({required UserRepository myUserRepository})
: userRepository = myUserRepository, : userRepository = myUserRepository,
super(const AuthenticationState.unknown()) { super(const AuthenticationState.unknown()) {_userSubscription = userRepository.streamUser().listen((authUser) {
_userSubscription = userRepository.streamUser().listen((authUser) {
add(AuthenticationUserChanged(authUser)); add(AuthenticationUserChanged(authUser));
}); });
on<AuthenticationUserChanged>(_onAuthenticationUserChanged); on<AuthenticationUserChanged>(_onAuthenticationUserChanged);
@@ -32,8 +30,7 @@ class AuthenticationBloc
); );
} }
void _onAuthenticationLogoutRequested(AuthenticationLogoutRequested event, void _onAuthenticationLogoutRequested(AuthenticationLogoutRequested event, Emitter<AuthenticationState> emit) async {
Emitter<AuthenticationState> emit) async {
await userRepository.logOut(); await userRepository.logOut();
emit(const AuthenticationState.unauthenticated()); emit(const AuthenticationState.unauthenticated());
} }
@@ -7,14 +7,6 @@ abstract class MyUserEvent extends Equatable {
List<Object?> get props => []; List<Object?> get props => [];
} }
// class GetMyUser extends MyUserEvent {
// final String myUserId;
// const GetMyUser({required this.myUserId});
// @override
// List<Object> get props => [myUserId];
// }
class UserChanged extends MyUserEvent { class UserChanged extends MyUserEvent {
final MyUser? user; final MyUser? user;
+25 -22
View File
@@ -9,30 +9,33 @@ class GeneralDrawerHeader extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final user = context.read<MyUserBloc>().state.user!; return BlocBuilder<MyUserBloc, MyUserState>(
return ListTile( builder: (context, state) {
onTap: () { if (state.status == MyUserStatus.success) {
// Navigator.pop(context); final user = state.user!;
Navigator.push( return ListTile(
context, onTap: () {
CupertinoPageRoute( Navigator.push(
builder: (BuildContext context) { context,
return const ProfileScreen(); CupertinoPageRoute(
builder: (BuildContext context) {
return const ProfileScreen();
},
),
);
}, },
), title: Text(user.name ?? '',style: const TextStyle(fontWeight: FontWeight.bold)),
); subtitle: Text(user.drawerLabel,style: const TextStyle(fontSize: 12)),
leading: pictureWidget(user.picture, context),
trailing: const Icon(Icons.keyboard_arrow_right, color: Colors.black),
contentPadding: const EdgeInsets.symmetric(vertical: 10, horizontal: 15),
);
} else if (state.status == MyUserStatus.failure) {
return const Text('Error obteniendo datos del usuario');
} else {
return const CircularProgressIndicator();
}
}, },
title: Text(
user.name ?? '',
style: const TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Text(
user.drawerLabel,
style: const TextStyle(fontSize: 12),
),
leading: pictureWidget(user.picture, context),
trailing: const Icon(Icons.keyboard_arrow_right, color: Colors.black),
contentPadding: const EdgeInsets.symmetric(vertical: 10, horizontal: 15),
); );
} }
@@ -1,3 +1,4 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_otp_text_field/flutter_otp_text_field.dart'; import 'package:flutter_otp_text_field/flutter_otp_text_field.dart';
@@ -16,6 +17,7 @@ class OtpAuthScreen extends StatefulWidget {
class _OtpAuthScreenState extends State<OtpAuthScreen> { class _OtpAuthScreenState extends State<OtpAuthScreen> {
late final AuthBloc authBloc; late final AuthBloc authBloc;
late String verificationCode = '';
@override @override
void initState() { void initState() {
@@ -47,7 +49,7 @@ class _OtpAuthScreenState extends State<OtpAuthScreen> {
crossAxisAlignment: CrossAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,
children: [ children: [
SizedBox(height: MediaQuery.of(context).size.height * 0.1), SizedBox(height: MediaQuery.of(context).size.height * 0.1),
const Text('Te enviaremos un Código de verificación a'), const Text('Te enviaremos un código de verificación a'),
Text( Text(
widget.phoneNumber, widget.phoneNumber,
style: const TextStyle( style: const TextStyle(
@@ -60,14 +62,18 @@ class _OtpAuthScreenState extends State<OtpAuthScreen> {
numberOfFields: 6, numberOfFields: 6,
borderColor: const Color(0xFF512DA8), borderColor: const Color(0xFF512DA8),
showFieldAsBox: true, showFieldAsBox: true,
onCodeChanged: (String code) {}, onCodeChanged: (String code) {
verificationCode = code;
},
onSubmit: (String verificationCode) { onSubmit: (String verificationCode) {
authBloc.add(AuthEventVerifyOAuth(code: verificationCode)); authBloc.add(AuthEventVerifyOAuth(code: verificationCode));
}, },
), ),
Expanded(child: Container()), Expanded(child: Container()),
GeneralPrimaryButton( GeneralPrimaryButton(
onPressed: () {}, onPressed: () {
authBloc.add(AuthEventVerifyOAuth(code: verificationCode));
},
label: 'Continuar', label: 'Continuar',
), ),
const SizedBox(height: 20), const SizedBox(height: 20),
+5 -12
View File
@@ -85,32 +85,25 @@ class WelcomeScreen extends StatelessWidget {
onChanged: (phone) { onChanged: (phone) {
_phoneNumber = phone.completeNumber; _phoneNumber = phone.completeNumber;
}, },
decoration: decoration: GeneralInputDecoration.getCustomDecoration(
GeneralInputDecoration.getCustomDecoration(
context: context, context: context,
hintText: 'Ingresa tu numero', hintText: 'Ingresa tu numero',
errorMsg: _errorMsg, errorMsg: _errorMsg,
), ),
), ),
), ),
Text( Text('Un código será enviado a este numero de celular.',
'Un código será enviado a este numero de celular.',
textAlign: TextAlign.center, textAlign: TextAlign.center,
style: TextStyle( style: TextStyle(fontSize: 13.0,color: Theme.of(context).colorScheme.onBackground),
fontSize: 13.0,
color: Theme.of(context).colorScheme.onBackground,
),
), ),
GeneralPrimaryButton( GeneralPrimaryButton(
onPressed: () { onPressed: () {
final phoneNumber = _phoneNumber; final phoneNumber = _phoneNumber;
if (phoneNumber != null && phoneNumber.isNotEmpty) { if (phoneNumber != null && phoneNumber.isNotEmpty) {
Navigator.push( Navigator.push(context,
context,
CupertinoPageRoute( CupertinoPageRoute(
builder: (context) => builder: (context) => OtpAuthScreen(phoneNumber: phoneNumber),
OtpAuthScreen(phoneNumber: phoneNumber),
), ),
); );
} }
@@ -1,44 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:prosappco/blocs/my_user_bloc/my_user_bloc.dart';
class ProfilePhoneScreen extends StatefulWidget {
const ProfilePhoneScreen({super.key});
@override
State<ProfilePhoneScreen> createState() => _ProfilePhoneScreenState();
}
class _ProfilePhoneScreenState extends State<ProfilePhoneScreen> {
final TextEditingController _phoneController = TextEditingController();
@override
void dispose() {
_phoneController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return BlocBuilder<MyUserBloc, MyUserState>(
builder: (context, state) {
if (state.status == MyUserStatus.success) {
_phoneController.text = state.user!.phone ?? '';
return Scaffold(
appBar: AppBar(
title: Text(
_phoneController.text.isEmpty
? 'Agregar telefono'
: 'Actualizar telefono',
),
),
body: const Placeholder(),
);
} else {
return const Center(child: CircularProgressIndicator());
}
},
);
}
}
@@ -1,23 +1,25 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_otp_text_field/flutter_otp_text_field.dart';
import 'package:injector/injector.dart'; import 'package:injector/injector.dart';
import 'package:prosappco/blocs/auth_bloc/auth_bloc.dart'; import 'package:prosappco/blocs/auth_bloc/auth_bloc.dart';
import 'package:prosappco/blocs/my_user_bloc/my_user_bloc.dart'; import 'package:prosappco/blocs/my_user_bloc/my_user_bloc.dart';
import 'package:prosappco/components/general_primary_button.dart'; import 'package:prosappco/components/general_primary_button.dart';
import 'package:prosappco/screens/authentication/sign_in_screen.dart';
class ProfileEmailScreen extends StatefulWidget { class ProfileRegisterEmailScreen extends StatefulWidget {
const ProfileEmailScreen({super.key}); const ProfileRegisterEmailScreen({super.key});
@override @override
State<ProfileEmailScreen> createState() => _ProfileEmailScreenState(); State<ProfileRegisterEmailScreen> createState() =>
_ProfileRegisterEmailScreenState();
} }
class _ProfileEmailScreenState extends State<ProfileEmailScreen> { class _ProfileRegisterEmailScreenState extends State<ProfileRegisterEmailScreen> {
final TextEditingController _emailController = TextEditingController(); final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController(); final TextEditingController _passwordController = TextEditingController();
late final AuthBloc authBloc; late final AuthBloc authBloc;
late String verificationCode;
@override @override
void initState() { void initState() {
@@ -32,28 +34,83 @@ class _ProfileEmailScreenState extends State<ProfileEmailScreen> {
super.dispose(); super.dispose();
} }
void _showLoginModal(BuildContext context) { void _showLoginModal(BuildContext context, MyUserState state) {
final authBlocDialog = Injector.appInstance.get<AuthBloc>();
final phone = state.user?.phone ?? '';
authBlocDialog.add(AuthEventLoginOAuth(phone: phone));
showDialog( showDialog(
context: context, context: context,
builder: (BuildContext context) { builder: (BuildContext context) {
return AlertDialog( return BlocProvider<AuthBloc>(
title: const Text('Requiere inicio de sesión reciente'), create: (context) => authBlocDialog,
content: const Text('Por favor, inicie sesión nuevamente para continuar.'), child: BlocConsumer<AuthBloc, AuthState>(
actions: <Widget>[ listener: (context, state) {
TextButton( if (state is AuthStateSuccess) {
onPressed: () { // here update email and password autentication
Navigator.of(context).pop(); authBloc.add(
AuthEventAddEmailAndPassword(
email: _emailController.text,
password: _passwordController.text,
),
);
} else if (state is AuthStateVerifyOAuth && state.isWrongCode) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('El Código es incorrecto'),
));
}
},
builder: (context, state) {
return AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Text(
'Te enviaremos un código \n de verificación a',
textAlign: TextAlign.center,
),
const SizedBox(height: 20),
Text(
phone,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 20),
OtpTextField(
numberOfFields: 6,
fieldWidth: 35,
borderColor: const Color(0xFF512DA8),
// showFieldAsBox: true,
onCodeChanged: (String code) {
verificationCode = code;
},
onSubmit: (String verificationCode) {
authBlocDialog.add(
AuthEventVerifyOAuth(code: verificationCode));
},
),
const SizedBox(height: 30),
GeneralPrimaryButton(
onPressed: () {
authBlocDialog.add(
AuthEventVerifyOAuth(code: verificationCode));
},
label: 'Continuar',
),
],
),
);
}, },
child: const Text('OK'),
), ),
], );
); });
},
);
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
// _showLoginModal(context);
return BlocProvider<AuthBloc>( return BlocProvider<AuthBloc>(
create: (context) => authBloc, create: (context) => authBloc,
child: BlocListener<AuthBloc, AuthState>( child: BlocListener<AuthBloc, AuthState>(
@@ -66,9 +123,11 @@ class _ProfileEmailScreenState extends State<ProfileEmailScreen> {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar( ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('El correo ya existe'), content: Text('El correo ya existe'),
)); ));
Navigator.of(context).pop();
} }
if (state is AuthStateRequiresRecentLogin) { if (state is AuthStateRequiresRecentLogin) {
_showLoginModal(context); // _showLoginModal(context, state);
} }
}, },
child: BlocBuilder<MyUserBloc, MyUserState>( child: BlocBuilder<MyUserBloc, MyUserState>(
@@ -78,11 +137,7 @@ class _ProfileEmailScreenState extends State<ProfileEmailScreen> {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: Text( title: const Text('Agregar correo'),
_emailController.text.isEmpty
? 'Agregar correo'
: 'Actualizar correo',
),
), ),
body: Center( body: Center(
// Centro del contenido // Centro del contenido
@@ -145,6 +200,33 @@ class _ProfileEmailScreenState extends State<ProfileEmailScreen> {
return null; return null;
}, },
), ),
const SizedBox(height: 20),
TextFormField(
controller: _passwordController,
obscureText: true,
decoration: const InputDecoration(
labelText: 'Confirmar contraseña',
prefixIcon: Icon(Icons.lock_rounded),
hintText: 'Contraseña',
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(10.0),
)),
errorBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red),
),
focusedErrorBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.red, width: 2.0),
),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Por favor, ingrese su contraseña';
}
return null;
},
),
const SizedBox(height: 30), const SizedBox(height: 30),
GeneralPrimaryButton( GeneralPrimaryButton(
onPressed: () { onPressed: () {
@@ -155,17 +237,9 @@ class _ProfileEmailScreenState extends State<ProfileEmailScreen> {
if (_passwordController.text.isEmpty) { if (_passwordController.text.isEmpty) {
return; return;
} }
_showLoginModal(context, state);
context.read<AuthBloc>().add(
AuthEventAddEmailAndPassword(
email: _emailController.text,
password: _passwordController.text,
),
);
}, },
label: _emailController.text.isEmpty label: 'Guardar',
? 'Registrar'
: 'Actualizar',
), ),
], ],
), ),
@@ -0,0 +1,279 @@
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_otp_text_field/flutter_otp_text_field.dart';
import 'package:injector/injector.dart';
import 'package:intl_phone_field/intl_phone_field.dart';
import 'package:prosappco/blocs/auth_bloc/auth_bloc.dart';
import 'package:prosappco/blocs/my_user_bloc/my_user_bloc.dart';
import 'package:prosappco/components/general_input_decoration.dart';
import 'package:prosappco/components/general_primary_button.dart';
import 'package:prosappco/screens/authentication/otp_auth_screen.dart';
class ProfileRegisterPhoneScreen extends StatefulWidget {
const ProfileRegisterPhoneScreen({super.key});
@override
State<ProfileRegisterPhoneScreen> createState() =>
_ProfileRegisterPhoneScreenState();
}
class _ProfileRegisterPhoneScreenState
extends State<ProfileRegisterPhoneScreen> {
final TextEditingController _actualPasswordController =
TextEditingController();
late final AuthBloc authBloc;
late String verificationCode;
@override
void initState() {
super.initState();
authBloc = Injector.appInstance.get<AuthBloc>();
}
@override
void dispose() {
super.dispose();
}
void _showLoginModal(BuildContext context, MyUserState state) {
final authBlocDialog = Injector.appInstance.get<AuthBloc>();
final phone = state.user?.phone ?? '';
authBlocDialog.add(AuthEventLoginOAuth(phone: phone));
showDialog(
context: context,
builder: (BuildContext context) {
return BlocProvider<AuthBloc>(
create: (context) => authBlocDialog,
child: BlocConsumer<AuthBloc, AuthState>(
listener: (context, state) {
if (state is AuthStateSuccess) {
// here update email and password autentication
// authBloc.add(
// AuthEventAddEmailAndPassword(
// email: _emailController.text,
// password: _passwordController.text,
// ),
// );
} else if (state is AuthStateVerifyOAuth && state.isWrongCode) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('El Código es incorrecto'),
));
}
},
builder: (context, state) {
return AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Text(
'Requiere autenticación porfavor ingresa tu contraseña',
textAlign: TextAlign.center,
),
const SizedBox(height: 20),
Text(
phone,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 20),
GeneralPrimaryButton(
onPressed: () {
// authBlocDialog.add(AuthEventVerifyOAuth(code: verificationCode));
},
label: 'Continuar',
),
],
),
);
},
),
);
});
}
String? _phoneNumber;
String? _errorMsg;
@override
Widget build(BuildContext context) {
return BlocProvider<AuthBloc>(
create: (context) => authBloc,
child: BlocConsumer<AuthBloc, AuthState>(
listener: (context, state) {},
builder: (context, state) {
return BlocBuilder<MyUserBloc, MyUserState>(
builder: (context, stateUser) {
if (stateUser.status == MyUserStatus.success) {
return Scaffold(
appBar: AppBar(
title: const Text('Agregar celular'),
),
body: Center(
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 40, vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
...switchContent(context, state),
],
),
),
),
),
);
} else {
return const Center(child: CircularProgressIndicator());
}
},
);
},
),
);
}
switchContent(
BuildContext context,
AuthState state,
) {
if (state is AuthStateInitial) {
return getContent(context);
}
if (state is AuthStateVerifyOAuth) {
return [
OtpTextField(
numberOfFields: 6,
fieldWidth: 35,
borderColor: const Color(0xFF512DA8),
showFieldAsBox: true,
onCodeChanged: (String code) {
verificationCode = code;
},
onSubmit: (String verificationCode) {
authBloc.add(LinkWithPhoneNumberOtp(
phoneNumber: _phoneNumber!, code: verificationCode));
},
),
];
}
if (state is AuthStateSuccess) {
return [
const Text('Tu celular ha sido agregado'),
];
}
if (state is AuthStateFailure) {
return [
Text(state.message ?? "Error inesperado. 🥸"),
];
}
return [
const CircularProgressIndicator(),
];
}
getContent(BuildContext context) {
double width = MediaQuery.of(context).size.width;
return [
SizedBox(
width: double.infinity,
child: Text(
'Numero de celular',
style: TextStyle(
fontSize: width * 0.045,
color: Theme.of(context).colorScheme.onBackground,
),
),
),
IntlPhoneField(
initialCountryCode: 'CO',
keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
validator: (value) {
if (value == null) {
return 'Ingresa un numero';
} else {
return null;
}
},
onChanged: (phone) {
_phoneNumber = phone.completeNumber;
log('xd ${_phoneNumber!}');
},
decoration: GeneralInputDecoration.getCustomDecoration(
context: context,
hintText: 'Ingresa tu numero',
errorMsg: _errorMsg,
),
),
const SizedBox(height: 10),
// TextFormField(
// controller: _actualPasswordController,
// obscureText: true,
// decoration: const InputDecoration(
// labelText: 'Contraseña actual',
// prefixIcon: Icon(Icons.lock_rounded),
// hintText: 'Contraseña',
// border: OutlineInputBorder(
// borderRadius: BorderRadius.all(
// Radius.circular(10.0),
// )),
// errorBorder: OutlineInputBorder(
// borderSide: BorderSide(color: Colors.red),
// ),
// focusedErrorBorder: OutlineInputBorder(
// borderSide: BorderSide(color: Colors.red, width: 2.0),
// ),
// ),
// validator: (value) {
// if (value == null || value.isEmpty) {
// return 'Por favor, ingrese su contraseña';
// }
// return null;
// },
// ),
const SizedBox(height: 15),
Center(
child: Text(
'Un código será enviado a este numero de celular.',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 13.0,
color: Theme.of(context).colorScheme.onBackground,
),
),
),
const SizedBox(height: 10),
Center(
child: GeneralPrimaryButton(
onPressed: () async {
final phoneNumber = _phoneNumber;
if (phoneNumber == null || phoneNumber.isEmpty) {
ScaffoldMessenger.of(context).clearSnackBars();
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Por favor, ingresa un numero'),
));
return;
}
authBloc.add(LinkWithPhoneNumber(
phoneNumber: phoneNumber,
));
},
label: 'Enviar código',
),
),
];
}
}
+44 -43
View File
@@ -11,8 +11,9 @@ import 'package:prosappco/blocs/profile_bloc/profile_bloc.dart';
import 'package:prosappco/components/birthday_picker.dart'; import 'package:prosappco/components/birthday_picker.dart';
import 'package:prosappco/components/gender_dropdown.dart'; import 'package:prosappco/components/gender_dropdown.dart';
import 'package:prosappco/screens/profile/components/profile_item.dart'; import 'package:prosappco/screens/profile/components/profile_item.dart';
import 'package:prosappco/screens/profile/profile_email_screen.dart'; import 'package:prosappco/screens/profile/profile_register_email_screen.dart';
import 'package:prosappco/screens/profile/profile_phone_screen.dart'; import 'package:prosappco/screens/profile/profile_register_phone_screen.dart';
import 'package:prosappco/screens/profile/profile_update_password_screen.dart';
class ProfileScreen extends StatefulWidget { class ProfileScreen extends StatefulWidget {
const ProfileScreen({super.key}); const ProfileScreen({super.key});
@@ -149,42 +150,54 @@ class _ProfileScreenState extends State<ProfileScreen> {
: const SizedBox(), : const SizedBox(),
const SizedBox(height: 20), const SizedBox(height: 20),
ProfileItem( ProfileItem(
title: 'Iniciar sesión con correo', title: 'Configurar inicio de sesión con correo',
subtitle: _emailController.text, subtitle: _emailController.text,
leading: Icons.email_rounded, leading: Icons.email_rounded,
onTap: () { onTap: () {
if (state.user!.name == null || if (state.user!.name == null ||
state.user!.name == '') { state.user!.name == '') {
ScaffoldMessenger.of(context) ScaffoldMessenger.of(context).showSnackBar(
.showSnackBar(const SnackBar( const SnackBar(
content: Text('Por favor, ingrese su nombre'), content: Text(
)); 'Por favor, ingrese su nombre')));
return; return;
} }
Navigator.push( Navigator.push(
context, context,
CupertinoPageRoute( CupertinoPageRoute(
builder: (context) => builder: (context) =>
const ProfileEmailScreen(), _emailController.text.isEmpty
), ? ProfileRegisterEmailScreen()
: ProfileUpdatePasswordScreen(
email: _emailController.text)),
); );
}, },
), ),
const SizedBox(height: 20), const SizedBox(height: 20),
ProfileItem( ProfileItem(
title: 'Iniciar sesión con teléfono', title: 'Configurar inicio de sesión con celular',
subtitle: _phoneController.text, subtitle: _phoneController.text,
leading: Icons.phone_iphone_rounded, leading: Icons.phone_iphone_rounded,
onTap: () { onTap: () {
Navigator.push( if (state.user!.name == null ||
context, state.user!.name == '') {
CupertinoPageRoute( ScaffoldMessenger.of(context).showSnackBar(
builder: (context) => const SnackBar(
const ProfilePhoneScreen(), content: Text(
), 'Por favor, ingrese su nombre')));
); return;
}
if (_phoneController.text.isEmpty) {
Navigator.push(
context,
CupertinoPageRoute(
builder: (context) =>
const ProfileRegisterPhoneScreen(),
),
);
}
}, },
), ),
const SizedBox(height: 60.0), const SizedBox(height: 60.0),
@@ -210,42 +223,30 @@ class _ProfileScreenState extends State<ProfileScreen> {
return; return;
} }
// if (enableLoginWithEmail) { if (_nameController.text.isEmpty) {
// if (_newEmailController.text.isEmpty) { ScaffoldMessenger.of(context).clearSnackBars();
// return;
// }
// if (_passwordController.text.isEmpty) { ScaffoldMessenger.of(context).showSnackBar(
// return; const SnackBar(content: Text('Por favor, ingrese su nombre')),
// } );
// context.read<AuthBloc>().add( return;
// AuthEventAddEmailAndPassword( }
// email: _newEmailController.text,
// password: _passwordController.text,
// ),
// );
// _emailController.text = _newEmailController.text;
// }
final myUser = state.user!.copyWith( final myUser = state.user!.copyWith(
name: _nameController.text, name: _nameController.text,
nickname: _nameController.text.trim().toLowerCase(),
email: _emailController.text, email: _emailController.text,
phone: _phoneController.text, phone: _phoneController.text,
birthday: _birthdayController.text, birthday: _birthdayController.text,
gender: _genderController.text, gender: _genderController.text,
nickname: _nameController.text.trim().toLowerCase(),
); );
context.read<ProfileBloc>().add( context
UpdateUserInfo( .read<ProfileBloc>()
myUser: myUser, .add(UpdateUserInfo(myUser: myUser, filePicture: _imageFile?.path));
filePicture: _imageFile?.path,
),
);
// Navigator.pop(context); Navigator.pop(context);
}, },
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue, backgroundColor: Colors.blue,
@@ -0,0 +1,180 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:injector/injector.dart';
import 'package:prosappco/blocs/auth_bloc/auth_bloc.dart';
import 'package:prosappco/components/general_primary_button.dart';
class ProfileUpdatePasswordScreen extends StatefulWidget {
final String email;
const ProfileUpdatePasswordScreen({super.key, required this.email});
@override
State<ProfileUpdatePasswordScreen> createState() =>
_ProfileUpdatePasswordScreenState();
}
class _ProfileUpdatePasswordScreenState
extends State<ProfileUpdatePasswordScreen> {
final TextEditingController _actualPasswordController =
TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final TextEditingController _confirmPasswordController =
TextEditingController();
@override
Widget build(BuildContext context) {
final authBloc = Injector.appInstance.get<AuthBloc>();
return BlocProvider<AuthBloc>(
create: (context) => authBloc,
child: BlocConsumer<AuthBloc, AuthState>(
listener: (context, state) {
if (state is AuthStateSuccess) {
Navigator.of(context).pop();
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Se actualizo la contraseña.🥳'),
));
} else if (state is AuthStateFailure) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(state.message ?? 'Error inesperado. 🥸'),
));
}
},
builder: (context, state) {
return Scaffold(
appBar: AppBar(
title: const Text('Actualizar contraseña'),
),
body: Center(
child: SingleChildScrollView(
child: Padding(
padding:
const EdgeInsets.symmetric(horizontal: 40, vertical: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextFormField(
controller: _actualPasswordController,
obscureText: true,
decoration: const InputDecoration(
labelText: 'Contraseña actual',
prefixIcon: Icon(Icons.lock_rounded),
hintText: 'Contraseña',
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(10.0),
)),
errorBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red),
),
focusedErrorBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.red, width: 2.0),
),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Por favor, ingrese su contraseña';
}
return null;
},
),
const SizedBox(height: 20),
TextFormField(
controller: _passwordController,
obscureText: true,
decoration: const InputDecoration(
labelText: 'Nueva contraseña',
prefixIcon: Icon(Icons.lock_rounded),
hintText: 'Contraseña',
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(10.0),
)),
errorBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red),
),
focusedErrorBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.red, width: 2.0),
),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Por favor, ingrese su contraseña';
}
return null;
},
),
const SizedBox(height: 20),
TextFormField(
controller: _confirmPasswordController,
obscureText: true,
decoration: const InputDecoration(
labelText: 'Confirmar contraseña',
prefixIcon: Icon(Icons.lock_rounded),
hintText: 'Contraseña',
border: OutlineInputBorder(
borderRadius: BorderRadius.all(
Radius.circular(10.0),
)),
errorBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red),
),
focusedErrorBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.red, width: 2.0),
),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Por favor, ingrese su contraseña';
}
return null;
},
),
const SizedBox(height: 30),
GeneralPrimaryButton(
onPressed: () {
if (_actualPasswordController.text.isEmpty) {
return;
}
if (_passwordController.text.isEmpty) {
return;
}
if (_confirmPasswordController.text.isEmpty) {
return;
}
if (_passwordController.text !=
_confirmPasswordController.text) {
return;
}
if (_actualPasswordController.text ==
_passwordController.text &&
_actualPasswordController.text ==
_confirmPasswordController.text) {
return;
}
authBloc.add(AuthEventUpdatePassword(
email: widget.email,
password: _passwordController.text,
actualPassword: _actualPasswordController.text));
},
label: 'Actualizar contraseña',
),
],
),
),
),
),
);
},
),
);
}
}
@@ -167,6 +167,14 @@ class FirebaseUserRepository implements UserRepository {
await _firebaseAuth.currentUser!.updateEmail(email); await _firebaseAuth.currentUser!.updateEmail(email);
await _firebaseAuth.currentUser!.updatePassword(password); await _firebaseAuth.currentUser!.updatePassword(password);
final user = await getMyUser(_firebaseAuth.currentUser!.uid);
if (user == null) {
return "user-not-found";
}
final newUser = user.copyWith(email: email);
await updateUserInfo(newUser);
return null; return null;
} catch (e) { } catch (e) {
if (e is FirebaseAuthException && e.code == 'requires-recent-login') { if (e is FirebaseAuthException && e.code == 'requires-recent-login') {
@@ -181,6 +189,95 @@ class FirebaseUserRepository implements UserRepository {
} }
} }
@override
addPhoneAuthCredential(String password, String phoneNumber,
{required Future<void> Function(FirebaseAuthException) verificationFailed,
required Future<void> Function(String) codeSent,
required Future<void> Function(String) codeAutoRetrievalTimeout}) async {
await _firebaseAuth.verifyPhoneNumber(
phoneNumber: phoneNumber,
timeout: const Duration(seconds: 60),
verificationCompleted: (AuthCredential authCredential) async {
// La verificación se completó automáticamente.
// TODO: Revisar si es necesario.
},
verificationFailed: (FirebaseAuthException authException) async {
// La verificación falló.
// throw authException;
log('verificationFailed: $authException');
await verificationFailed(authException);
},
codeAutoRetrievalTimeout: (String verificationId) async {
// Tiempo de espera agotado para la recuperación automática del código.
// throw 'timeout';
log(verificationId);
await codeAutoRetrievalTimeout(verificationId);
},
codeSent: (String verificationId, int? resendToken) async {
await codeSent(verificationId);
},
);
}
@override
Future<bool> linkWithOTP(
String phoneNumber, String verificationId, String code) async {
try {
var phoneAuthCredential = PhoneAuthProvider.credential(
verificationId: verificationId, smsCode: code);
User? userAuth = FirebaseAuth.instance.currentUser;
if (userAuth == null) {
throw 'User not found';
}
final user = await getMyUser(_firebaseAuth.currentUser!.uid);
if (user == null) {
throw "user-not-found";
}
await userAuth.linkWithCredential(phoneAuthCredential);
final newUser = user.copyWith(phone: phoneNumber);
await updateUserInfo(newUser);
return true;
} catch (e) {
if (e is FirebaseAuthException) {
if (e.code == 'invalid-verification-code') {
return false;
} else {
rethrow;
}
} else {
rethrow;
}
}
}
@override
Future<UpdatePassworErros?> updatePassword(
String password, String newPassword) async {
try {
User? user = FirebaseAuth.instance.currentUser;
if (user == null) {
return UpdatePassworErros.userNotFound;
}
// Verificar la autenticación reciente
await user.reauthenticateWithCredential(EmailAuthProvider.credential(
email: user.email!,
password: password,
));
await _firebaseAuth.currentUser!.updatePassword(newPassword);
return null;
} catch (e) {
log(e.toString());
return UpdatePassworErros.unknown;
}
}
// Sign out // Sign out
@override @override
Future<void> logOut() async { Future<void> logOut() async {
@@ -1,3 +1,5 @@
import 'package:firebase_auth/firebase_auth.dart';
import '../../user_repository.dart'; import '../../user_repository.dart';
abstract class UserRepository { abstract class UserRepository {
@@ -8,6 +10,9 @@ abstract class UserRepository {
Future<String?> addEmailAndPassword(String email, String password); Future<String?> addEmailAndPassword(String email, String password);
Future<UpdatePassworErros?> updatePassword(
String password, String newPassword);
Future<void> logOut(); Future<void> logOut();
Future<MyUser> signUp(MyUser myUser, String password); Future<MyUser> signUp(MyUser myUser, String password);
@@ -16,6 +21,17 @@ abstract class UserRepository {
Future<bool> verifyOTP(String code); Future<bool> verifyOTP(String code);
Future<void> addPhoneAuthCredential(String password, String phoneNumber,
{
required Future<void> Function(FirebaseAuthException) verificationFailed,
required Future<void> Function(String) codeSent,
required Future<void> Function(String) codeAutoRetrievalTimeout
});
Future<bool> linkWithOTP(
String phoneNumber, String verificationId, String code);
Future<void> resetPassword(String email); Future<void> resetPassword(String email);
Future<void> setUserData(MyUser user); Future<void> setUserData(MyUser user);
@@ -28,3 +44,5 @@ abstract class UserRepository {
Future<void> createUser(MyUser myUser); Future<void> createUser(MyUser myUser);
} }
enum UpdatePassworErros { credentialsWrong, userNotFound, unknown }
@@ -0,0 +1,76 @@
import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';
class PhoneVerificationService {
final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
Stream<PhoneAuthEvent> verifyPhoneNumber(String phoneNumber) async* {
final StreamController<PhoneAuthEvent> phoneAuthController =
StreamController<PhoneAuthEvent>();
_firebaseAuth.verifyPhoneNumber(
phoneNumber: phoneNumber,
timeout: const Duration(seconds: 60),
verificationCompleted: (AuthCredential authCredential) async {
phoneAuthController
.add(PhoneAuthEvent.verificationCompleted(authCredential));
},
verificationFailed: (FirebaseAuthException authException) async {
phoneAuthController
.add(PhoneAuthEvent.verificationFailed(authException));
phoneAuthController.close();
},
codeAutoRetrievalTimeout: (String verificationId) async {
phoneAuthController
.add(PhoneAuthEvent.codeAutoRetrievalTimeout(verificationId));
},
codeSent: (String verificationId, int? resendToken) async {
phoneAuthController
.add(PhoneAuthEvent.codeSent(verificationId, resendToken));
},
);
await for (PhoneAuthEvent event in phoneAuthController.stream) {
yield event;
if (event.type == PhoneAuthEventType.verificationFailed) {
await phoneAuthController.close();
break;
}
}
}
}
enum PhoneAuthEventType {
verificationCompleted,
verificationFailed,
codeAutoRetrievalTimeout,
codeSent,
}
class PhoneAuthEvent {
final PhoneAuthEventType type;
final dynamic data;
PhoneAuthEvent(this.type, this.data);
static PhoneAuthEvent verificationCompleted(AuthCredential authCredential) {
return PhoneAuthEvent(
PhoneAuthEventType.verificationCompleted, authCredential);
}
static PhoneAuthEvent verificationFailed(
FirebaseAuthException authException) {
return PhoneAuthEvent(PhoneAuthEventType.verificationFailed, authException);
}
static PhoneAuthEvent codeAutoRetrievalTimeout(String verificationId) {
return PhoneAuthEvent(
PhoneAuthEventType.codeAutoRetrievalTimeout, verificationId);
}
static PhoneAuthEvent codeSent(String verificationId, int? resendToken) {
return PhoneAuthEvent(PhoneAuthEventType.codeSent,
{'verificationId': verificationId, 'resendToken': resendToken});
}
}
@@ -2,5 +2,6 @@ library user_repository;
export 'src/models/models.dart'; export 'src/models/models.dart';
export 'src/entities/entities.dart'; export 'src/entities/entities.dart';
export 'src/services/phone_verification_service.dart';
export 'src/repositories/user_repo.dart'; export 'src/repositories/user_repo.dart';
export 'src/repositories/firebase_user_repository.dart'; export 'src/repositories/firebase_user_repository.dart';