login changes

This commit is contained in:
mohammad
2024-08-15 09:51:10 +03:00
parent 6efcc6081d
commit de46bc9872
8 changed files with 391 additions and 314 deletions

View File

@ -24,25 +24,33 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
on<PasswordVisibleEvent>(_passwordVisible); on<PasswordVisibleEvent>(_passwordVisible);
on<RegionInitialEvent>(_fetchRegion); on<RegionInitialEvent>(_fetchRegion);
on<SelectRegionEvent>(selectRegion); on<SelectRegionEvent>(selectRegion);
on<CheckEnableEvent>(checkEnable);
on<ChangeValidateEvent>(changeValidate);
} }
////////////////////////////// forget password ////////////////////////////////// ////////////////////////////// forget password //////////////////////////////////
final TextEditingController forgetEmailController = TextEditingController(); final TextEditingController forgetEmailController = TextEditingController();
final TextEditingController forgetPasswordController = TextEditingController(); final TextEditingController forgetPasswordController =
TextEditingController();
final TextEditingController forgetOtp = TextEditingController(); final TextEditingController forgetOtp = TextEditingController();
final forgetFormKey = GlobalKey<FormState>(); final forgetFormKey = GlobalKey<FormState>();
late bool checkValidate = false;
Timer? _timer; Timer? _timer;
int _remainingTime = 0; int _remainingTime = 0;
List<RegionModel>? regionList=[RegionModel(name: 'name', id: 'id')]; List<RegionModel>? regionList = [RegionModel(name: 'name', id: 'id')];
Future<void> _onStartTimer(StartTimerEvent event, Emitter<AuthState> emit) async { Future<void> _onStartTimer(
StartTimerEvent event, Emitter<AuthState> emit) async {
if (_validateInputs(emit)) return; if (_validateInputs(emit)) return;
if (_timer != null && _timer!.isActive) { if (_timer != null && _timer!.isActive) {
return; return;
} }
_remainingTime = 1; _remainingTime = 1;
add(UpdateTimerEvent(remainingTime: _remainingTime, isButtonEnabled: false)); add(UpdateTimerEvent(
_remainingTime = (await AuthenticationAPI.sendOtp(email: forgetEmailController.text,regionUuid: regionUuid))!; remainingTime: _remainingTime, isButtonEnabled: false));
_remainingTime = (await AuthenticationAPI.sendOtp(
email: forgetEmailController.text, regionUuid: regionUuid))!;
_timer = Timer.periodic(const Duration(seconds: 1), (timer) { _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
_remainingTime--; _remainingTime--;
if (_remainingTime <= 0) { if (_remainingTime <= 0) {
@ -85,10 +93,6 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
remainingTime: event.remainingTime)); remainingTime: event.remainingTime));
} }
///////////////////////////////////// login ///////////////////////////////////// ///////////////////////////////////// login /////////////////////////////////////
final TextEditingController loginEmailController = TextEditingController(); final TextEditingController loginEmailController = TextEditingController();
final TextEditingController loginPasswordController = TextEditingController(); final TextEditingController loginPasswordController = TextEditingController();
@ -106,6 +110,7 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
void _login(LoginButtonPressed event, Emitter<AuthState> emit) async { void _login(LoginButtonPressed event, Emitter<AuthState> emit) async {
emit(AuthLoading()); emit(AuthLoading());
if (isChecked) { if (isChecked) {
try { try {
if (event.username.isEmpty || event.password.isEmpty) { if (event.username.isEmpty || event.password.isEmpty) {
@ -117,12 +122,12 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
model: LoginWithEmailModel( model: LoginWithEmailModel(
email: event.username, email: event.username,
password: event.password, password: event.password,
regionUuid: event.regionUuid regionUuid: event.regionUuid),
),
); );
} catch (failure) { } catch (failure) {
validate='Something went wrong'; validate = 'Invalid Credentials!';
emit(const LoginFailure(error: 'Something went wrong')); emit(AuthInitialState());
// emit(const LoginFailure(error: 'Something went wrong'));
return; return;
} }
if (token.accessTokenIsNotEmpty) { if (token.accessTokenIsNotEmpty) {
@ -137,9 +142,11 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
loginPasswordController.clear(); loginPasswordController.clear();
emit(LoginSuccess()); emit(LoginSuccess());
} else { } else {
emit(const LoginFailure(error: 'Something went wrong')); emit(const LoginFailure(error: 'Something went wrong'));
} }
} else { } else {
emit(const LoginFailure(error: 'Accept terms and condition')); emit(const LoginFailure(error: 'Accept terms and condition'));
} }
} }
@ -147,13 +154,13 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
checkBoxToggle(CheckBoxEvent event, Emitter<AuthState> emit,) { checkBoxToggle(CheckBoxEvent event, Emitter<AuthState> emit,) {
emit(AuthLoading()); emit(AuthLoading());
isChecked = event.newValue!; isChecked = event.newValue!;
add(CheckEnableEvent());
emit(LoginInitial()); emit(LoginInitial());
} }
checkOtpCode(ChangePasswordEvent event, Emitter<AuthState> emit,) async { checkOtpCode(ChangePasswordEvent event, Emitter<AuthState> emit,) async {
emit(LoadingForgetState()); emit(LoadingForgetState());
await AuthenticationAPI.verifyOtp( await AuthenticationAPI.verifyOtp(email: forgetEmailController.text, otpCode: forgetOtp.text);
email: forgetEmailController.text, otpCode: forgetOtp.text);
emit(SuccessForgetState()); emit(SuccessForgetState());
} }
@ -163,30 +170,32 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
emit(PasswordVisibleState()); emit(PasswordVisibleState());
} }
void launchURL(String url) { void launchURL(String url) {}
}
/////////////////////////////////////VALIDATORS///////////////////////////////////// /////////////////////////////////////VALIDATORS/////////////////////////////////////
String? validatePassword(String? value) { String? validatePassword(String? value) {
if (value == null || value.isEmpty) { if (value == null || value.isEmpty) {
return 'Password is required'; return '';
} else if (value.length < 8) {
return 'Password must be at least 8 characters';
} }
return null; return null;
} }
String? validateEmail(String? value) { String? validateEmail(String? value) {
if (value == null || value.isEmpty) { if (value == null || value.isEmpty) {
return 'Email is required'; return 'Email is required';
} else if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(value)) { } else if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(value)) {
return 'Enter a valid email address'; return 'Enter a valid email address';
}else if (regionUuid=='') { } else if (regionUuid == '') {
return 'Please select your region'; return 'Please select your region';
} }
validate='';
return null;
}
String? loginValidateEmail(String? value) {
if (!RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(value!)) {
return '';
}
return null; return null;
} }
@ -277,17 +286,17 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
return '$maskedLocalPart@$domainPart'; return '$maskedLocalPart@$domainPart';
} }
static Future<String> getTokenAndValidate() async { static Future<String> getTokenAndValidate() async {
try { try {
const storage = FlutterSecureStorage(); const storage = FlutterSecureStorage();
final firstLaunch = await SharedPreferencesHelper.readBoolFromSP(StringsManager.firstLaunch) ?? true; final firstLaunch = await SharedPreferencesHelper.readBoolFromSP(
StringsManager.firstLaunch) ??
true;
if (firstLaunch) { if (firstLaunch) {
storage.deleteAll(); storage.deleteAll();
} }
await SharedPreferencesHelper.saveBoolToSP(StringsManager.firstLaunch, false); await SharedPreferencesHelper.saveBoolToSP(
StringsManager.firstLaunch, false);
final value = await storage.read(key: Token.loginAccessTokenKey) ?? ''; final value = await storage.read(key: Token.loginAccessTokenKey) ?? '';
if (value.isEmpty) { if (value.isEmpty) {
return 'Token not found'; return 'Token not found';
@ -315,16 +324,14 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
regionList = await AuthenticationAPI.fetchRegion(); regionList = await AuthenticationAPI.fetchRegion();
emit(AuthInitialState()); emit(AuthInitialState());
} catch (e) { } catch (e) {
emit( LoginFailure(error: e.toString())); emit(LoginFailure(error: e.toString()));
} }
} }
Future selectRegion(SelectRegionEvent event, Emitter<AuthState> emit) async { Future selectRegion(SelectRegionEvent event, Emitter<AuthState> emit) async {
try { try {
emit(AuthLoading()); emit(AuthLoading());
regionUuid= event.val; regionUuid = event.val;
emit(AuthInitialState()); emit(AuthInitialState());
} catch (e) { } catch (e) {
emit(FailureForgetState(error: e.toString())); emit(FailureForgetState(error: e.toString()));
@ -340,7 +347,8 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
final String formattedTime = [ final String formattedTime = [
if (days > 0) '${days}d', // Append 'd' for days if (days > 0) '${days}d', // Append 'd' for days
if (days > 0 || hours > 0) hours.toString().padLeft(2, '0'), // Show hours if there are days or hours if (days > 0 || hours > 0)
hours.toString().padLeft(2, '0'), // Show hours if there are days or hours
minutes.toString().padLeft(2, '0'), minutes.toString().padLeft(2, '0'),
seconds.toString().padLeft(2, '0'), seconds.toString().padLeft(2, '0'),
].join(':'); ].join(':');
@ -348,8 +356,19 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
return formattedTime; return formattedTime;
} }
bool checkEnable( CheckEnableEvent event, Emitter<AuthState> emit,) {
emit(AuthLoading());
checkValidate = isChecked==true &&
loginPasswordController.text.isNotEmpty &&
loginEmailController.text.isNotEmpty &&
regionUuid != '';
emit(LoginInitial());
return checkValidate;
}
changeValidate(ChangeValidateEvent event, Emitter<AuthState> emit,){
emit(AuthLoading());
validate='';
print('validate');
emit(LoginInitial());
}
} }

View File

@ -13,7 +13,7 @@ class LoginButtonPressed extends AuthEvent {
final String password; final String password;
final String regionUuid; final String regionUuid;
const LoginButtonPressed({required this.username, required this.password, required this.regionUuid}); const LoginButtonPressed({required this.username, required this.password, required this.regionUuid, });
@override @override
List<Object> get props => [username, password,regionUuid]; List<Object> get props => [username, password,regionUuid];
@ -53,6 +53,8 @@ class PasswordVisibleEvent extends AuthEvent{
} }
class RegionInitialEvent extends AuthEvent {} class RegionInitialEvent extends AuthEvent {}
class CheckEnableEvent extends AuthEvent {}
class ChangeValidateEvent extends AuthEvent {}
class SelectRegionEvent extends AuthEvent { class SelectRegionEvent extends AuthEvent {
final String val; final String val;

View File

@ -254,8 +254,7 @@ class ForgetPasswordWebPage extends StatelessWidget {
SizedBox( SizedBox(
child: TextFormField( child: TextFormField(
validator: forgetBloc.passwordValidator, validator: forgetBloc.passwordValidator,
keyboardType: keyboardType: TextInputType.visiblePassword,
TextInputType.visiblePassword,
controller: controller:
forgetBloc.forgetPasswordController, forgetBloc.forgetPasswordController,
decoration: textBoxDecoration()!.copyWith( decoration: textBoxDecoration()!.copyWith(

View File

@ -297,8 +297,7 @@ class LoginMobilePage extends StatelessWidget {
: ColorsManager.grayColor, : ColorsManager.grayColor,
child: const Text('Sign in'), child: const Text('Sign in'),
onPressed: () { onPressed: () {
if (loginBloc.loginFormKey.currentState! if (loginBloc.loginFormKey.currentState!.validate()) {
.validate()) {
loginBloc.add( loginBloc.add(
LoginButtonPressed( LoginButtonPressed(
regionUuid:'' , regionUuid:'' ,

View File

@ -1,7 +1,6 @@
import 'package:flutter/cupertino.dart'; import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart'; import 'package:flutter/widgets.dart';
import 'package:syncrow_web/pages/auth/view/login_mobile_page.dart';
import 'package:syncrow_web/pages/auth/view/login_web_page.dart'; import 'package:syncrow_web/pages/auth/view/login_web_page.dart';
import 'package:syncrow_web/utils/responsive_layout.dart'; import 'package:syncrow_web/utils/responsive_layout.dart';
@ -11,7 +10,7 @@ class LoginPage extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return const ResponsiveLayout( return const ResponsiveLayout(
desktopBody: LoginWebPage(), desktopBody: LoginWebPage(),
mobileBody:LoginMobilePage() mobileBody:LoginWebPage()
); );
} }
} }

View File

@ -48,11 +48,7 @@ class _LoginWebPageState extends State<LoginWebPage> {
} }
}, },
builder: (context, state) { builder: (context, state) {
if (state is AuthLoading) {
return const Center(child: CircularProgressIndicator());
} else {
return _buildLoginForm(context,state); return _buildLoginForm(context,state);
}
}, },
), ),
), ),
@ -75,7 +71,9 @@ class _LoginWebPageState extends State<LoginWebPage> {
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
_scrollToCenter(); _scrollToCenter();
}); });
return FirstLayer( return Stack(
children: [
FirstLayer(
second: Center( second: Center(
child: ListView( child: ListView(
controller: _scrollController, controller: _scrollController,
@ -129,43 +127,58 @@ class _LoginWebPageState extends State<LoginWebPage> {
children: [ children: [
Text( Text(
"Country/Region", "Country/Region",
style: Theme.of(context).textTheme.bodySmall, style: Theme.of(context).textTheme.bodySmall!.copyWith(fontSize: 14,fontWeight: FontWeight.w400),
), ),
const SizedBox(height: 10,), const SizedBox(height: 10,),
SizedBox( SizedBox(
child: DropdownButtonFormField<String>( child: DropdownButtonFormField<String>(
validator:loginBloc.validateRegion , padding: EdgeInsets.zero,
value: loginBloc.regionList!.any((region) => region.id == loginBloc.regionUuid)
? loginBloc.regionUuid
: null,
validator: loginBloc.validateRegion,
icon: const Icon( icon: const Icon(
Icons.keyboard_arrow_down_outlined, Icons.keyboard_arrow_down_outlined,
), ),
decoration: textBoxDecoration()!.copyWith( decoration: textBoxDecoration()!.copyWith(
hintText: null,), errorStyle: const TextStyle(height: 0),
hintText: null,
),
hint: SizedBox( hint: SizedBox(
width: size.width * 0.11, width: size.width * 0.12,
child: const Align( child: Align(
alignment: Alignment.centerLeft, alignment: Alignment.centerLeft,
child: Text( child: Text(
'Select your region/country', 'Select your region/country',
textAlign: TextAlign.center, textAlign: TextAlign.center,
style: TextStyle(fontSize: 14), style: Theme.of(context).textTheme.bodySmall!.copyWith(
color: ColorsManager.grayColor,
fontWeight: FontWeight.w400),
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
), ),
), ),
), ),
isDense: true, isDense: true,
style: const TextStyle(color: Colors.black), style: const TextStyle(color: Colors.black),
items:loginBloc.regionList!.map((RegionModel region) { items: loginBloc.regionList!.map((RegionModel region) {
return DropdownMenuItem<String>( return DropdownMenuItem<String>(
value: region.id, value: region.id,
child: Text(region.name), child: SizedBox(
width: size.width*0.06,
child: Text(region.name)),
); );
}).toList(), }).toList(),
onChanged: (String? value) { onChanged: (String? value) {
loginBloc.add(CheckEnableEvent());
loginBloc.add(SelectRegionEvent(val: value!,)); loginBloc.add(SelectRegionEvent(val: value!));
}, },
), ),
) )
], ],
), ),
const SizedBox(height: 20.0), const SizedBox(height: 20.0),
@ -174,16 +187,26 @@ class _LoginWebPageState extends State<LoginWebPage> {
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
children: [ children: [
Text("Email", Text("Email",
style: Theme.of(context).textTheme.bodySmall, style: Theme.of(context).textTheme.bodySmall!.copyWith(fontSize: 14,fontWeight: FontWeight.w400),
), ),
const SizedBox( const SizedBox(
height: 10, height: 10,
), ),
SizedBox( SizedBox(
child: TextFormField( child: TextFormField(
validator:loginBloc.validateEmail , onChanged: (value) {
loginBloc.add(CheckEnableEvent());
// print(loginBloc.checkEnable());
},
validator:loginBloc.loginValidateEmail ,
controller:loginBloc.loginEmailController, controller:loginBloc.loginEmailController,
decoration: textBoxDecoration()!.copyWith(hintText: 'Enter your email'), decoration: textBoxDecoration()!.copyWith(
errorStyle: const TextStyle(height: 0), // Hide the error text space
hintText: 'Enter your email address',
hintStyle: Theme.of(context).textTheme.bodySmall!.copyWith(
color: ColorsManager.grayColor,
fontWeight: FontWeight.w400)
),
style: const TextStyle(color: Colors.black), style: const TextStyle(color: Colors.black),
), ),
), ),
@ -194,18 +217,26 @@ class _LoginWebPageState extends State<LoginWebPage> {
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start,
children: [ children: [
Text("Password", style: Theme.of(context).textTheme.bodySmall,), Text("Password",
style: Theme.of(context).textTheme.bodySmall!.copyWith(fontSize: 14,fontWeight: FontWeight.w400),
),
const SizedBox( const SizedBox(
height: 10, height: 10,
), ),
SizedBox( SizedBox(
child: TextFormField( child: TextFormField(
onChanged: (value) {
loginBloc.add(CheckEnableEvent());
},
validator:loginBloc.validatePassword, validator:loginBloc.validatePassword,
obscureText:loginBloc.obscureText, obscureText:loginBloc.obscureText,
keyboardType: TextInputType.visiblePassword, keyboardType: TextInputType.visiblePassword,
controller:loginBloc.loginPasswordController, controller:loginBloc.loginPasswordController,
decoration: textBoxDecoration()!.copyWith( decoration: textBoxDecoration()!.copyWith(
hintText: 'At least 8 characters', hintText: 'At least 8 characters',
hintStyle: Theme.of(context).textTheme.bodySmall!.copyWith(
color: ColorsManager.grayColor,
fontWeight: FontWeight.w400),
suffixIcon: IconButton(onPressed: () { suffixIcon: IconButton(onPressed: () {
loginBloc.add(PasswordVisibleEvent(newValue: loginBloc.obscureText)); loginBloc.add(PasswordVisibleEvent(newValue: loginBloc.obscureText));
}, },
@ -218,7 +249,8 @@ class _LoginWebPageState extends State<LoginWebPage> {
width: 15, width: 15,
), ),
), ),
) ),
errorStyle: const TextStyle(height: 0), // Hide the error text space
), ),
style: const TextStyle(color: Colors.black), style: const TextStyle(color: Colors.black),
), ),
@ -238,7 +270,7 @@ class _LoginWebPageState extends State<LoginWebPage> {
}, },
child: Text( child: Text(
"Forgot Password?", "Forgot Password?",
style: Theme.of(context).textTheme.bodySmall, style: Theme.of(context).textTheme.bodySmall!.copyWith(color: Colors.black,fontSize: 14,fontWeight: FontWeight.w400),
), ),
), ),
], ],
@ -305,24 +337,39 @@ class _LoginWebPageState extends State<LoginWebPage> {
], ],
), ),
const SizedBox(height: 20.0), const SizedBox(height: 20.0),
Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox( SizedBox(
width:size.width * 0.2, width:size.width * 0.2,
child: DefaultButton( child: DefaultButton(
backgroundColor: loginBloc.isChecked? enabled: loginBloc.checkValidate,
ColorsManager.btnColor:ColorsManager.grayColor, child:Text('Sign in',
child: const Text('Sign in'), style: Theme.of(context).textTheme.labelLarge !.copyWith(
fontSize: 14,
color:
loginBloc.checkValidate ?
ColorsManager.whiteColors:ColorsManager.whiteColors.withOpacity(0.2),
)
),
onPressed: () { onPressed: () {
if (loginBloc.loginFormKey.currentState!.validate()) {
if(loginBloc.loginFormKey.currentState!.validate() ){
loginBloc.add(LoginButtonPressed( loginBloc.add(LoginButtonPressed(
regionUuid:loginBloc.regionUuid , regionUuid:loginBloc.regionUuid,
username: loginBloc.loginEmailController.text, username: loginBloc.loginEmailController.text,
password: loginBloc.loginPasswordController.text, password: loginBloc.loginPasswordController.text,
), ));
); }else{
loginBloc.add(ChangeValidateEvent());
} }
}, },
), ),
), ),
],
),
const SizedBox(height: 15.0), const SizedBox(height: 15.0),
Row( Row(
crossAxisAlignment: CrossAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,
@ -341,6 +388,10 @@ class _LoginWebPageState extends State<LoginWebPage> {
], ],
), ),
), ),
),
if (state is AuthLoading)
const Center(child: CircularProgressIndicator())
],
); );
} }
} }

View File

@ -59,7 +59,7 @@ class DefaultButton extends StatelessWidget {
(Set<MaterialState> states) { (Set<MaterialState> states) {
return enabled return enabled
? backgroundColor ?? ColorsManager.primaryColor ? backgroundColor ?? ColorsManager.primaryColor
: Colors.grey; : Colors.black.withOpacity(0.2);
}), }),
shape: MaterialStateProperty.all( shape: MaterialStateProperty.all(
RoundedRectangleBorder( RoundedRectangleBorder(

View File

@ -8,17 +8,25 @@ InputDecoration? textBoxDecoration({bool suffixIcon = false}) => InputDecoration
filled: true, // Enable background filling filled: true, // Enable background filling
fillColor: Colors.grey.shade200, // Set the background color fillColor: Colors.grey.shade200, // Set the background color
border: OutlineInputBorder( border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15), // Add border radius borderRadius: BorderRadius.circular(20), // Add border radius
borderSide: BorderSide.none, // Remove the underline borderSide: BorderSide.none, // Remove the underline
), ),
enabledBorder: OutlineInputBorder( enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15), // Add border radius borderRadius: BorderRadius.circular(20), // Add border radius
borderSide: BorderSide.none, // Remove the underline borderSide: BorderSide.none, // Remove the underline
), ),
focusedBorder: OutlineInputBorder( focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15), // Add border radius borderRadius: BorderRadius.circular(20), // Add border radius
borderSide: BorderSide.none, // Remove the underline borderSide: BorderSide.none, // Remove the underline
), ),
errorBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red, width: 2),
borderRadius: BorderRadius.circular(20),
),
focusedErrorBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.red, width: 2),
borderRadius: BorderRadius.circular(20),
),
); );