This commit is contained in:
Venba 2024-07-11 17:31:14 +05:30
parent 44e94898b7
commit 5a9dec473c
17 changed files with 1538 additions and 39 deletions

2
.env
View File

@ -1,4 +1,4 @@
API_URL=https://venbait.in/nhance/dev/employeeRest/
TICKET_API_URL=https://venbait.in/nhance/helpdesk/dev/api
BASE_HREF=/nhance/employee/dev/
ENV=development
ENV=production

View File

@ -1,4 +1,4 @@
API_URL=https://venbait.in/nhance/uat/employeeRest/
TICKET_API_URL=https://venbait.in/nhance/helpdesk/uat/api
BASE_HREF=/nhance/employee/uat/
API_URL=https://venbait.in/nhance/dev/employeeRest/
TICKET_API_URL=https://venbait.in/nhance/helpdesk/dev/api
BASE_HREF=/nhance/employee/dev/
ENV=production

View File

@ -4,6 +4,8 @@
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.USE_BIOMETRIC"/>
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
<application
android:usesCleartextTraffic="true"
android:label="nhance_app_pwa"
@ -35,6 +37,7 @@
<meta-data
android:name="flutterEmbedding"
android:value="2" />
<meta-data android:name="io.flutter.embedding.android.FlutterFragmentActivity" android:value="true"/>
</application>
<!-- Required to query activities that can process text, see:
https://developer.android.com/training/package-visibility?hl=en and

View File

@ -1,5 +1,5 @@
package com.example.nhance_app_pwa
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.android.FlutterFragmentActivity
class MainActivity: FlutterActivity()
class MainActivity: FlutterFragmentActivity()

BIN
assets/mpin.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

View File

@ -2,6 +2,8 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSFaceIDUsageDescription</key>
<string>We use Face ID to protect your data in the app.</string>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>

View File

@ -25,7 +25,7 @@ class _CustomAppBarState extends State<CustomAppBar> {
final String? token = prefs.getString('token');
if (token != null && token.isNotEmpty) {
await prefs.clear();
// await prefs.clear();
Navigator.pushNamed(context, 'login');
}
}

View File

@ -17,6 +17,9 @@ import 'package:nhance_app_pwa/pages/postEnrollment/policies.dart';
import 'package:nhance_app_pwa/pages/postEnrollment/privacypolicy.dart';
import 'package:nhance_app_pwa/pages/postEnrollment/profile.dart';
import 'package:nhance_app_pwa/pages/postEnrollment/termsofuse.dart';
import 'package:nhance_app_pwa/pages/session/SetPinBiometric.dart';
import 'package:nhance_app_pwa/pages/session/authenticationService.dart';
import 'package:nhance_app_pwa/pages/session/settingUpPinAndBiometric.dart';
import 'package:nhance_app_pwa/pages/verify.dart';
import 'models/environment.dart';
@ -24,13 +27,30 @@ import 'models/environment.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await dotenv.load(fileName: Environment.fileName);
final AuthService _authService = AuthService();
runApp(MaterialApp(
initialRoute: 'login',
debugShowCheckedModeBanner: false,
// home: FutureBuilder<String?>(
// future: _authService.getPin(),
// builder: (context, snapshot) {
// if (snapshot.connectionState == ConnectionState.waiting) {
// return CircularProgressIndicator();
// }
// if (snapshot.hasData && snapshot.data != null) {
// // If PIN is saved, authenticate with PIN or biometric
// return PinOrBiometricPage();
// }
// // Otherwise, show login page
// return login();
// },
// ),
routes: {
'login': (context) => login(),
'verify': (context) => MyVerify(),
'pinSettingPage': (context) => pinSettingPage(),
'pinPage': (context) => pinPage(),
'home': (context) => MyApp(),
'policies': (context) => policies(),
'claims': (context) => claims(),

View File

@ -2,6 +2,7 @@ import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:nhance_app_pwa/pages/session/SetPinBiometric.dart';
import 'dart:convert';
import 'dart:io';
import 'package:shared_preferences/shared_preferences.dart';
@ -23,21 +24,65 @@ class _loginState extends State<login> {
TextEditingController countryController = TextEditingController();
TextEditingController mobileController = TextEditingController();
final _formKey = GlobalKey<FormState>();
bool _isCheckingToken = false;
dynamic empMobileNo;
@override
void initState() {
countryController.text = "+91";
super.initState();
checkTokenAvailability();
checkLoginPin();
WidgetsBinding.instance
.addPostFrameCallback((_) => checkTokenAvailability());
}
Future<void> checkTokenAvailability() async {
if (_isCheckingToken) return;
_isCheckingToken = true;
print('checkTokenAvailability');
final SharedPreferences prefs = await SharedPreferences.getInstance();
final String? token = prefs.getString('token');
final mpin = prefs.getString('user_pin');
int skipStatus = prefs.getInt('skipStatus') ?? 1;
final emp_status = prefs.getString('emp_status');
if (token != null && token.isNotEmpty) {
// Token available, navigate to home page
Navigator.pushReplacementNamed(context, 'home');
// if (prefs.containsKey('skipStatus') && skipStatus == 1) {
// if (prefs.containsKey('user_pin') && mpin != null && mpin.isNotEmpty) {
// Navigator.pushReplacementNamed(context, 'pinPage');
// }
// }
// checkLoginPin();
}
Future<void> checkLoginPin() async {
print('checkLoginPin');
try {
final SharedPreferences prefs = await SharedPreferences.getInstance();
empMobileNo = prefs.getString('empMobileNo');
// _token = prefs.getString('token');
final response = await http.post(
Uri.parse(Environment.apiUrl + 'checkMpin'),
body: json.encode({'mobile_number': empMobileNo}),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
},
);
if (response.statusCode == 200) {
Map<String, dynamic> data = json.decode(response.body);
if (data['status'] == 'success') {
print('data');
prefs.setString('mpin', data['data']);
Navigator.pushReplacementNamed(context, 'pinPage');
}
} else {
ToastHelper.showErrorToast(context, 'Something went wrong');
throw Exception('Failed to verify pin number');
}
} catch (e) {
ToastHelper.showErrorToast(context, 'Something went wrong');
print('Error: $e');
}
}
@ -59,6 +104,11 @@ class _loginState extends State<login> {
bool userVerification = data['data']['user_verification'];
String message = data['data']['message'];
if (userVerification) {
final SharedPreferences prefs =
await SharedPreferences.getInstance();
var enteredMobileNumber = mobileController.text;
prefs.setString('empMobileNo', enteredMobileNumber);
ToastHelper.showSuccessToast(context, message);
Navigator.pushNamed(context, 'verify',
arguments: enteredMobileNumber);

View File

@ -141,9 +141,13 @@ class _profileState extends State<profile> {
Future<void> logout(BuildContext context) async {
final prefs = await SharedPreferences.getInstance();
await prefs.clear();
Navigator.pushNamed(context, 'login');
// Navigator.pushNamed(context, "phone");
if (Responsive.isDesktop(context)) {
await prefs.clear();
Navigator.pushNamed(context, 'login');
} else {
// await prefs.clear();
Navigator.pushNamed(context, 'login');
}
}
@override
@ -537,6 +541,43 @@ class _profileState extends State<profile> {
)
])),
SizedBox(height: 12),
Container(
child: Row(
children: [
Expanded(
flex: 12,
child: Container(
width: 150,
height: Responsive.isDesktop(context) ? 150 : 100,
alignment: Alignment.center,
child: ElevatedButton(
onPressed: () {
logout(context);
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Adjust space between icon and text
Text(
'Change Pin',
style: GoogleFonts.poppins(
color: Color(0xFFE26728)),
),
],
),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5),
side: BorderSide(color: Color(0xFFE26728)),
),
),
),
)),
],
),
),
// SizedBox(height: 1),
Container(
child: Row(
children: [

View File

@ -0,0 +1,623 @@
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:jwt_decode/jwt_decode.dart';
import 'package:nhance_app_pwa/customAppBar/toastHelper.dart';
import 'package:pinput/pinput.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../customAppBar/customFooter.dart';
import '../../customAppBar/responsive.dart';
import '../../models/environment.dart';
import 'authenticationService.dart';
class pinPage extends StatefulWidget {
const pinPage({Key? key}) : super(key: key);
@override
State<pinPage> createState() => _pinPageState();
}
class _pinPageState extends State<pinPage> {
final AuthService _authService = AuthService();
final TextEditingController _pinController = TextEditingController();
final _formKey = GlobalKey<FormState>();
late final FocusNode focusNode;
String? savedPin;
dynamic empMobileNo;
dynamic _token;
dynamic empCodeString;
dynamic empClientBranchId;
dynamic empPrimaryId;
dynamic gpaEmpName;
dynamic client_id;
dynamic clientName;
dynamic clientLogo;
dynamic emp_status;
@override
void initState() {
super.initState();
_checkBiometricAuthentication();
_loadSavedPin();
focusNode = FocusNode();
}
@override
void dispose() {
focusNode.dispose();
super.dispose();
}
Future<void> _checkBiometricAuthentication() async {
bool authenticated = await _authService.authenticateWithBiometrics();
if (authenticated) {
enterPinApi();
} else {
ToastHelper.showErrorToast(context, 'Biometric authentication failed');
}
}
Future<void> enterPinApi() async {
try {
final SharedPreferences prefs = await SharedPreferences.getInstance();
empMobileNo = prefs.getString('empMobileNo');
// _token = prefs.getString('token');
final response = await http.post(
Uri.parse(Environment.apiUrl + 'verifyMpin'),
body: json.encode(
{'mobile_number': empMobileNo, 'mpin': _pinController.text}),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
},
);
if (response.statusCode == 200) {
Map<String, dynamic> data = json.decode(response.body);
if (data['status'] == 'success') {
final SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('token', data['data']);
// Decode the JWT token received from the API response
Map<String, dynamic>? decodedToken = Jwt.parseJwt(data['data']);
print('decodedToken : $decodedToken');
empClientBranchId = decodedToken['client_branch_id'];
prefs.setString('empClientBranchId', empClientBranchId);
empCodeString = decodedToken['emp_code'].toString();
prefs.setString('empCode', empCodeString);
empPrimaryId = decodedToken['id'];
prefs.setString('empPrimaryId', empPrimaryId);
gpaEmpName = decodedToken['name'].toString();
prefs.setString('gpaEmpName', gpaEmpName);
client_id = decodedToken['client_id'];
prefs.setString('client_id', client_id);
emp_status = decodedToken['emp_status'];
prefs.setString('emp_status', emp_status);
getClientLogoAndDetails();
print('Successfully Login');
final token = prefs.getString('token');
if (token != null && token.isNotEmpty) {
ToastHelper.showSuccessToast(context, 'Successfully Login');
if (emp_status == 'enrolled') {
Navigator.pushReplacementNamed(context, 'home');
} else {
Navigator.pushReplacementNamed(context, 'empDetails');
}
}
} else {
ToastHelper.showErrorToast(context, 'Invalid Pin Number');
print('Invalid Pin Number');
}
} else {
ToastHelper.showErrorToast(context, 'Something went wrong');
throw Exception('Failed to verify pin number');
}
} catch (e) {
ToastHelper.showErrorToast(context, 'Something went wrong');
print('Error: $e');
}
}
Future<void> enterLoginPin() async {
try {
if (_formKey.currentState!.validate()) {
enterPinApi();
}
} catch (e) {
ToastHelper.showErrorToast(context, 'Something went wrong');
print('Error: $e');
}
}
Future<void> _loadSavedPin() async {
savedPin = await _authService.getPin();
}
String? _validatePin(String? value) {
if (value == null || value.isEmpty) {
return 'Please enter a pin';
}
if (value.length != 4) {
return 'Pin must be 4 digits';
}
if (value != savedPin) {
return 'Incorrect pin';
}
return null;
}
Future<void> forgotPin() async {
final prefs = await SharedPreferences.getInstance();
await prefs.clear();
Navigator.pushNamed(context, 'login');
}
Future<void> getClientLogoAndDetails() async {
var url = Uri.parse(Environment.apiUrl +
'getClientDetails?client_id=$client_id&emp_code=$empCodeString');
try {
var response = await http.get(
url,
headers: {
'Authorization':
'Bearer $_token', // Add token to the Authorization header
},
);
if (response.statusCode == 200) {
// print('response.statusCode == 200');
Map<String, dynamic> data = json.decode(response.body);
// print(data);
if (data.containsKey('data')) {
dynamic clientDetails = data['data'];
final SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('clientLogo', clientDetails['client']['client_logo']);
prefs.setString('clientName', clientDetails['client']['client_name']);
setState(() {
// dynamic clientDetails = data['data'];
// print(clientDetails);
clientName = clientDetails['client']['client_name'];
print(clientName);
clientLogo = clientDetails['client']['client_logo'];
print(clientLogo);
});
} else {
// Handle other status messages if needed
// ToastHelper.showErrorToast(
// context, 'API request failed with status: ${data['status']}');
print('API request failed with status: ${data['status']}');
}
} else {
// Handle other status codes
// ToastHelper.showErrorToast(
// context, 'Request failed with status: ${response.statusCode}');
print('Request failed with status: ${response.statusCode}');
}
} catch (e) {
// Handle exceptions
print('Exception occurred: $e');
}
}
@override
Widget build(BuildContext context) {
const focusedBorderColor = Color.fromRGBO(23, 171, 144, 1);
const fillColor = Color.fromRGBO(243, 246, 249, 0);
const borderColor = Color.fromRGBO(23, 171, 144, 0.4);
Size _size = MediaQuery.of(context).size;
EdgeInsets marginInsets = EdgeInsets.zero;
if (Responsive.isDesktop(context)) {
marginInsets = const EdgeInsets.only(
left: 0,
right: 0,
bottom: 0,
top: 0,
);
} else if (Responsive.isMobile(context)) {
marginInsets = const EdgeInsets.only(
left: 25, // Example value for mobile
right: 25, // Example value for mobile
bottom: 0, // Example value for mobile
top: 0, // Example value for mobile
);
} else if (Responsive.isTablet(context)) {
marginInsets = const EdgeInsets.only(
left: 25, // Example value for mobile
right: 25, // Example value for mobile
bottom: 0, // Example value for mobile
top: 0, // Example value for mobile
);
}
final defaultPinTheme = PinTheme(
width: 56,
height: 56,
textStyle: const TextStyle(
fontSize: 20,
color: Color.fromRGBO(30, 60, 87, 1),
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(19),
border: Border.all(color: borderColor),
),
);
return Scaffold(
body: Container(
color: Colors.white, // Set the color for the body
child: SizedBox.expand(
child: Stack(children: [
SingleChildScrollView(
child: Container(
padding: EdgeInsets.all(0),
color: Color(0xFFFFFCE5),
child: Column(children: [
Container(
decoration: BoxDecoration(
color: Color(
0xFFFFFCE5), // Set background color for the container
borderRadius: BorderRadius.circular(
10), // Set border radius for the container
),
// padding: EdgeInsets.only(top: 0, bottom: 0, left: 10, right: 10),
child: Column(
// crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Expanded(
flex: 12,
child: Align(
alignment: Alignment.topLeft,
child: Padding(
padding: const EdgeInsets.only(
left: 16.0), // Add left margin
child: Image.asset(
'assets/nhance_app_logo.png',
width: 150,
height: 100,
),
),
),
),
],
),
SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
flex: 12,
child: Align(
alignment: Alignment.center,
child: Padding(
padding: const EdgeInsets.only(
left: 16.0), // Add left margin
child: Image.asset(
'assets/mpin.png',
width: 150,
height: 150,
),
),
),
),
],
),
SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
flex: 12,
child: Text(
'Enter PIN to login',
textAlign: TextAlign.center,
style: GoogleFonts.poppins(
fontSize: 16,
color: Color(0xFF404040),
fontWeight: FontWeight.w500,
),
),
),
],
),
SizedBox(height: 10),
],
),
),
Container(
decoration: BoxDecoration(
color: Colors
.white, // Set background color for the container
borderRadius: BorderRadius.only(
topLeft: Radius.circular(150.0),
topRight: Radius.circular(0),
), // Set border radius for the container
),
padding: EdgeInsets.only(
top: 20, bottom: 10, left: 10, right: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
margin: marginInsets,
alignment: Alignment.bottomCenter,
child: SingleChildScrollView(
child: Form(
key: _formKey,
child: Column(
children: [
Row(
children: [
Expanded(
flex: 12,
child: Column(
children: [
SizedBox(height: 40),
Container(
margin: EdgeInsets.symmetric(
horizontal: 30),
child: Row(
mainAxisAlignment:
MainAxisAlignment
.start, // Align text to the right
children: [
Align(
// alignment: Alignment.centerLeft,
child: Text(
'Enter the 4 Digit pin',
style: GoogleFonts
.poppins(
fontSize: 16,
color: Color(
0xFF909090),
fontWeight:
FontWeight.w400,
),
),
),
]),
),
SizedBox(height: 5),
Container(
margin: EdgeInsets.symmetric(
horizontal: 0),
child: Pinput(
length: 4,
// defaultPinTheme: defaultPinTheme,
// focusedPinTheme: focusedPinTheme,
// submittedPinTheme: submittedPinTheme,
defaultPinTheme:
defaultPinTheme,
separatorBuilder: (index) =>
const SizedBox(width: 8),
showCursor: true,
controller: _pinController,
validator: _validatePin,
errorPinTheme: defaultPinTheme
.copyBorderWith(
border: Border.all(
color:
Colors.redAccent),
),
hapticFeedbackType:
HapticFeedbackType
.lightImpact,
onCompleted: (pin) {
debugPrint(
'onCompleted: $pin');
},
onChanged: (value) {
debugPrint(
'onChanged: $value');
},
cursor: Column(
mainAxisAlignment:
MainAxisAlignment.end,
children: [
Container(
margin: const EdgeInsets
.only(bottom: 9),
width: 22,
height: 1,
color:
focusedBorderColor,
),
],
),
focusedPinTheme:
defaultPinTheme.copyWith(
decoration: defaultPinTheme
.decoration!
.copyWith(
borderRadius:
BorderRadius.circular(
8),
border: Border.all(
color:
focusedBorderColor),
),
),
submittedPinTheme:
defaultPinTheme.copyWith(
decoration: defaultPinTheme
.decoration!
.copyWith(
color: fillColor,
borderRadius:
BorderRadius.circular(
19),
border: Border.all(
color:
focusedBorderColor),
),
),
),
),
SizedBox(height: 15),
Container(
margin: EdgeInsets.symmetric(
horizontal: 30),
child: SizedBox(
width: double.infinity,
height: 45,
child: ElevatedButton(
style: ElevatedButton
.styleFrom(
backgroundColor:
Color(0xFF00989E),
shape:
RoundedRectangleBorder(
borderRadius:
BorderRadius
.circular(10),
),
),
onPressed: () async {
enterLoginPin();
},
child: Text(
"Submit",
style:
GoogleFonts.poppins(
color: Color(
0xFFFFFFFF)),
),
),
),
),
SizedBox(height: 15),
Container(
child: Row(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
GestureDetector(
onTap: () {
forgotPin();
},
child: Text(
'Forget PIN?',
style:
GoogleFonts.poppins(
fontSize: 12,
color:
Color(0xFF929292),
fontWeight:
FontWeight.w400,
),
),
),
],
),
),
],
),
),
],
),
],
),
),
),
),
],
),
),
]),
)),
Align(
alignment: Alignment.bottomCenter,
child: Container(
width: double.infinity, // Make the footer full width
child: RichText(
textAlign: TextAlign.center,
text: TextSpan(
text: 'By continuing, you agree with our ',
style: GoogleFonts.poppins(
color: Colors.black,
fontSize: 9,
),
children: <TextSpan>[
TextSpan(
text: 'privacy policy ',
style: GoogleFonts.poppins(
color: Color(0xFF00989E),
fontSize: 9,
),
),
TextSpan(
text: 'and ',
style: GoogleFonts.poppins(
color: Colors.black,
fontSize: 9,
),
),
TextSpan(
text: 'terms of use',
style: GoogleFonts.poppins(
color: Color(0xFF00989E),
fontSize: 9,
),
),
],
),
),
),
),
]),
)));
}
// Widget build(BuildContext context) {
// return Scaffold(
// appBar: AppBar(title: Text('Authenticate')),
// body: Padding(
// padding: const EdgeInsets.all(16.0),
// child: Column(
// children: [
// ElevatedButton(
// onPressed: () async {
// bool authenticated =
// await _authService.authenticateWithBiometrics();
// if (authenticated) {
// Navigator.pushReplacementNamed(context, 'home');
// } else {
// ScaffoldMessenger.of(context).showSnackBar(SnackBar(
// content: Text('Biometric authentication failed'),
// ));
// }
// },
// child: Text('Authenticate with Biometric'),
// ),
// TextField(
// controller: _pinController,
// decoration: InputDecoration(labelText: 'Enter PIN'),
// keyboardType: TextInputType.number,
// obscureText: true,
// ),
// SizedBox(height: 20),
// ElevatedButton(
// onPressed: () async {
// String pin = _pinController.text;
// String? savedPin = await _authService.getPin();
// if (pin == savedPin) {
// Navigator.pushReplacementNamed(context, 'home');
// } else {
// ScaffoldMessenger.of(context).showSnackBar(SnackBar(
// content: Text('Incorrect PIN'),
// ));
// }
// },
// child: Text('Authenticate with PIN'),
// ),
// ],
// ),
// ),
// );
// }
}

View File

@ -0,0 +1,49 @@
import 'package:local_auth/local_auth.dart';
import 'package:shared_preferences/shared_preferences.dart';
class AuthService {
final LocalAuthentication _localAuth = LocalAuthentication();
Future<bool> authenticateWithBiometrics() async {
try {
bool canCheckBiometrics = await _localAuth.canCheckBiometrics;
bool isDeviceSupported = await _localAuth.isDeviceSupported();
if (canCheckBiometrics && isDeviceSupported) {
bool authenticated = await _localAuth.authenticate(
localizedReason: 'Scan your fingerprint to authenticate',
);
return authenticated;
} else {
return false;
}
} catch (e) {
return false;
}
}
Future<void> saveBiometricEnableKey(status) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setBool('biometricStatus', status);
}
Future<void> saveSkipStatus(status) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setInt('skipStatus', status);
}
Future<void> savePin(String pin) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.setString('user_pin', pin);
}
Future<String?> getPin() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString('user_pin');
}
Future<void> clearPin() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.remove('user_pin');
}
}

View File

@ -0,0 +1,704 @@
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:pinput/pinput.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../customAppBar/customFooter.dart';
import '../../customAppBar/responsive.dart';
import '../../customAppBar/toastHelper.dart';
import '../../models/environment.dart';
import 'authenticationService.dart';
class pinSettingPage extends StatefulWidget {
const pinSettingPage({Key? key}) : super(key: key);
@override
State<pinSettingPage> createState() => _pinSettingPageState();
}
class _pinSettingPageState extends State<pinSettingPage> {
bool _enableBiometric = false;
final _pinController = TextEditingController();
final _confirmPinController = TextEditingController();
final AuthService _authService = AuthService();
late final _formKey = GlobalKey<FormState>();
late final FocusNode focusNode;
dynamic empMobileNo;
dynamic _token;
dynamic emp_status;
@override
void initState() {
super.initState();
focusNode = FocusNode();
}
@override
void dispose() {
focusNode.dispose();
super.dispose();
}
Future<void> setLoginPin() async {
try {
if (_formKey.currentState!.validate()) {
final SharedPreferences prefs = await SharedPreferences.getInstance();
empMobileNo = prefs.getString('empMobileNo');
emp_status = prefs.getString('emp_status');
_token = prefs.getString('token');
String pin = _pinController.text;
await _authService.savePin(pin);
await _authService.saveSkipStatus(1);
final response = await http.post(
Uri.parse(Environment.apiUrl + 'saveMpin'),
body: json.encode(
{'mobile_number': empMobileNo, 'mpin': _pinController.text}),
headers: {
HttpHeaders.contentTypeHeader: 'application/json',
'Authorization': 'Bearer $_token',
},
);
if (response.statusCode == 200) {
Map<String, dynamic> data = json.decode(response.body);
bool userVerification = data['data']['user_verification'];
String message = data['data']['message'];
if (userVerification) {
if (_enableBiometric == true) {
await _authService.saveBiometricEnableKey(_enableBiometric);
bool biometricEnabled =
await _authService.authenticateWithBiometrics();
if (biometricEnabled) {
if (emp_status == 'enrolled') {
Navigator.pushReplacementNamed(context, 'home');
} else {
Navigator.pushReplacementNamed(context, 'empDetails');
}
} else {
ToastHelper.showErrorToast(
context, 'Biometric authentication failed');
}
} else {
if (emp_status == 'enrolled') {
Navigator.pushReplacementNamed(context, 'home');
} else {
Navigator.pushReplacementNamed(context, 'empDetails');
}
}
} else {
ToastHelper.showErrorToast(context, message);
print('Invalid Pin Number');
}
} else {
ToastHelper.showErrorToast(context, 'Something went wrong');
throw Exception('Failed to verify mobile number');
}
}
} catch (e) {
ToastHelper.showErrorToast(context, 'Something went wrong');
print('Error: $e');
}
}
String? _validatePin(String? value) {
if (value == null || value.isEmpty) {
return 'Please enter a PIN';
}
if (value.length != 4) {
return 'PIN must be 4 digits';
}
return null;
}
String? _validateConfirmPin(String? value) {
if (value == null || value.isEmpty) {
return 'Please re-enter your PIN';
}
if (value != _pinController.text) {
return 'PINs do not match';
}
return null;
}
Future<void> setSkipStatus() async {
await _authService.saveSkipStatus(0);
Navigator.pushReplacementNamed(context, 'home');
}
@override
Widget build(BuildContext context) {
const focusedBorderColor = Color.fromRGBO(23, 171, 144, 1);
const fillColor = Color.fromRGBO(243, 246, 249, 0);
const borderColor = Color.fromRGBO(23, 171, 144, 0.4);
Size _size = MediaQuery.of(context).size;
EdgeInsets marginInsets = EdgeInsets.zero;
if (Responsive.isDesktop(context)) {
marginInsets = const EdgeInsets.only(
left: 0,
right: 0,
bottom: 0,
top: 0,
);
} else if (Responsive.isMobile(context)) {
marginInsets = const EdgeInsets.only(
left: 25, // Example value for mobile
right: 25, // Example value for mobile
bottom: 0, // Example value for mobile
top: 0, // Example value for mobile
);
} else if (Responsive.isTablet(context)) {
marginInsets = const EdgeInsets.only(
left: 25, // Example value for mobile
right: 25, // Example value for mobile
bottom: 0, // Example value for mobile
top: 0, // Example value for mobile
);
}
// final defaultPinTheme = PinTheme(
// width: 56,
// height: 56,
// textStyle: TextStyle(
// fontSize: 20,
// color: Color.fromRGBO(30, 60, 87, 1),
// fontWeight: FontWeight.w600,
// ),
// decoration: BoxDecoration(
// border: Border.all(color: Color.fromRGBO(234, 239, 243, 1)),
// borderRadius: BorderRadius.circular(20),
// ),
// );
final defaultPinTheme = PinTheme(
width: 56,
height: 56,
textStyle: const TextStyle(
fontSize: 20,
color: Color.fromRGBO(30, 60, 87, 1),
),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(19),
border: Border.all(color: borderColor),
),
);
return Scaffold(
body: Container(
color: Colors.white, // Set the color for the body
child: SizedBox.expand(
child: Stack(children: [
SingleChildScrollView(
child: Container(
padding: EdgeInsets.all(0),
color: Color(0xFFFFFCE5),
child: Column(children: [
Container(
decoration: BoxDecoration(
color: Color(
0xFFFFFCE5), // Set background color for the container
borderRadius: BorderRadius.circular(
10), // Set border radius for the container
),
// padding: EdgeInsets.only(top: 0, bottom: 0, left: 10, right: 10),
child: Column(
// crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Expanded(
flex: 12,
child: Align(
alignment: Alignment.topLeft,
child: Padding(
padding: const EdgeInsets.only(
left: 16.0), // Add left margin
child: Image.asset(
'assets/nhance_app_logo.png',
width: 150,
height: 100,
),
),
),
),
],
),
SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
flex: 12,
child: Align(
alignment: Alignment.center,
child: Padding(
padding: const EdgeInsets.only(
left: 16.0), // Add left margin
child: Image.asset(
'assets/mpin.png',
width: 150,
height: 150,
),
),
),
),
],
),
SizedBox(height: 10),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
flex: 12,
child: Text(
'Set PIN To enter',
textAlign: TextAlign.center,
style: GoogleFonts.poppins(
fontSize: 16,
color: Color(0xFF404040),
fontWeight: FontWeight.w500,
),
),
),
],
),
SizedBox(height: 10),
],
),
),
Container(
decoration: BoxDecoration(
color: Colors
.white, // Set background color for the container
borderRadius: BorderRadius.only(
topLeft: Radius.circular(150.0),
topRight: Radius.circular(0),
), // Set border radius for the container
),
padding: EdgeInsets.only(
top: 20, bottom: 10, left: 10, right: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
margin: marginInsets,
alignment: Alignment.bottomCenter,
child: SingleChildScrollView(
child: Form(
key: _formKey,
child: Column(
children: [
Row(
children: [
Expanded(
flex: 12,
child: Column(
children: [
SizedBox(height: 40),
Container(
margin: EdgeInsets.symmetric(
horizontal: 30),
child: Row(
mainAxisAlignment:
MainAxisAlignment
.start, // Align text to the right
children: [
Align(
// alignment: Alignment.centerLeft,
child: Text(
'Enter the 4 Digit pin',
style: GoogleFonts
.poppins(
fontSize: 16,
color: Color(
0xFF909090),
fontWeight:
FontWeight.w400,
),
),
),
]),
),
SizedBox(height: 5),
Container(
margin: EdgeInsets.symmetric(
horizontal: 0),
child: Pinput(
length: 4,
// defaultPinTheme: defaultPinTheme,
// focusedPinTheme: focusedPinTheme,
// submittedPinTheme: submittedPinTheme,
defaultPinTheme:
defaultPinTheme,
separatorBuilder: (index) =>
const SizedBox(width: 8),
showCursor: true,
controller: _pinController,
validator: _validatePin,
errorPinTheme: defaultPinTheme
.copyBorderWith(
border: Border.all(
color:
Colors.redAccent),
),
hapticFeedbackType:
HapticFeedbackType
.lightImpact,
onCompleted: (pin) {
debugPrint(
'onCompleted: $pin');
},
onChanged: (value) {
debugPrint(
'onChanged: $value');
},
cursor: Column(
mainAxisAlignment:
MainAxisAlignment.end,
children: [
Container(
margin: const EdgeInsets
.only(bottom: 9),
width: 22,
height: 1,
color:
focusedBorderColor,
),
],
),
focusedPinTheme:
defaultPinTheme.copyWith(
decoration: defaultPinTheme
.decoration!
.copyWith(
borderRadius:
BorderRadius.circular(
8),
border: Border.all(
color:
focusedBorderColor),
),
),
submittedPinTheme:
defaultPinTheme.copyWith(
decoration: defaultPinTheme
.decoration!
.copyWith(
color: fillColor,
borderRadius:
BorderRadius.circular(
19),
border: Border.all(
color:
focusedBorderColor),
),
),
),
),
SizedBox(height: 15),
Container(
margin: EdgeInsets.symmetric(
horizontal: 30),
child: Row(
mainAxisAlignment:
MainAxisAlignment
.start, // Align text to the right
children: [
Align(
// alignment: Alignment.centerLeft,
child: Text(
'Reenter the 4 Digit pin',
style: GoogleFonts
.poppins(
fontSize: 16,
color: Color(
0xFF909090),
fontWeight:
FontWeight.w400,
),
),
),
]),
),
SizedBox(height: 5),
Container(
margin: Responsive.isDesktop(
context)
? EdgeInsets.symmetric(
horizontal: 150)
: EdgeInsets.symmetric(
horizontal: 0),
child: Pinput(
length: 4,
// defaultPinTheme: defaultPinTheme,
// focusedPinTheme: focusedPinTheme,
// submittedPinTheme: submittedPinTheme,
defaultPinTheme:
defaultPinTheme,
separatorBuilder: (index) =>
const SizedBox(width: 8),
showCursor: true,
controller:
_confirmPinController,
validator:
_validateConfirmPin,
errorPinTheme: defaultPinTheme
.copyBorderWith(
border: Border.all(
color:
Colors.redAccent),
),
hapticFeedbackType:
HapticFeedbackType
.lightImpact,
onCompleted: (pin) {
debugPrint(
'onCompleted: $pin');
},
onChanged: (value) {
debugPrint(
'onChanged: $value');
},
cursor: Column(
mainAxisAlignment:
MainAxisAlignment.end,
children: [
Container(
margin: const EdgeInsets
.only(bottom: 9),
width: 22,
height: 1,
color:
focusedBorderColor,
),
],
),
focusedPinTheme:
defaultPinTheme.copyWith(
decoration: defaultPinTheme
.decoration!
.copyWith(
borderRadius:
BorderRadius.circular(
8),
border: Border.all(
color:
focusedBorderColor),
),
),
submittedPinTheme:
defaultPinTheme.copyWith(
decoration: defaultPinTheme
.decoration!
.copyWith(
color: fillColor,
borderRadius:
BorderRadius.circular(
19),
border: Border.all(
color:
focusedBorderColor),
),
),
),
),
SizedBox(height: 15),
Container(
margin: EdgeInsets.symmetric(
horizontal: 30),
child: Row(
mainAxisAlignment:
MainAxisAlignment
.end, // Align text to the right
children: [
Text(
'Enable Biometric',
style:
GoogleFonts.poppins(
fontSize: 12,
color:
Color(0xFF000000),
fontWeight:
FontWeight.w400,
),
),
SizedBox(
width:
10), // Optional: Add some spacing between the text and switch
Transform.scale(
scale:
0.8, // Adjust the scale factor to change the size
child: Switch(
value:
_enableBiometric,
onChanged: (value) {
setState(() {
_enableBiometric =
value;
});
},
activeColor: Color(
0xFFE26728), // Color when the switch is ON
inactiveTrackColor: Color(
0xFFD8D8D8), // Color of the switch track when OFF
),
),
]),
),
SizedBox(height: 15),
Container(
margin: EdgeInsets.symmetric(
horizontal: 30),
child: SizedBox(
width: double.infinity,
height: 45,
child: ElevatedButton(
style: ElevatedButton
.styleFrom(
backgroundColor:
Color(0xFF00989E),
shape:
RoundedRectangleBorder(
borderRadius:
BorderRadius
.circular(10),
),
),
onPressed: () async {
setLoginPin();
},
child: Text(
"Save",
style:
GoogleFonts.poppins(
color: Color(
0xFFFFFFFF)),
),
),
),
),
SizedBox(height: 15),
Container(
child: Row(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
GestureDetector(
onTap: () {
setSkipStatus();
},
child: Text(
'Skip ?',
style:
GoogleFonts.poppins(
fontSize: 12,
color:
Color(0xFF929292),
fontWeight:
FontWeight.w400,
),
),
),
],
),
),
],
),
),
],
),
],
),
),
),
),
SizedBox(height: 40),
],
),
),
]),
)),
Align(
alignment: Alignment.bottomCenter,
child: Container(
width: double.infinity, // Make the footer full width
child: RichText(
textAlign: TextAlign.center,
text: TextSpan(
text: 'By continuing, you agree with our ',
style: GoogleFonts.poppins(
color: Colors.black,
fontSize: 9,
),
children: <TextSpan>[
TextSpan(
text: 'privacy policy ',
style: GoogleFonts.poppins(
color: Color(0xFF00989E),
fontSize: 9,
),
),
TextSpan(
text: 'and ',
style: GoogleFonts.poppins(
color: Colors.black,
fontSize: 9,
),
),
TextSpan(
text: 'terms of use',
style: GoogleFonts.poppins(
color: Color(0xFF00989E),
fontSize: 9,
),
),
],
),
),
),
),
]),
)));
}
// @override
// Widget build(BuildContext context) {
// return Scaffold(
// appBar: AppBar(title: Text('Set PIN and Biometric')),
// body: Padding(
// padding: const EdgeInsets.all(16.0),
// child: Column(
// children: [
// TextField(
// controller: _pinController,
// decoration: InputDecoration(labelText: 'Enter PIN'),
// keyboardType: TextInputType.number,
// obscureText: true,
// ),
// SizedBox(height: 20),
// ElevatedButton(
// onPressed: () async {
// String pin = _pinController.text;
// await _authService.savePin(pin);
// bool biometricEnabled =
// await _authService.authenticateWithBiometrics();
// if (biometricEnabled) {
// Navigator.pushReplacementNamed(context, 'home');
// } else {
// ScaffoldMessenger.of(context).showSnackBar(SnackBar(
// content: Text('Biometric authentication failed'),
// ));
// }
// },
// child: Text('Set PIN and Enable Biometric'),
// ),
// ],
// ),
// ),
// );
// }
}

View File

@ -39,7 +39,7 @@ class _MyVerifyState extends State<MyVerify> {
@override
void initState() {
super.initState();
checkTokenAvailability();
// checkTokenAvailability();
// Start the timer when the widget is initialized
startTimer();
}
@ -64,20 +64,20 @@ class _MyVerifyState extends State<MyVerify> {
});
}
Future<void> checkTokenAvailability() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
final String? token = prefs.getString('token');
final String? emp_status = prefs.getString('emp_status');
if (token != null && token.isNotEmpty) {
// Token available, navigate to home page
if (emp_status == 'enrolled') {
Navigator.pushReplacementNamed(context, 'home');
} else {
Navigator.pushReplacementNamed(context, 'empDetails');
}
}
}
// Future<void> checkTokenAvailability() async {
// final SharedPreferences prefs = await SharedPreferences.getInstance();
// final String? token = prefs.getString('token');
// final String? emp_status = prefs.getString('emp_status');
//
// if (token != null && token.isNotEmpty) {
// // Token available, navigate to home page
// if (emp_status == 'enrolled') {
// Navigator.pushReplacementNamed(context, 'home');
// } else {
// Navigator.pushReplacementNamed(context, 'empDetails');
// }
// }
// }
Future<void> resendOTP(String mobileNumber) async {
print(mobileNumber);
@ -156,18 +156,20 @@ class _MyVerifyState extends State<MyVerify> {
// Redirect to another page
final token = prefs.getString('token');
if (token != null && token.isNotEmpty) {
ToastHelper.showSuccessToast(context, 'Successfully Login');
if (emp_status == 'enrolled') {
Navigator.pushReplacementNamed(context, 'home');
} else {
Navigator.pushReplacementNamed(context, 'empDetails');
// int skipStatus = prefs.getInt('skipStatus') ?? 1;
final mpin = prefs.getString('mpin');
if (prefs.containsKey('mpin') && mpin != 'Mpin - exist') {
if (token != null && token.isNotEmpty) {
ToastHelper.showSuccessToast(context, 'Successfully Login');
if (emp_status == 'enrolled') {
Navigator.pushReplacementNamed(context, 'home');
} else {
Navigator.pushReplacementNamed(context, 'empDetails');
}
}
} else {
// Token is empty or null, handle accordingly (e.g., navigate to login screen)
// For now, let's navigate to the login screen
ToastHelper.showErrorToast(context, 'Session Out');
Navigator.pushReplacementNamed(context, 'login');
Navigator.pushReplacementNamed(context, 'pinSettingPage');
}
} else {
ToastHelper.showErrorToast(context, 'Invalid OTP. Please try again');

View File

@ -56,6 +56,7 @@ dependencies:
webview_flutter_android: ^3.16.4
path_provider: ^2.1.3
dash_chat_2: ^0.0.21
local_auth: ^2.2.0
dev_dependencies:
flutter_test:

View File

@ -6,10 +6,13 @@
#include "generated_plugin_registrant.h"
#include <local_auth_windows/local_auth_plugin.h>
#include <smart_auth/smart_auth_plugin.h>
#include <url_launcher_windows/url_launcher_windows.h>
void RegisterPlugins(flutter::PluginRegistry* registry) {
LocalAuthPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("LocalAuthPlugin"));
SmartAuthPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("SmartAuthPlugin"));
UrlLauncherWindowsRegisterWithRegistrar(

View File

@ -3,6 +3,7 @@
#
list(APPEND FLUTTER_PLUGIN_LIST
local_auth_windows
smart_auth
url_launcher_windows
)