remove legacy router and auth

This commit is contained in:
2025-09-10 13:35:03 +02:00
parent 841a3adb74
commit 9f1877be95
5 changed files with 0 additions and 1512 deletions

View File

@@ -1,358 +0,0 @@
import 'package:flutter/material.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_layout/mih_print_prevew.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_objects/app_user.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_objects/arguments.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_package_components/Example/package_test.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_pop_up_messages/mih_notification_message.dart';
import 'package:mzansi_innovation_hub/mih_packages/about_mih/about_mih.dart';
import 'package:mzansi_innovation_hub/mih_packages/about_mih/mih_policy_tos_ext/mih_privacy_polocy_external.dart';
import 'package:mzansi_innovation_hub/mih_packages/about_mih/mih_policy_tos_ext/mih_terms_of_service_external.dart';
import 'package:mzansi_innovation_hub/mih_packages/access_review/mih_access.dart';
import 'package:mzansi_innovation_hub/mih_packages/authentication/auth_check.dart';
import 'package:mzansi_innovation_hub/mih_packages/authentication/forgot_password.dart';
// import 'package:mzansi_innovation_hub/mih_packages/authentication/reset_password.dart';
import 'package:mzansi_innovation_hub/mih_packages/calculator/mih_calculator.dart';
import 'package:mzansi_innovation_hub/mih_packages/calendar/mzansi_calendar.dart';
import 'package:mzansi_innovation_hub/mih_packages/mih_authentication/mih_authentication.dart';
import 'package:mzansi_innovation_hub/mih_packages/mzansi_ai/mzansi_ai.dart';
import 'package:mzansi_innovation_hub/mih_packages/mzansi_directory/mzansi_directory.dart';
import 'package:mzansi_innovation_hub/mih_packages/mzansi_profile/business_profile/mzansi_business_profile.dart';
import 'package:mzansi_innovation_hub/mih_packages/mzansi_profile/business_profile/mzansi_business_profile_view.dart';
import 'package:mzansi_innovation_hub/mih_packages/mzansi_profile/business_profile/profile_business_add.dart';
import 'package:mzansi_innovation_hub/mih_packages/mzansi_profile/personal_profile/mzansi_profile.dart';
import 'package:mzansi_innovation_hub/mih_packages/mzansi_profile/personal_profile/mzansi_profile_view.dart';
import 'package:mzansi_innovation_hub/mih_packages/mzansi_wallet/components/mih_barcode_scanner.dart';
import 'package:mzansi_innovation_hub/mih_packages/mzansi_wallet/mih_wallet.dart';
import 'package:mzansi_innovation_hub/mih_packages/patient_profile/pat_manager/pat_manager.dart';
import 'package:mzansi_innovation_hub/mih_packages/patient_profile/pat_profile/add_or_view_patient.dart';
import 'package:mzansi_innovation_hub/mih_packages/patient_profile/pat_profile/components/full_screen_file.dart';
import 'package:mzansi_innovation_hub/mih_packages/patient_profile/pat_profile/patient_add.dart';
import 'package:mzansi_innovation_hub/mih_packages/patient_profile/pat_profile/patient_edit.dart';
import 'package:mzansi_innovation_hub/mih_packages/patient_profile/pat_profile/patient_profile.dart';
// 1. Define Route Names as Constants
// This prevents typos and allows for easier refactoring.
// Consider moving this to a separate `lib/constants/app_routes.dart` file
// if your project grows larger.
class AppRoutes {
// External
static const String resetPasswordExternal = '/auth/reset-password';
static const String privacyPolicyExternal = '/privacy-policy';
static const String termsOfServiceExternal = '/terms-of-service';
// Internal
static const String authCheck = '/';
static const String mihAuthentication = '/mih-authentication';
static const String notifications = '/notifications';
static const String forgotPassword = '/forgot-password';
static const String aboutMih = '/about';
static const String mzansiProfile = '/mzansi-profile';
static const String mzansiProfileView = '/mzansi-profile/view';
static const String businessProfileSetup = '/business-profile/set-up';
static const String businessProfileManage = '/business-profile/manage';
static const String businessProfileView = '/business-profile/view';
static const String patientProfile = '/patient-profile';
static const String patientProfileSetup = '/patient-profile/set-up';
static const String patientProfileEdit = '/patient-profile/edit';
static const String mzansiWallet = '/mzansi-wallet';
static const String mzansiDirectory = '/mzansi-directory';
static const String mihAccess = '/mih-access';
static const String calendar = '/calendar';
static const String appointments = '/appointments';
static const String patientManager = '/patient-manager';
static const String patientManagerPatient = '/patient-manager/patient';
static const String fileViewer = '/file-veiwer';
static const String printPreview = '/file-veiwer/print-preview';
static const String barcodeScanner = '/scanner';
static const String calculator = '/calculator';
static const String mzansiAi = '/mzansi-ai';
static const String packageDevTest = '/package-dev';
}
class RouteGenerator {
static Route<dynamic> generateRoute(RouteSettings settings) {
final args = settings.arguments;
final extPath =
Uri.base.path; // Moved outside the internal switch for clarity
// 2. Prioritize External Links
// Using an if-else if chain for external routes might be slightly
// more performant than a switch if there are many external routes,
// as it avoids string hashing for each case. For a small number,
// a switch is also fine.
if (extPath == AppRoutes.resetPasswordExternal) {
// return MaterialPageRoute(
// settings: settings,
// builder: (_) => ResetPassword(token: Uri.base.queryParameters['token']),
// );
} else if (extPath == AppRoutes.privacyPolicyExternal) {
return MaterialPageRoute(
settings: settings,
builder: (_) => const MIHPrivacyPolocyExternal(),
);
} else if (extPath == AppRoutes.termsOfServiceExternal) {
return MaterialPageRoute(
settings: settings,
builder: (_) => const MIHTermsOfServiceExternal(),
);
}
// 3. Handle Internal Navigation with a Switch Statement
// This switch now only deals with internal app routes, making it cleaner.
switch (settings.name) {
case AppRoutes.authCheck:
if (args is AuthArguments) {
return MaterialPageRoute(
settings: settings,
builder: (_) => AuthCheck(
personalSelected: args.personalSelected,
firstBoot: args.firstBoot,
),
);
}
break; // Use break and fall through to _errorRoute if argument type is wrong
case AppRoutes.mihAuthentication:
// if (args is AuthArguments) {
return MaterialPageRoute(
settings: settings,
builder: (_) => MihAuthentication(),
);
// }
// break; // Use break and fall through to _errorRoute if argument type is wrong
case AppRoutes.mzansiDirectory:
if (args is MzansiDirectoryArguments) {
return MaterialPageRoute(
settings: settings,
builder: (_) => MzansiDirectory(arguments: args),
);
}
break;
case AppRoutes.notifications:
if (args is NotificationArguments) {
return MaterialPageRoute(
settings: settings,
builder: (_) => MIHNotificationMessage(arguments: args),
);
}
break;
case AppRoutes.forgotPassword:
return MaterialPageRoute(
settings: settings, builder: (_) => const ForgotPassword());
case AppRoutes.aboutMih:
if (args is int) {
return MaterialPageRoute(
settings: settings,
builder: (_) => AboutMih(packageIndex: args),
);
} else {
return MaterialPageRoute(
settings: settings,
builder: (_) => AboutMih(),
);
}
case AppRoutes.mzansiProfile:
if (args is AppProfileUpdateArguments) {
return MaterialPageRoute(
settings: settings,
builder: (_) => MzansiProfile(arguments: args),
);
}
break;
case AppRoutes.mzansiProfileView:
if (args is AppUser) {
return MaterialPageRoute(
settings: settings,
builder: (_) => MzansiProfileView(user: args),
);
}
break;
case AppRoutes.businessProfileSetup:
if (args is AppUser) {
return MaterialPageRoute(
settings: settings,
builder: (_) => ProfileBusinessAdd(signedInUser: args),
);
}
break;
case AppRoutes.businessProfileManage:
if (args is BusinessArguments) {
return MaterialPageRoute(
settings: settings,
builder: (_) => MzansiBusinessProfile(arguments: args),
);
}
break;
case AppRoutes.businessProfileView:
if (args is BusinessViewArguments) {
return MaterialPageRoute(
settings: settings,
builder: (_) => MzansiBusinessProfileView(arguments: args),
);
}
break;
case AppRoutes.patientProfile:
if (args is PatientViewArguments) {
return MaterialPageRoute(
settings: settings,
builder: (_) => AddOrViewPatient(arguments: args),
);
}
break;
case AppRoutes.patientProfileSetup:
if (args is AppUser) {
return MaterialPageRoute(
settings: settings,
builder: (_) => AddPatient(signedInUser: args),
);
}
break;
case AppRoutes.patientProfileEdit:
if (args is PatientEditArguments) {
return MaterialPageRoute(
settings: settings,
builder: (_) => EditPatient(
signedInUser: args.signedInUser,
selectedPatient: args.selectedPatient,
),
);
}
break;
case AppRoutes.mzansiWallet:
if (args is WalletArguments) {
return MaterialPageRoute(
settings: settings,
builder: (_) => MihWallet(arguments: args),
);
}
break;
case AppRoutes.mihAccess:
if (args is AppUser) {
return MaterialPageRoute(
settings: settings,
builder: (_) => MihAccess(signedInUser: args),
);
}
break;
// 4. Handle Calendar/Appointments - Unified to one case or keep separate as needed
case AppRoutes.calendar:
case AppRoutes
.appointments: // Fall-through if both lead to the same screen
if (args is CalendarArguments) {
return MaterialPageRoute(
settings: settings,
builder: (_) => MzansiCalendar(arguments: args),
);
}
break;
case AppRoutes.patientManager:
if (args is PatManagerArguments) {
return MaterialPageRoute(
settings: settings,
builder: (_) => PatManager(arguments: args),
);
}
break;
case AppRoutes.patientManagerPatient:
if (args is PatientViewArguments) {
return MaterialPageRoute(
settings: settings,
builder: (_) => PatientProfile(arguments: args),
);
}
break;
case AppRoutes.fileViewer:
if (args is FileViewArguments) {
return MaterialPageRoute(
settings: settings,
builder: (_) => FullScreenFileViewer(arguments: args),
);
}
break;
case AppRoutes.printPreview:
if (args is PrintPreviewArguments) {
return MaterialPageRoute(
settings: settings,
builder: (_) => MIHPrintPreview(arguments: args),
);
}
break;
case AppRoutes.barcodeScanner:
if (args is TextEditingController) {
return MaterialPageRoute(
settings: settings,
builder: (_) => MihBarcodeScanner(cardNumberController: args),
);
}
break;
case AppRoutes.calculator:
if (args is bool) {
return MaterialPageRoute(
settings: settings,
builder: (_) => MIHCalculator(personalSelected: args),
);
}
break;
case AppRoutes.mzansiAi:
if (args is MzansiAiArguments) {
return MaterialPageRoute(
settings: settings,
builder: (_) => MzansiAi(arguments: args),
);
}
break;
case AppRoutes.packageDevTest:
if (args is TestArguments) {
return MaterialPageRoute(
settings: settings,
builder: (_) => PackageTest(arguments: args),
);
}
break;
default:
// If no match is found, fall through to the error route
break;
}
// 5. Consolidated Error Route Call
// If any of the internal cases fail (e.g., wrong argument type or no matching route),
// it will fall through here.
return _errorRoute();
}
// 6. Refined Error Route
// Providing a simple, clear error message or redirection.
static Route<dynamic> _errorRoute() {
debugPrint(
"Invalid Route or Missing/Incorrect Arguments"); // Use debugPrint for development logs
return MaterialPageRoute(
settings: const RouteSettings(name: AppRoutes.authCheck),
builder: (_) => const AuthCheck(
personalSelected: true,
firstBoot: true,
),
);
}
}

View File

@@ -1,92 +0,0 @@
import 'package:mzansi_innovation_hub/mih_components/mih_pop_up_messages/mih_loading_circle.dart';
import 'package:mzansi_innovation_hub/mih_packages/authentication/biometric_check.dart';
import 'package:flutter/material.dart';
import 'package:mzansi_innovation_hub/mih_packages/mih_authentication/mih_authentication.dart';
import 'package:supertokens_flutter/supertokens.dart';
// import 'package:no_screenshot/no_screenshot.dart';
class AuthCheck extends StatefulWidget {
final bool personalSelected;
final bool firstBoot;
const AuthCheck({
super.key,
required this.personalSelected,
required this.firstBoot,
});
@override
State<AuthCheck> createState() => _AuthCheckState();
}
class _AuthCheckState extends State<AuthCheck> {
// final _noScreenshot = NoScreenshot.instance;
Future<bool> doesSessionExist() async {
//wait
//await Future.delayed(const Duration(seconds: 1));
bool signedIn = await SuperTokens.doesSessionExist();
return signedIn;
}
// void disableScreenshot() async {
// try {
// bool result = await _noScreenshot.screenshotOff();
// print('Screenshot Off: $result');
// } on Exception {
// print("Web");
// }
// }
@override
void initState() {
//signedIn = doesSessionExist();
// disableScreenshot(); Screenshot
// var brightness =
// SchedulerBinding.instance.platformDispatcher.platformBrightness;
// bool isDarkMode = brightness == Brightness.dark;
// if (isDarkMode) {
// MzansiInnovationHub.of(context)!.theme.mode = "Dark";
// } else {
// MzansiInnovationHub.of(context)!.theme.mode = "Light";
// }
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: OrientationBuilder(
builder: (BuildContext context, Orientation orientation) {
// Return a widget tree based on the orientation
return FutureBuilder(
future: doesSessionExist(),
builder: (context, snapshot) {
//print(snapshot.data);
if (snapshot.data == true) {
return BiometricCheck(
personalSelected: widget.personalSelected,
firstBoot: widget.firstBoot,
);
} else if (snapshot.data == false) {
return MihAuthentication();
} else {
return
// const SizedBox(width: 5, height: 5);
const Mihloadingcircle();
}
});
},
// child: FutureBuilder(
// future: signedIn,
// builder: (context, snapshot) {
// if (snapshot.data == true) {
// return const MIHProfileGetter();
// } else {
// return const SignInOrRegister();
// }
// }),
),
);
}
}

View File

@@ -1,299 +0,0 @@
import 'package:mzansi_innovation_hub/main.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_layout/mih_action.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_layout/mih_body.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_layout/mih_header.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_layout/mih_layout_builder.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_package_components/mih_button.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_package_components/mih_package_alert.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_package_components/mih_icons.dart';
import 'package:mzansi_innovation_hub/mih_config/mih_colors.dart';
import 'package:mzansi_innovation_hub/mih_packages/mih_home/mih_profile_getter.dart';
import 'package:flutter/material.dart';
import 'package:local_auth/local_auth.dart';
import 'package:app_settings/app_settings.dart';
class BiometricCheck extends StatefulWidget {
final bool personalSelected;
final bool firstBoot;
const BiometricCheck({
super.key,
required this.personalSelected,
required this.firstBoot,
});
@override
State<BiometricCheck> createState() => _BiometricCheckState();
}
class _BiometricCheckState extends State<BiometricCheck> {
bool _isBioAuthenticated = false;
final LocalAuthentication _auth = LocalAuthentication();
MIHAction getActionButton() {
return MIHAction(
icon: Padding(
padding: const EdgeInsets.all(10.0),
child: SizedBox(
height: 50,
child: FittedBox(
child: Icon(
MihIcons.mihLogo,
color: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
),
),
),
),
iconSize: 35,
onTap: () async {
// await SuperTokens.signOut(completionHandler: (error) {
// print(error);
// });
// if (await SuperTokens.doesSessionExist() == false) {
// Navigator.of(context).popAndPushNamed('/');
// }
// Navigator.of(context).pushNamed(
// '/about',
// //arguments: widget.signedInUser,
// );
},
);
}
MIHHeader getHeader() {
return const MIHHeader(
headerAlignment: MainAxisAlignment.center,
headerItems: [
Text(
"",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 25,
),
),
],
);
}
void authenticateUser() async {
final bool canAuthWithBio = await _auth.canCheckBiometrics;
final bool canAuthenticate =
canAuthWithBio || await _auth.isDeviceSupported();
print("Auth Available: $canAuthenticate");
if (canAuthenticate) {
try {
final bool didBioAuth = await _auth.authenticate(
localizedReason: "Authenticate to access MIH",
options: const AuthenticationOptions(
biometricOnly: false,
),
);
if (didBioAuth) {
setState(() {
_isBioAuthenticated = true;
});
} else {
authErrorPopUp();
}
// print("Authenticated: $didBioAuth");
} catch (error) {
print("Auth Error: $error");
authErrorPopUp();
}
} else {
print("Auth Error: No Biometrics Available");
authErrorPopUp();
}
}
void authErrorPopUp() {
Widget alertpopUp = MihPackageAlert(
alertIcon: Icon(
Icons.fingerprint,
color: MihColors.getRedColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
size: 100,
),
alertTitle: "Biometric Authentication Error",
alertBody: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Hi there! To jump into the MIH Home Package, you'll need to authenticate yourself with your phones biometrics, please set up biometric authentication (like fingerprint, face ID, pattern or pin) on your device first.\n\nIf you have already set up biometric authentication, press \"Authenticate now\" to try again or press \"Set Up Authentication\" to go to your device settings.",
style: TextStyle(
fontSize: 15,
color: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
),
),
const SizedBox(height: 20),
Wrap(
runAlignment: WrapAlignment.center,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 10,
runSpacing: 10,
children: [
MihButton(
onPressed: () {
AppSettings.openAppSettings(
type: AppSettingsType.security,
);
Navigator.of(context).pop();
},
buttonColor: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
width: 300,
child: Text(
"Set Up Authentication",
style: TextStyle(
color: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
MihButton(
onPressed: () {
Navigator.of(context).pop();
authenticateUser();
},
buttonColor: MihColors.getGreenColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
width: 300,
child: Text(
"Authenticate Now",
style: TextStyle(
color: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
],
),
],
),
alertColour: MihColors.getRedColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
);
showDialog(
context: context,
builder: (context) {
return alertpopUp;
},
);
}
MIHBody getBody() {
return MIHBody(
borderOn: false,
bodyItems: [
SafeArea(
child: Center(
child: Padding(
padding: const EdgeInsets.all(25.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
//logo
Icon(
Icons.fingerprint,
size: 100,
color: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
),
//spacer
const SizedBox(height: 10),
//Heading
Text(
'Biomentric Authentication',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
color: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
),
),
//spacer
const SizedBox(height: 25),
// if (!_isBioAuthenticated)
Icon(
Icons.lock,
size: 200,
color: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
),
const SizedBox(height: 30),
MihButton(
onPressed: () {
authenticateUser();
},
buttonColor: MihColors.getGreenColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
width: 300,
child: Text(
"Authenticate Now",
style: TextStyle(
color: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
],
),
),
),
),
],
);
}
Widget getBiomentricAuthScreen() {
return MIHLayoutBuilder(
actionButton: getActionButton(),
header: getHeader(),
secondaryActionButton: null,
body: getBody(),
actionDrawer: null,
secondaryActionDrawer: null,
bottomNavBar: null,
pullDownToRefresh: false,
onPullDown: () async {},
);
}
@override
void initState() {
// TODO: implement initState
super.initState();
if (widget.firstBoot == true) authenticateUser();
}
@override
Widget build(BuildContext context) {
if (MzansiInnovationHub.of(context)!.theme.getPlatform() == "Web") {
return MIHProfileGetter(
personalSelected: widget.personalSelected,
);
} else if (!widget.firstBoot) {
return MIHProfileGetter(
personalSelected: widget.personalSelected,
);
} else {
if (_isBioAuthenticated) {
return MIHProfileGetter(
personalSelected: widget.personalSelected,
);
} else {
return getBiomentricAuthScreen();
}
}
}
}

View File

@@ -1,405 +0,0 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:go_router/go_router.dart';
import 'package:mzansi_innovation_hub/mih_config/mih_colors.dart';
import 'package:mzansi_innovation_hub/mih_services/mih_alert_services.dart';
import 'package:mzansi_innovation_hub/mih_services/mih_validation_services.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_package_components/mih_button.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_package_components/mih_form.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_package_components/mih_package_alert.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_package_components/mih_text_form_field.dart';
import '../../main.dart';
import 'package:supertokens_flutter/http.dart' as http;
import '../../mih_components/mih_layout/mih_action.dart';
import '../../mih_components/mih_layout/mih_body.dart';
import '../../mih_components/mih_layout/mih_header.dart';
import '../../mih_components/mih_layout/mih_layout_builder.dart';
import '../../mih_components/mih_pop_up_messages/mih_error_message.dart';
import '../../mih_components/mih_pop_up_messages/mih_loading_circle.dart';
import '../../mih_config/mih_env.dart';
class ForgotPassword extends StatefulWidget {
const ForgotPassword({super.key});
@override
State<ForgotPassword> createState() => _ForgotPasswordState();
}
class _ForgotPasswordState extends State<ForgotPassword> {
final emailController = TextEditingController();
final _formKey = GlobalKey<FormState>();
//bool _obscureText = true;
bool successfulForgotPassword = false;
bool acceptWarning = false;
// focus node to capture keyboard events
final FocusNode _focusNode = FocusNode();
final baseAPI = AppEnviroment.baseApiUrl;
Future<void> submitPasswodReset() async {
showDialog(
context: context,
builder: (context) {
return const Mihloadingcircle();
},
);
try {
var response = await http.post(
Uri.parse("$baseAPI/auth/user/password/reset/token"),
body:
'{"formFields": [{"id": "email","value": "${emailController.text}"}]}',
headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
//"Authorization": "leatucczyixqwkqqdrhayiwzeofkltds"
},
);
//print(response.body[])
if (response.statusCode == 200) {
//print(response.body);
var userSignedin = jsonDecode(response.body);
if (userSignedin["status"] == "OK") {
//print("here");
setState(() {
successfulForgotPassword = true;
});
Navigator.of(context).pop();
} else {
Navigator.of(context).pop();
//loginError();
}
}
} on Exception {
Navigator.of(context).pop();
//loginError();
}
}
Color getPrim() {
return MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark");
}
Color getSec() {
return MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark");
}
void prePassResteWarning() {
showDialog(
context: context,
builder: (context) {
return MihPackageAlert(
alertIcon: Icon(
Icons.warning_amber_rounded,
size: 100,
color: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
),
alertTitle: "Password Reset Confirmation",
alertBody: Column(
//mainAxisSize: MainAxisSize.max,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 25.0),
child: Text(
"Before you reset your password, please be aware that you'll receive an email with a link to confirm your identity and set a new password. Make sure to check your inbox, including spam or junk folders. If you don't receive the email within a few minutes, please try resending the reset request.",
style: TextStyle(
color: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
fontSize: 15.0,
fontWeight: FontWeight.bold,
),
),
),
const SizedBox(height: 25),
MihButton(
onPressed: () {
setState(() {
acceptWarning = true;
});
Navigator.of(context).pop();
validateInput();
},
buttonColor: MihColors.getGreenColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
width: 300,
child: Text(
"Continue",
style: TextStyle(
color: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
],
),
alertColour: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
);
},
);
}
void loginError() {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Invalid Credentials");
},
);
}
void resetLinkSentSuccessfully() {
showDialog(
context: context,
builder: (context) {
return MihPackageAlert(
alertIcon: Icon(
Icons.check_circle_outline_rounded,
size: 150,
color: MihColors.getGreenColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
),
alertTitle: "Successfully Sent Reset Link",
alertBody: Column(
children: [
Text(
"We've sent a password reset link to your email address. Please check your inbox, including spam or junk folders.\n\nOnce you find the email, click on the link to reset your password.\n\nIf you don't receive the email within a few minutes, please try resending the reset request.\n\nThe reset link will expire after 2 hours",
style: TextStyle(
color: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
fontSize: 15,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 25),
Center(
child: MihButton(
onPressed: () {
context.goNamed(
'mihHome',
extra: true,
);
},
buttonColor: MihColors.getGreenColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
elevation: 10,
width: 300,
child: Text(
"Dismiss",
style: TextStyle(
color: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
)
],
),
alertColour: MihColors.getGreenColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark"),
);
// return const MIHSuccessMessage(
// successType: "Success",
// successMessage:
// "We've sent a password reset link to your email address. Please check your inbox, including spam or junk folders.\n\nOnce you find the email, click on the link to reset your password.\n\nIf you don't receive the email within a few minutes, please try resending the reset request.\n\nThe reset link will expire after 2 hours");
},
);
}
void validateInput() async {
if (emailController.text.isEmpty) {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Input Error");
},
);
} else {
await submitPasswodReset();
if (successfulForgotPassword) {
// Navigator.of(context).pushNamedAndRemoveUntil('/', (route) => false);
resetLinkSentSuccessfully();
}
}
}
MIHAction getActionButton() {
return MIHAction(
icon: const Icon(Icons.arrow_back),
iconSize: 35,
onTap: () {
// Navigator.of(context).pop();
context.goNamed(
'mihHome',
extra: true,
);
},
);
}
MIHHeader getHeader() {
return const MIHHeader(
headerAlignment: MainAxisAlignment.center,
headerItems: [
Text(
"",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 25,
),
),
],
);
}
MIHBody getBody(double width) {
return MIHBody(
borderOn: false,
bodyItems: [
KeyboardListener(
focusNode: _focusNode,
autofocus: true,
onKeyEvent: (event) async {
if (event is KeyDownEvent &&
event.logicalKey == LogicalKeyboardKey.enter) {
validateInput();
}
},
child: SafeArea(
child: Center(
child: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Padding(
padding: MzansiInnovationHub.of(context)!.theme.screenType ==
"desktop"
? EdgeInsets.symmetric(
vertical: 25, horizontal: width * 0.2)
: EdgeInsets.symmetric(
vertical: 25, horizontal: width * 0.075),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
//logo
Icon(
Icons.lock,
size: 100,
color: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
),
//spacer
const SizedBox(height: 10),
//Heading
Text(
'Forgot Password',
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
color: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
),
),
const SizedBox(height: 25),
MihForm(
formKey: _formKey,
formFields: [
MihTextFormField(
fillColor: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
inputColor: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
controller: emailController,
multiLineInput: false,
requiredText: true,
hintText: "Email",
validator: (value) {
return MihValidationServices()
.validateEmail(value);
},
),
//spacer
const SizedBox(height: 20),
Align(
alignment: Alignment.center,
child: MihButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
prePassResteWarning();
} else {
MihAlertServices()
.formNotFilledCompletely(context);
}
},
buttonColor: MihColors.getGreenColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
width: 300,
child: Text(
"Reset Password",
style: TextStyle(
color: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!
.theme
.mode ==
"Dark"),
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
),
],
),
],
),
),
),
),
),
),
],
);
}
@override
void dispose() {
emailController.dispose();
_focusNode.dispose();
super.dispose();
}
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
double screenWidth = MediaQuery.of(context).size.width;
return MIHLayoutBuilder(
actionButton: getActionButton(),
header: getHeader(),
secondaryActionButton: null,
body: getBody(screenWidth),
actionDrawer: null,
secondaryActionDrawer: null,
bottomNavBar: null,
pullDownToRefresh: false,
onPullDown: () async {},
);
}
}

View File

@@ -1,358 +0,0 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mzansi_innovation_hub/mih_config/mih_colors.dart';
import 'package:mzansi_innovation_hub/mih_services/mih_alert_services.dart';
import 'package:mzansi_innovation_hub/mih_services/mih_validation_services.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_package_components/mih_button.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_package_components/mih_form.dart';
import 'package:mzansi_innovation_hub/mih_components/mih_package_components/mih_text_form_field.dart';
import '../../main.dart';
import 'package:supertokens_flutter/http.dart' as http;
import '../../mih_components/mih_layout/mih_action.dart';
import '../../mih_components/mih_layout/mih_body.dart';
import '../../mih_components/mih_layout/mih_header.dart';
import '../../mih_components/mih_layout/mih_layout_builder.dart';
import '../../mih_components/mih_pop_up_messages/mih_error_message.dart';
import '../../mih_components/mih_pop_up_messages/mih_loading_circle.dart';
import '../../mih_components/mih_pop_up_messages/mih_success_message.dart';
import '../../mih_config/mih_env.dart';
class ResetPassword extends StatefulWidget {
final String token;
const ResetPassword({
super.key,
required this.token,
});
@override
State<ResetPassword> createState() => _ResetPasswordState();
}
class _ResetPasswordState extends State<ResetPassword> {
final passwordController = TextEditingController();
final confirmPasswordController = TextEditingController();
//bool _obscureText = true;
bool successfulResetPassword = false;
bool acceptWarning = false;
// focus node to capture keyboard events
final FocusNode _focusNode = FocusNode();
final _formKey = GlobalKey<FormState>();
final baseAPI = AppEnviroment.baseApiUrl;
Future<void> submitPasswodReset() async {
showDialog(
context: context,
builder: (context) {
return const Mihloadingcircle();
},
);
try {
var callBody =
'{"method": "token","formFields": [{"id": "password","value": "${passwordController.text}"}],"token": "${widget.token}"}';
//print(callBody);
var response = await http.post(
Uri.parse("$baseAPI/auth/user/password/reset"),
body: callBody,
headers: {
'Content-type': 'application/json; charset=utf-8',
// 'Accept': 'application/json',
//"Authorization": "leatucczyixqwkqqdrhayiwzeofkltds"
},
);
//print(response.body[])
if (response.statusCode == 200) {
//print(response.body);
var userPassReset = jsonDecode(response.body);
if (userPassReset["status"] == "OK") {
//print("here");
setState(() {
successfulResetPassword = true;
});
Navigator.of(context).pop();
Navigator.of(context).pushNamed('/');
} else if (userPassReset["status"] == "FIELD_ERROR") {
Navigator.of(context).pop();
passwordReqError();
} else {
Navigator.of(context).pop();
loginError();
}
}
} on Exception {
Navigator.of(context).pop();
//loginError();
}
}
void passwordReqError() {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Password Requirements");
},
);
}
Color getPrim() {
return MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark");
}
Color getSec() {
return MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode == "Dark");
}
void loginError() {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Invalid Credentials");
},
);
}
void resetSuccessfully() {
showDialog(
context: context,
builder: (context) {
return const MIHSuccessMessage(
successType: "Success",
successMessage:
"Great news! Your password reset is complete. You can now log in to Mzansi Innovation Hub using your new password.");
},
);
}
void passwordError() {
showDialog(
context: context,
builder: (context) {
return const MIHErrorMessage(errorType: "Password Match");
},
);
}
void submitFormInput() async {
if (passwordController.text != confirmPasswordController.text) {
passwordError();
} else {
await submitPasswodReset();
if (successfulResetPassword) {
resetSuccessfully();
}
}
}
MIHAction getActionButton() {
return MIHAction(
icon: Padding(
padding: const EdgeInsets.all(10.0),
child: SizedBox(
height: 50,
child: Image.asset(
'lib/mih_components/mih_package_components/assets/images/logo_light.png'),
),
),
iconSize: 35,
onTap: () {},
);
}
MIHHeader getHeader() {
return const MIHHeader(
headerAlignment: MainAxisAlignment.center,
headerItems: [
Text(
"",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 25,
),
),
],
);
}
MIHBody getBody(double width) {
return MIHBody(
borderOn: false,
bodyItems: [
KeyboardListener(
focusNode: _focusNode,
autofocus: true,
onKeyEvent: (event) async {
if (event is KeyDownEvent &&
event.logicalKey == LogicalKeyboardKey.enter) {
if (_formKey.currentState!.validate()) {
submitFormInput();
} else {
MihAlertServices().formNotFilledCompletely(context);
}
}
},
child: SafeArea(
child: Center(
child: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Padding(
padding: MzansiInnovationHub.of(context)!.theme.screenType ==
"desktop"
? EdgeInsets.symmetric(horizontal: width * 0.2)
: EdgeInsets.symmetric(horizontal: width * 0.075),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
widget.token,
style: TextStyle(
fontSize: 20,
color: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
),
),
const SizedBox(height: 25),
//logo
Icon(
Icons.lock,
size: 100,
color: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
),
//spacer
const SizedBox(height: 10),
//Heading
Text(
'Reset Password',
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
color: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
),
),
//spacer
const SizedBox(height: 25),
MihForm(
formKey: _formKey,
formFields: [
MihTextFormField(
fillColor: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
inputColor: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
controller: passwordController,
multiLineInput: false,
requiredText: true,
hintText: "Password",
passwordMode: true,
autofillHints: const [AutofillHints.password],
validator: (value) {
return MihValidationServices()
.validatePassword(value);
},
),
//spacer
const SizedBox(height: 10),
MihTextFormField(
fillColor: MihColors.getSecondaryColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
inputColor: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
controller: confirmPasswordController,
multiLineInput: false,
requiredText: true,
hintText: "Confirm Password",
passwordMode: true,
autofillHints: const [AutofillHints.password],
validator: (value) {
return MihValidationServices()
.validatePassword(value);
},
),
//spacer
const SizedBox(height: 25),
// sign in button
Center(
child: MihButton(
onPressed: () {
if (_formKey.currentState!.validate()) {
submitFormInput();
} else {
MihAlertServices()
.formNotFilledCompletely(context);
}
},
buttonColor: MihColors.getGreenColor(
MzansiInnovationHub.of(context)!.theme.mode ==
"Dark"),
width: 300,
child: Text(
"Reset Password",
style: TextStyle(
color: MihColors.getPrimaryColor(
MzansiInnovationHub.of(context)!
.theme
.mode ==
"Dark"),
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
),
],
),
],
),
),
),
),
),
),
],
);
}
@override
void dispose() {
passwordController.dispose();
confirmPasswordController.dispose();
_focusNode.dispose();
super.dispose();
}
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
double screenWidth = MediaQuery.of(context).size.width;
return MIHLayoutBuilder(
actionButton: getActionButton(),
header: getHeader(),
secondaryActionButton: null,
body: getBody(screenWidth),
actionDrawer: null,
secondaryActionDrawer: null,
bottomNavBar: null,
pullDownToRefresh: false,
onPullDown: () async {},
);
}
}