oke pembaruan auth ke google

This commit is contained in:
kleponijo 2026-04-05 20:33:12 +07:00
parent 75d9e3220e
commit 499bf7d568
8 changed files with 434 additions and 339 deletions

View File

@ -8,9 +8,7 @@ part 'sign_in_state.dart';
class SignInBloc extends Bloc<SignInEvent, SignInState> { class SignInBloc extends Bloc<SignInEvent, SignInState> {
final UserRepository _userRepository; final UserRepository _userRepository;
SignInBloc( SignInBloc(this._userRepository) : super(SignInInitial()) {
this._userRepository
) : super(SignInInitial()) {
on<SignInRequired>((event, emit) async { on<SignInRequired>((event, emit) async {
emit(SignInProcess()); emit(SignInProcess());
try { try {
@ -20,6 +18,15 @@ class SignInBloc extends Bloc<SignInEvent, SignInState> {
} }
}); });
on<GoogleSignInRequired>((event, emit) async {
emit(SignInProcess());
try {
await _userRepository.signInWithGoogle();
} catch (e) {
emit(SignInFailure());
}
});
on<SignOutRequired>((event, emit) async => await _userRepository.logOut()); on<SignOutRequired>((event, emit) async => await _userRepository.logOut());
} }
} }

View File

@ -17,6 +17,6 @@ class SignInRequired extends SignInEvent {
List<Object> get props => [email, password]; List<Object> get props => [email, password];
} }
class SignOutRequired extends SignInEvent { class GoogleSignInRequired extends SignInEvent {}
} class SignOutRequired extends SignInEvent {}

View File

@ -12,12 +12,23 @@ class SignUpBloc extends Bloc<SignUpEvent, SignUpState> {
on<SignUpRequired>((event, emit) async { on<SignUpRequired>((event, emit) async {
emit(SignUpProcess()); emit(SignUpProcess());
try { try {
MyUser myUser = await _userRepository.signUp(event.user, event.password); MyUser myUser =
await _userRepository.signUp(event.user, event.password);
await _userRepository.setUserData(myUser); await _userRepository.setUserData(myUser);
emit(SignUpSuccess()); emit(SignUpSuccess());
} catch (e) { } catch (e) {
emit(SignUpFailure(e.toString())); emit(SignUpFailure(e.toString()));
} }
}); });
on<GoogleSignInRequired>((event, emit) async {
emit(SignUpProcess());
try {
await _userRepository.signInWithGoogle();
emit(SignUpSuccess());
} catch (e) {
emit(SignUpFailure(e.toString()));
}
});
} }
} }

View File

@ -16,3 +16,5 @@ class SignUpRequired extends SignUpEvent {
@override @override
List<Object> get props => [user, password]; List<Object> get props => [user, password];
} }
class GoogleSignInRequired extends SignUpEvent {}

View File

@ -13,125 +13,149 @@ class SignInScreen extends StatefulWidget {
} }
class _SignInScreenState extends State<SignInScreen> { class _SignInScreenState extends State<SignInScreen> {
final passwordController = TextEditingController(); final passwordController = TextEditingController();
final emailController = TextEditingController(); final emailController = TextEditingController();
final _formKey = GlobalKey<FormState>(); final _formKey = GlobalKey<FormState>();
bool signInRequired = false; bool signInRequired = false;
IconData iconPassword = CupertinoIcons.eye_fill; IconData iconPassword = CupertinoIcons.eye_fill;
bool obscurePassword = true; bool obscurePassword = true;
String? _errorMsg; String? _errorMsg;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return BlocListener<SignInBloc, SignInState>( return BlocListener<SignInBloc, SignInState>(
listener: (context, state) { listener: (context, state) {
if(state is SignInSuccess) { if (state is SignInSuccess) {
setState(() { setState(() {
signInRequired = false; signInRequired = false;
}); });
} else if(state is SignInProcess) { } else if (state is SignInProcess) {
setState(() { setState(() {
signInRequired = true; signInRequired = true;
}); });
} else if(state is SignInFailure) { } else if (state is SignInFailure) {
setState(() { setState(() {
signInRequired = false; signInRequired = false;
_errorMsg = 'Invalid email or password'; _errorMsg = 'Invalid email or password';
}); });
} }
}, },
child: Form( child: Form(
key: _formKey, key: _formKey,
child: Column( child: Column(
children: [ children: [
const SizedBox(height: 20), const SizedBox(height: 20),
SizedBox( SizedBox(
width: MediaQuery.of(context).size.width * 0.9, width: MediaQuery.of(context).size.width * 0.9,
child: MyTextField( child: MyTextField(
controller: emailController, controller: emailController,
hintText: 'Email', hintText: 'Email',
obscureText: false, obscureText: false,
keyboardType: TextInputType.emailAddress, keyboardType: TextInputType.emailAddress,
prefixIcon: const Icon(CupertinoIcons.mail_solid), prefixIcon: const Icon(CupertinoIcons.mail_solid),
errorMsg: _errorMsg, errorMsg: _errorMsg,
validator: (val) { validator: (val) {
if (val!.isEmpty) { if (val!.isEmpty) {
return 'Please fill in this field'; return 'Please fill in this field';
} }
return null; return null;
} })),
) const SizedBox(height: 10),
), SizedBox(
const SizedBox(height: 10), width: MediaQuery.of(context).size.width * 0.9,
SizedBox( child: MyTextField(
width: MediaQuery.of(context).size.width * 0.9, controller: passwordController,
child: MyTextField( hintText: 'Password',
controller: passwordController, obscureText: obscurePassword,
hintText: 'Password', keyboardType: TextInputType.visiblePassword,
obscureText: obscurePassword, prefixIcon: const Icon(CupertinoIcons.lock_fill),
keyboardType: TextInputType.visiblePassword, errorMsg: _errorMsg,
prefixIcon: const Icon(CupertinoIcons.lock_fill), validator: (val) {
errorMsg: _errorMsg, if (val!.isEmpty) {
validator: (val) { return 'Please fill in this field';
if (val!.isEmpty) { }
return 'Please fill in this field'; return null;
}
return null;
},
suffixIcon: IconButton(
onPressed: () {
setState(() {
obscurePassword = !obscurePassword;
if(obscurePassword) {
iconPassword = CupertinoIcons.eye_fill;
} else {
iconPassword = CupertinoIcons.eye_slash_fill;
}
});
}, },
icon: Icon(iconPassword), suffixIcon: IconButton(
onPressed: () {
setState(() {
obscurePassword = !obscurePassword;
if (obscurePassword) {
iconPassword = CupertinoIcons.eye_fill;
} else {
iconPassword = CupertinoIcons.eye_slash_fill;
}
});
},
icon: Icon(iconPassword),
),
), ),
), ),
), const SizedBox(height: 20),
const SizedBox(height: 20), !signInRequired
!signInRequired ? SizedBox(
? SizedBox( width: MediaQuery.of(context).size.width * 0.5,
width: MediaQuery.of(context).size.width * 0.5, child: TextButton(
child: TextButton( onPressed: () {
onPressed: () { if (_formKey.currentState!.validate()) {
if (_formKey.currentState!.validate()) { context.read<SignInBloc>().add(SignInRequired(
context.read<SignInBloc>().add(SignInRequired( emailController.text,
emailController.text, passwordController.text));
passwordController.text) }
); },
} style: TextButton.styleFrom(
}, elevation: 3.0,
style: TextButton.styleFrom( backgroundColor:
elevation: 3.0, Theme.of(context).colorScheme.primary,
backgroundColor: Theme.of(context).colorScheme.primary, foregroundColor: Colors.white,
foregroundColor: Colors.white, shape: RoundedRectangleBorder(
shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(60))),
borderRadius: BorderRadius.circular(60) child: const Padding(
) padding: EdgeInsets.symmetric(
), horizontal: 25, vertical: 5),
child: const Padding( child: Text(
padding: EdgeInsets.symmetric(horizontal: 25, vertical: 5), 'Sign In',
child: Text( textAlign: TextAlign.center,
'Sign In', style: TextStyle(
textAlign: TextAlign.center, color: Colors.white,
style: TextStyle( fontSize: 16,
color: Colors.white, fontWeight: FontWeight.w600),
fontSize: 16, ),
fontWeight: FontWeight.w600 )),
),
),
) )
: const CircularProgressIndicator(),
const SizedBox(height: 20),
SizedBox(
width: MediaQuery.of(context).size.width * 0.5,
child: TextButton.icon(
onPressed: () {
context.read<SignInBloc>().add(GoogleSignInRequired());
},
icon: const Text(
'G',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.blue,
),
), ),
) label: const Text(
: const CircularProgressIndicator(), 'Sign In with Google',
], style: TextStyle(
) color: Colors.black,
), fontSize: 16,
); fontWeight: FontWeight.w600),
),
style: TextButton.styleFrom(
elevation: 3.0,
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(60),
side: const BorderSide(color: Colors.grey))),
),
),
],
)),
);
} }
} }

View File

@ -23,223 +23,266 @@ class _SignUpScreenState extends State<SignUpScreen> {
bool signUpRequired = false; bool signUpRequired = false;
bool containsUpperCase = false; bool containsUpperCase = false;
bool containsLowerCase = false; bool containsLowerCase = false;
bool containsNumber = false; bool containsNumber = false;
bool containsSpecialChar = false; bool containsSpecialChar = false;
bool contains8Length = false; bool contains8Length = false;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return BlocListener<SignUpBloc, SignUpState>( return BlocListener<SignUpBloc, SignUpState>(
listener: (context, state) { listener: (context, state) {
if (state is SignUpSuccess) { if (state is SignUpSuccess) {
setState(() { setState(() {
signUpRequired = false; signUpRequired = false;
}); });
} else if (state is SignUpProcess) { } else if (state is SignUpProcess) {
setState(() { setState(() {
signUpRequired = true; signUpRequired = true;
}); });
} else if (state is SignUpFailure) { } else if (state is SignUpFailure) {
return; return;
} }
}, },
child: Form( child: Form(
key: _formKey, key: _formKey,
child: Scaffold( child: Scaffold(
backgroundColor: Colors.white, backgroundColor: Colors.white,
body: Center( body: Center(
child: SingleChildScrollView( child: SingleChildScrollView(
child: Column( child: Column(
children: [ children: [
const SizedBox(height: 30), const SizedBox(height: 30),
Container( Container(
width: MediaQuery.of(context).size.width * 0.92, width: MediaQuery.of(context).size.width * 0.92,
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 22), padding: const EdgeInsets.symmetric(
decoration: BoxDecoration( horizontal: 20, vertical: 22),
color: Colors.white, decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12), color: Colors.white,
boxShadow: [ borderRadius: BorderRadius.circular(12),
BoxShadow( boxShadow: [
color: Colors.black.withOpacity(0.04), BoxShadow(
blurRadius: 10, color: Colors.black.withOpacity(0.04),
offset: const Offset(0, 4), blurRadius: 10,
) offset: const Offset(0, 4),
], )
), ],
child: Column( ),
crossAxisAlignment: CrossAxisAlignment.start, child: Column(
children: [ crossAxisAlignment: CrossAxisAlignment.start,
const SizedBox(height: 6), children: [
const Center( const SizedBox(height: 6),
child: Text( const Center(
'Buat Akun', child: Text(
style: TextStyle(fontSize: 22, fontWeight: FontWeight.w700), 'Buat Akun',
), style: TextStyle(
fontSize: 22, fontWeight: FontWeight.w700),
), ),
const SizedBox(height: 6), ),
const Center( const SizedBox(height: 6),
child: Text( const Center(
'Daftar untuk mulai monitoring', child: Text(
style: TextStyle(fontSize: 13, color: Colors.black54), 'Daftar untuk mulai monitoring',
), style:
TextStyle(fontSize: 13, color: Colors.black54),
), ),
const SizedBox(height: 14), ),
const SizedBox(height: 14),
// Name // Name
SizedBox( SizedBox(
width: MediaQuery.of(context).size.width * 0.9, width: MediaQuery.of(context).size.width * 0.9,
child: MyTextField( child: MyTextField(
controller: nameController, controller: nameController,
hintText: 'Masukkan nama lengkap', hintText: 'Masukkan nama lengkap',
obscureText: false, obscureText: false,
keyboardType: TextInputType.name, keyboardType: TextInputType.name,
prefixIcon: const Icon(CupertinoIcons.person_fill), prefixIcon: const Icon(CupertinoIcons.person_fill),
validator: (val) { validator: (val) {
if (val == null || val.isEmpty) { if (val == null || val.isEmpty) {
return 'Please fill in this field'; return 'Please fill in this field';
} else if (val.length > 50) { } else if (val.length > 50) {
return 'Name too long'; return 'Name too long';
} }
return null; return null;
},
),
),
const SizedBox(height: 10),
// Email
SizedBox(
width: MediaQuery.of(context).size.width * 0.9,
child: MyTextField(
controller: emailController,
hintText: 'nama@email.com',
obscureText: false,
keyboardType: TextInputType.emailAddress,
prefixIcon: const Icon(CupertinoIcons.mail_solid),
validator: (val) {
if (val == null || val.isEmpty) {
return 'Please fill in this field';
}
return null;
},
),
),
const SizedBox(height: 10),
// Password
SizedBox(
width: MediaQuery.of(context).size.width * 0.9,
child: MyTextField(
controller: passwordController,
hintText: 'Minimal 6 karakter',
obscureText: obscurePassword,
keyboardType: TextInputType.visiblePassword,
prefixIcon: const Icon(CupertinoIcons.lock_fill),
suffixIcon: IconButton(
onPressed: () {
setState(() {
obscurePassword = !obscurePassword;
iconPassword = obscurePassword
? CupertinoIcons.eye_fill
: CupertinoIcons.eye_slash_fill;
});
}, },
icon: Icon(iconPassword),
), ),
validator: (val) {
if (val == null || val.isEmpty) {
return 'Please fill in this field';
}
return null;
},
), ),
const SizedBox(height: 10), ),
const SizedBox(height: 10),
// Email // Confirm Password
SizedBox( SizedBox(
width: MediaQuery.of(context).size.width * 0.9, width: MediaQuery.of(context).size.width * 0.9,
child: MyTextField( child: MyTextField(
controller: emailController, controller: confirmPasswordController,
hintText: 'nama@email.com', hintText: 'Ulangi password',
obscureText: false, obscureText: obscurePassword,
keyboardType: TextInputType.emailAddress, keyboardType: TextInputType.visiblePassword,
prefixIcon: const Icon(CupertinoIcons.mail_solid), prefixIcon: const Icon(CupertinoIcons.lock_fill),
validator: (val) { validator: (val) {
if (val == null || val.isEmpty) { if (val == null || val.isEmpty) {
return 'Please fill in this field'; return 'Please fill in this field';
} } else if (val != passwordController.text) {
return null; return 'Password tidak cocok';
}, }
), return null;
},
), ),
const SizedBox(height: 10), ),
// Password const SizedBox(height: 18),
SizedBox(
width: MediaQuery.of(context).size.width * 0.9,
child: MyTextField(
controller: passwordController,
hintText: 'Minimal 6 karakter',
obscureText: obscurePassword,
keyboardType: TextInputType.visiblePassword,
prefixIcon: const Icon(CupertinoIcons.lock_fill),
suffixIcon: IconButton(
onPressed: () {
setState(() {
obscurePassword = !obscurePassword;
iconPassword = obscurePassword
? CupertinoIcons.eye_fill
: CupertinoIcons.eye_slash_fill;
});
},
icon: Icon(iconPassword),
),
validator: (val) {
if (val == null || val.isEmpty) {
return 'Please fill in this field';
}
return null;
},
),
),
const SizedBox(height: 10),
// Confirm Password // Button
SizedBox( !signUpRequired
width: MediaQuery.of(context).size.width * 0.9, ? SizedBox(
child: MyTextField( width: MediaQuery.of(context).size.width * 0.92,
controller: confirmPasswordController, child: ElevatedButton(
hintText: 'Ulangi password', onPressed: () {
obscureText: obscurePassword, if (_formKey.currentState!.validate()) {
keyboardType: TextInputType.visiblePassword, MyUser myUser = MyUser.empty;
prefixIcon: const Icon(CupertinoIcons.lock_fill), myUser.email = emailController.text;
validator: (val) { myUser.name = nameController.text;
if (val == null || val.isEmpty) {
return 'Please fill in this field';
} else if (val != passwordController.text) {
return 'Password tidak cocok';
}
return null;
},
),
),
const SizedBox(height: 18), setState(() {
context.read<SignUpBloc>().add(
// Button SignUpRequired(
!signUpRequired myUser,
? SizedBox( passwordController.text,
width: MediaQuery.of(context).size.width * 0.92, ),
child: ElevatedButton( );
onPressed: () { });
if (_formKey.currentState!.validate()) { }
MyUser myUser = MyUser.empty; },
myUser.email = emailController.text; style: ElevatedButton.styleFrom(
myUser.name = nameController.text; backgroundColor: Colors.black87,
foregroundColor: Colors.white,
setState(() { padding: const EdgeInsets.symmetric(
context.read<SignUpBloc>().add( vertical: 16),
SignUpRequired( shape: RoundedRectangleBorder(
myUser, borderRadius: BorderRadius.circular(8),
passwordController.text,
),
);
});
}
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.black87,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
child: const Text(
'Daftar',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
), ),
), ),
) child: const Text(
: const CircularProgressIndicator(), 'Daftar',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w600),
),
),
)
: const CircularProgressIndicator(),
const SizedBox(height: 12), const SizedBox(height: 12),
Center( Center(
child: Row( child: Text('Atau'),
mainAxisAlignment: MainAxisAlignment.center, ),
children: [ const SizedBox(height: 12),
const Text('Sudah punya akun? '), SizedBox(
TextButton( width: MediaQuery.of(context).size.width * 0.92,
onPressed: () { child: TextButton.icon(
Navigator.of(context).pop(); onPressed: () {
}, context
child: const Text('Login di sini'), .read<SignUpBloc>()
) .add(GoogleSignInRequired());
], },
icon: const Text(
'G',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.blue,
),
),
label: const Text(
'Daftar dengan Google',
style: TextStyle(
color: Colors.black,
fontSize: 16,
fontWeight: FontWeight.w600),
),
style: TextButton.styleFrom(
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
side: const BorderSide(color: Colors.grey)),
padding: const EdgeInsets.symmetric(vertical: 16),
), ),
), ),
], ),
), const SizedBox(height: 12),
Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Sudah punya akun? '),
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: const Text('Login di sini'),
)
],
),
),
],
), ),
const SizedBox(height: 30), ),
], const SizedBox(height: 30),
), ],
), ),
), ),
), ),
), ),
); ),
);
} }
} }

View File

@ -21,13 +21,15 @@ class FirebaseUserRepo implements UserRepository {
try { try {
final userData = await userCollection.doc(firebaseUser.uid).get(); final userData = await userCollection.doc(firebaseUser.uid).get();
if (userData.exists && userData.data() != null) { if (userData.exists && userData.data() != null) {
yield MyUser.fromEntity(MyUserEntity.fromDocument(userData.data()!)); yield MyUser.fromEntity(
MyUserEntity.fromDocument(userData.data()!));
} else { } else {
// User baru yang belum ada data di Firestore, tunggu sebentar // User baru yang belum ada data di Firestore, tunggu sebentar
await Future.delayed(const Duration(milliseconds: 500)); await Future.delayed(const Duration(milliseconds: 500));
final retryData = await userCollection.doc(firebaseUser.uid).get(); final retryData = await userCollection.doc(firebaseUser.uid).get();
if (retryData.exists && retryData.data() != null) { if (retryData.exists && retryData.data() != null) {
yield MyUser.fromEntity(MyUserEntity.fromDocument(retryData.data()!)); yield MyUser.fromEntity(
MyUserEntity.fromDocument(retryData.data()!));
} else { } else {
yield MyUser.empty; yield MyUser.empty;
} }
@ -40,32 +42,28 @@ class FirebaseUserRepo implements UserRepository {
}); });
} }
@override @override
Future<void> signIn(String email, String password) async { Future<void> signIn(String email, String password) async {
try { try {
await _firebaseAuth.signInWithEmailAndPassword( await _firebaseAuth.signInWithEmailAndPassword(
email: email, email: email, password: password);
password: password
);
} catch (e) { } catch (e) {
log(e.toString()); log(e.toString());
rethrow; rethrow;
} }
} }
@override @override
Future<MyUser> signUp(MyUser myUser, String password) async { Future<MyUser> signUp(MyUser myUser, String password) async {
try { try {
UserCredential user = await _firebaseAuth.createUserWithEmailAndPassword( UserCredential user = await _firebaseAuth.createUserWithEmailAndPassword(
email: myUser.email, email: myUser.email, password: password);
password: password myUser.userId = user.user!.uid;
); return myUser;
myUser.userId = user.user!.uid;
return myUser;
} catch (e) { } catch (e) {
log(e.toString()); log(e.toString());
rethrow; rethrow;
} }
} }
@override @override
@ -77,8 +75,8 @@ class FirebaseUserRepo implements UserRepository {
Future<void> setUserData(MyUser myUser) async { Future<void> setUserData(MyUser myUser) async {
try { try {
await userCollection await userCollection
.doc(myUser.userId) .doc(myUser.userId)
.set(myUser.toEntity().toDocument()); .set(myUser.toEntity().toDocument());
// Tunggu sebentar agar data tersimpan dengan baik sebelum stream update // Tunggu sebentar agar data tersimpan dengan baik sebelum stream update
await Future.delayed(const Duration(milliseconds: 500)); await Future.delayed(const Duration(milliseconds: 500));
} catch (e) { } catch (e) {
@ -87,6 +85,14 @@ class FirebaseUserRepo implements UserRepository {
} }
} }
@override
Future<void> signInWithGoogle() async {
try {
final GoogleAuthProvider googleProvider = GoogleAuthProvider();
await _firebaseAuth.signInWithPopup(googleProvider);
} catch (e) {
log('Google sign-in error: $e');
rethrow;
}
}
} }

View File

@ -3,11 +3,13 @@ import 'models/models.dart';
abstract class UserRepository { abstract class UserRepository {
Stream<MyUser?> get user; Stream<MyUser?> get user;
Future<MyUser> signUp(MyUser myUser, String password); Future<MyUser> signUp(MyUser myUser, String password);
Future<void> setUserData(MyUser user); Future<void> setUserData(MyUser user);
Future<void> signIn(String email, String password); Future<void> signIn(String email, String password);
Future<void> logOut(); Future<void> signInWithGoogle();
Future<void> logOut();
} }