password reset flow works

This commit is contained in:
2026-01-08 13:44:39 -06:00
parent 0ffffdeee5
commit 08f1c05ac2
9 changed files with 1050 additions and 87 deletions

View File

@@ -21,6 +21,7 @@ class _CreateUserScreenState extends State<CreateUserScreen> {
final emailController = TextEditingController();
final nameController = TextEditingController();
final passwordController = TextEditingController();
final confirmPasswordController = TextEditingController();
final _passFormKey = GlobalKey<FormState>();
final _emailFormKey = GlobalKey<FormState>();
@@ -87,13 +88,24 @@ class _CreateUserScreenState extends State<CreateUserScreen> {
}
String? confirmPasswordValidator(String? input) {
if (input == passwordController.text) {
return null;
String? passwordValidator(String? input) {
if (input == null || input.isEmpty) {
return 'Password is required';
}
else {
if (input.length < 8) {
return 'Password must be at least 8 characters';
}
return null;
}
String? confirmPasswordValidator(String? input) {
if (input == null || input.isEmpty) {
return 'Please confirm your password';
}
if (input != passwordController.text) {
return "Passwords do not match!";
}
return null;
}
String? emailValidator(String? input) {
@@ -135,18 +147,20 @@ class _CreateUserScreenState extends State<CreateUserScreen> {
),
Form(
key: _passFormKey,
autovalidateMode: AutovalidateMode.onUserInteraction,
autovalidateMode: AutovalidateMode.onUnfocus,
child: Column(
children: [
BlindMasterMainInput(
"Password",
password: true,
controller: passwordController
controller: passwordController,
validator: passwordValidator,
),
BlindMasterMainInput(
"Confirm Password",
validator: confirmPasswordValidator,
password: true,
controller: confirmPasswordController,
)
],
)

View File

@@ -0,0 +1,186 @@
import 'package:flutter/material.dart';
import 'dart:convert';
import '../../BlindMasterResources/secure_transmissions.dart';
import 'verify_reset_code_screen.dart';
class ForgotPasswordScreen extends StatefulWidget {
const ForgotPasswordScreen({super.key});
@override
State<ForgotPasswordScreen> createState() => _ForgotPasswordScreenState();
}
class _ForgotPasswordScreenState extends State<ForgotPasswordScreen> {
final _formKey = GlobalKey<FormState>();
final _emailController = TextEditingController();
bool _isLoading = false;
@override
void dispose() {
_emailController.dispose();
super.dispose();
}
String? _emailValidator(String? value) {
if (value == null || value.isEmpty) {
return 'Please enter your email';
}
final emailRegex = RegExp(r'^[^@]+@[^@]+\.[^@]+');
if (!emailRegex.hasMatch(value)) {
return 'Please enter a valid email';
}
return null;
}
Future<void> _handleSendCode() async {
if (!_formKey.currentState!.validate()) {
return;
}
setState(() {
_isLoading = true;
});
try {
final response = await regularPost(
{
'email': _emailController.text.trim(),
},
'/forgot-password',
);
if (!mounted) return;
if (response.statusCode == 200) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => VerifyResetCodeScreen(
email: _emailController.text.trim(),
),
),
);
} else if (response.statusCode == 429) {
final body = json.decode(response.body) as Map<String, dynamic>;
final retryAfter = body['retryAfter'] ?? 'some time';
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Please wait $retryAfter seconds before requesting another code.'),
backgroundColor: Colors.red,
duration: const Duration(seconds: 5),
),
);
} else {
final body = json.decode(response.body) as Map<String, dynamic>;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(body['error'] ?? 'Failed to send reset code'),
backgroundColor: Colors.red,
),
);
}
} catch (error) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Error: $error'),
backgroundColor: Colors.red,
),
);
} finally {
if (mounted) {
setState(() {
_isLoading = false;
});
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Forgot Password'),
backgroundColor: Theme.of(context).primaryColorLight,
),
body: SafeArea(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24.0),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Icon(
Icons.lock_reset,
size: 80,
color: Theme.of(context).primaryColorLight,
),
const SizedBox(height: 32),
const Text(
'Reset Your Password',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 16),
const Text(
'Enter your email address and we\'ll send you a 6-character code to reset your password.',
style: TextStyle(
fontSize: 16,
color: Colors.grey,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 32),
TextFormField(
controller: _emailController,
decoration: const InputDecoration(
labelText: 'Email',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.email),
),
keyboardType: TextInputType.emailAddress,
validator: _emailValidator,
enabled: !_isLoading,
),
const SizedBox(height: 24),
ElevatedButton(
onPressed: _isLoading ? null : _handleSendCode,
style: ElevatedButton.styleFrom(
backgroundColor: Theme.of(context).primaryColorLight,
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
child: _isLoading
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
),
)
: const Text(
'Send Reset Code',
style: TextStyle(
fontSize: 16,
color: Colors.white,
),
),
),
],
),
),
),
),
),
);
}
}

View File

@@ -1,5 +1,6 @@
import 'package:blind_master/BlindMasterResources/secure_transmissions.dart';
import 'package:blind_master/BlindMasterScreens/Startup/create_user_screen.dart';
import 'package:blind_master/BlindMasterScreens/Startup/forgot_password_screen.dart';
import 'package:blind_master/BlindMasterScreens/home_screen.dart';
import 'package:blind_master/BlindMasterResources/error_snackbar.dart';
import 'package:blind_master/BlindMasterResources/fade_transition.dart';
@@ -107,6 +108,13 @@ class _LoginScreenState extends State<LoginScreen> {
);
}
void switchToForgotPassword() {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const ForgotPasswordScreen()),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
@@ -121,7 +129,7 @@ class _LoginScreenState extends State<LoginScreen> {
child: Column(
children: [
BlindMasterMainInput("Email", controller: emailController),
BlindMasterMainInput("Password", controller: passwordController, password: true,),
BlindMasterMainInput("Password", controller: passwordController, password: true),
],
),
),
@@ -140,6 +148,13 @@ class _LoginScreenState extends State<LoginScreen> {
"Create Account"
),
),
const SizedBox(height: 8),
TextButton(
onPressed: switchToForgotPassword,
child: Text(
"Forgot Password?"
),
),
],
),
),

View File

@@ -0,0 +1,214 @@
import 'package:flutter/material.dart';
import 'dart:convert';
import '../../BlindMasterResources/secure_transmissions.dart';
import '../../BlindMasterResources/text_inputs.dart';
import 'login_screen.dart';
class ResetPasswordFormScreen extends StatefulWidget {
final String email;
final String code;
const ResetPasswordFormScreen({
super.key,
required this.email,
required this.code,
});
@override
State<ResetPasswordFormScreen> createState() => _ResetPasswordFormScreenState();
}
class _ResetPasswordFormScreenState extends State<ResetPasswordFormScreen> {
final _formKey = GlobalKey<FormState>();
final _passwordController = TextEditingController();
final _confirmPasswordController = TextEditingController();
bool _isLoading = false;
@override
void dispose() {
_passwordController.dispose();
_confirmPasswordController.dispose();
super.dispose();
}
String? _passwordValidator(String? value) {
if (value == null || value.isEmpty) {
return 'Please enter a password';
}
if (value.length < 8) {
return 'Password must be at least 8 characters';
}
return null;
}
String? _confirmPasswordValidator(String? value) {
if (value == null || value.isEmpty) {
return 'Please confirm your password';
}
if (value != _passwordController.text) {
return 'Passwords do not match';
}
return null;
}
Future<void> _handleResetPassword() async {
if (!_formKey.currentState!.validate()) {
return;
}
setState(() {
_isLoading = true;
});
try {
final response = await regularPost(
{
'email': widget.email,
'code': widget.code,
'newPassword': _passwordController.text,
},
'/reset-password',
);
if (!mounted) return;
if (response.statusCode == 200) {
// Navigate back to login screen and remove all previous routes
Navigator.of(context).pushAndRemoveUntil(
MaterialPageRoute(builder: (context) => const LoginScreen()),
(route) => false,
);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Password reset successfully! Please log in with your new password.'),
backgroundColor: Colors.green,
duration: Duration(seconds: 4),
),
);
} else if (response.statusCode == 429) {
final body = json.decode(response.body) as Map<String, dynamic>;
final retryAfter = body['retryAfter'] ?? 'some time';
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Too many attempts. Please try again in $retryAfter minutes.'),
backgroundColor: Colors.red,
duration: const Duration(seconds: 5),
),
);
} else {
final body = json.decode(response.body) as Map<String, dynamic>;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(body['error'] ?? 'Failed to reset password'),
backgroundColor: Colors.red,
),
);
}
} catch (error) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Error: $error'),
backgroundColor: Colors.red,
),
);
} finally {
if (mounted) {
setState(() {
_isLoading = false;
});
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Reset Password'),
backgroundColor: Theme.of(context).primaryColorLight,
),
body: SafeArea(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24.0),
child: Form(
key: _formKey,
autovalidateMode: AutovalidateMode.onUnfocus,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Icon(
Icons.lock_open,
size: 80,
color: Theme.of(context).primaryColorLight,
),
const SizedBox(height: 32),
const Text(
'Create New Password',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 16),
const Text(
'Enter your new password below.',
style: TextStyle(
fontSize: 16,
color: Colors.grey,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 32),
BlindMasterMainInput(
'New Password',
controller: _passwordController,
password: true,
validator: _passwordValidator,
),
BlindMasterMainInput(
'Confirm New Password',
controller: _confirmPasswordController,
password: true,
validator: _confirmPasswordValidator,
),
const SizedBox(height: 24),
ElevatedButton(
onPressed: _isLoading ? null : _handleResetPassword,
style: ElevatedButton.styleFrom(
backgroundColor: Theme.of(context).primaryColorLight,
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
child: _isLoading
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
),
)
: const Text(
'Reset Password',
style: TextStyle(
fontSize: 16,
color: Colors.white,
),
),
),
],
),
),
),
),
),
);
}
}

View File

@@ -0,0 +1,298 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:convert';
import '../../BlindMasterResources/secure_transmissions.dart';
import 'reset_password_form_screen.dart';
class VerifyResetCodeScreen extends StatefulWidget {
final String email;
const VerifyResetCodeScreen({
super.key,
required this.email,
});
@override
State<VerifyResetCodeScreen> createState() => _VerifyResetCodeScreenState();
}
class _VerifyResetCodeScreenState extends State<VerifyResetCodeScreen> {
final _formKey = GlobalKey<FormState>();
final _codeController = TextEditingController();
bool _isLoading = false;
bool _isResending = false;
@override
void dispose() {
_codeController.dispose();
super.dispose();
}
String? _codeValidator(String? value) {
if (value == null || value.isEmpty) {
return 'Please enter the reset code';
}
if (value.length != 6) {
return 'Code must be 6 characters';
}
return null;
}
Future<void> _handleVerifyCode() async {
if (!_formKey.currentState!.validate()) {
return;
}
setState(() {
_isLoading = true;
});
try {
final response = await regularPost(
{
'email': widget.email,
'code': _codeController.text.trim().toUpperCase(),
},
'/verify-reset-code',
);
if (!mounted) return;
if (response.statusCode == 200) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ResetPasswordFormScreen(
email: widget.email,
code: _codeController.text.trim().toUpperCase(),
),
),
);
} else if (response.statusCode == 429) {
final body = json.decode(response.body) as Map<String, dynamic>;
final retryAfter = body['retryAfter'] ?? 'some time';
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Too many attempts. Please try again in $retryAfter minutes.'),
backgroundColor: Colors.red,
duration: const Duration(seconds: 5),
),
);
} else if (response.statusCode == 401) {
final body = json.decode(response.body) as Map<String, dynamic>;
final remainingAttempts = body['remainingAttempts'] ?? 0;
String message = body['error'] ?? 'Invalid or expired code';
if (remainingAttempts > 0) {
message += '\n$remainingAttempts attempts remaining before timeout.';
}
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(message),
backgroundColor: Colors.orange[700],
duration: const Duration(seconds: 4),
),
);
} else {
final body = json.decode(response.body) as Map<String, dynamic>;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(body['error'] ?? 'Invalid or expired code'),
backgroundColor: Colors.red,
),
);
}
} catch (error) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Error: $error'),
backgroundColor: Colors.red,
),
);
} finally {
if (mounted) {
setState(() {
_isLoading = false;
});
}
}
}
Future<void> _handleResendCode() async {
setState(() {
_isResending = true;
});
try {
final response = await regularPost(
{
'email': widget.email,
},
'/forgot-password',
);
if (!mounted) return;
if (response.statusCode == 200) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: const Text('A new code has been sent to your email'),
backgroundColor: Theme.of(context).primaryColorLight,
),
);
_codeController.clear();
} else if (response.statusCode == 429) {
final body = json.decode(response.body) as Map<String, dynamic>;
final retryAfter = body['retryAfter'] ?? 'some time';
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Please wait $retryAfter seconds before requesting another code.'),
backgroundColor: Colors.red,
duration: const Duration(seconds: 5),
),
);
} else {
final body = json.decode(response.body) as Map<String, dynamic>;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(body['error'] ?? 'Failed to resend code'),
backgroundColor: Colors.red,
),
);
}
} catch (error) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Error: $error'),
backgroundColor: Colors.red,
),
);
} finally {
if (mounted) {
setState(() {
_isResending = false;
});
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Verify Code'),
backgroundColor: Theme.of(context).primaryColorLight,
),
body: SafeArea(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24.0),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Icon(
Icons.mark_email_read,
size: 80,
color: Theme.of(context).primaryColorLight,
),
const SizedBox(height: 32),
const Text(
'Check Your Email',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 16),
Text(
'We\'ve sent a 6-character code to ${widget.email}. Enter it below to continue.',
style: const TextStyle(
fontSize: 16,
color: Colors.grey,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 32),
TextFormField(
controller: _codeController,
decoration: const InputDecoration(
labelText: 'Reset Code',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.security),
hintText: 'ABC123',
),
keyboardType: TextInputType.text,
textCapitalization: TextCapitalization.characters,
inputFormatters: [
LengthLimitingTextInputFormatter(6),
FilteringTextInputFormatter.allow(RegExp(r'[A-Za-z0-9]')),
],
validator: _codeValidator,
enabled: !_isLoading && !_isResending,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 24,
letterSpacing: 8,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 24),
ElevatedButton(
onPressed: _isLoading || _isResending ? null : _handleVerifyCode,
style: ElevatedButton.styleFrom(
backgroundColor: Theme.of(context).primaryColorLight,
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
child: _isLoading
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
),
)
: const Text(
'Verify Code',
style: TextStyle(
fontSize: 16,
color: Colors.white,
),
),
),
const SizedBox(height: 16),
TextButton(
onPressed: _isLoading || _isResending ? null : _handleResendCode,
child: _isResending
? SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(Theme.of(context).primaryColorLight),
),
)
: Text(
'Didn\'t receive the code? Resend',
style: TextStyle(
color: Theme.of(context).primaryColorLight,
),
),
),
],
),
),
),
),
),
);
}
}