add user deletion, email change

This commit is contained in:
2026-01-08 17:50:51 -06:00
parent ebce85068e
commit 75c81e3127
10 changed files with 895 additions and 82 deletions

View File

@@ -0,0 +1,431 @@
import 'dart:convert';
import 'package:blind_master/BlindMasterResources/error_snackbar.dart';
import 'package:blind_master/BlindMasterResources/secure_transmissions.dart';
import 'package:blind_master/BlindMasterScreens/accountManagement/change_password_screen.dart';
import 'package:blind_master/BlindMasterScreens/accountManagement/verify_email_change_screen.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class AccountScreen extends StatefulWidget {
const AccountScreen({super.key});
@override
State<AccountScreen> createState() => _AccountScreenState();
}
class _AccountScreenState extends State<AccountScreen> {
String? name;
String? email;
String? createdAt;
bool isLoading = true;
@override
void initState() {
super.initState();
fetchAccountInfo();
}
Future<void> fetchAccountInfo() async {
try {
final response = await secureGet('account_info');
if (response == null) {
throw Exception('No response from server');
}
if (response.statusCode == 200) {
final body = json.decode(response.body);
setState(() {
name = body['name'] ?? 'N/A';
email = body['email'] ?? 'N/A';
// Parse and format the created_at timestamp
if (body['created_at'] != null) {
try {
final DateTime dateTime = DateTime.parse(body['created_at']);
final months = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'];
createdAt = '${months[dateTime.month - 1]} ${dateTime.day}, ${dateTime.year}';
} catch (e) {
createdAt = 'N/A';
}
} else {
createdAt = 'N/A';
}
isLoading = false;
});
} else {
throw Exception('Failed to load account info');
}
} catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(errorSnackbar(e));
setState(() {
isLoading = false;
});
}
}
Future<void> _handleDeleteAccount() async {
final primaryColor = Theme.of(context).primaryColorLight;
final confirmed = await showDialog<bool>(
context: context,
builder: (BuildContext dialogContext) {
return AlertDialog(
title: Row(
children: [
Icon(Icons.warning, color: Colors.red),
SizedBox(width: 10),
Text('Delete Account'),
],
),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Are you sure you want to delete your account?',
style: TextStyle(fontWeight: FontWeight.bold),
),
SizedBox(height: 10),
Text('This action cannot be undone. All your data will be permanently deleted.'),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: Text('Cancel'),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
foregroundColor: Colors.white,
),
onPressed: () => Navigator.of(dialogContext).pop(true),
child: Text('Delete Account'),
),
],
);
},
);
if (confirmed == true && mounted) {
try {
// Show loading indicator
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext loadingContext) {
return Center(
child: CircularProgressIndicator(
color: primaryColor,
),
);
},
);
final response = await secureDelete('delete_account');
// Remove loading indicator
if (mounted) Navigator.of(context).pop();
if (response == null) {
throw Exception('No response from server');
}
if (response.statusCode == 200) {
if (!mounted) return;
// Navigate to splash screen (remove all routes)
Navigator.of(context).pushNamedAndRemoveUntil('/', (route) => false);
} else {
final body = json.decode(response.body);
throw Exception(body['error'] ?? 'Failed to delete account');
}
} catch (e) {
// Remove loading indicator if still showing
if (mounted && Navigator.of(context).canPop()) {
Navigator.of(context).pop();
}
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(errorSnackbar(e));
}
}
}
Future<void> _handleChangeEmail() async {
final TextEditingController emailController = TextEditingController();
final formKey = GlobalKey<FormState>();
final primaryColor = Theme.of(context).primaryColorLight;
final result = await showDialog<bool>(
context: context,
builder: (BuildContext dialogContext) {
return AlertDialog(
title: Text('Change Email'),
content: Form(
key: formKey,
child: TextFormField(
controller: emailController,
decoration: InputDecoration(
labelText: 'New Email Address',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.email),
),
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter an email address';
}
final emailRegex = RegExp(r'^[^\s@]+@[^\s@]+\.[^\s@]+$');
if (!emailRegex.hasMatch(value)) {
return 'Please enter a valid email';
}
if (value == email) {
return 'This is your current email';
}
return null;
},
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: Text('Cancel'),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: primaryColor,
foregroundColor: Colors.white,
),
onPressed: () async {
if (formKey.currentState!.validate()) {
Navigator.of(dialogContext).pop(true);
}
},
child: Text('Send Verification'),
),
],
);
},
);
// Allow dialog to fully close before disposing controller
await Future.delayed(Duration(milliseconds: 100));
if (result == true && mounted) {
final newEmail = emailController.text.trim();
try {
// Show loading indicator
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext loadingContext) {
return Center(
child: CircularProgressIndicator(
color: primaryColor,
),
);
},
);
final localHour = DateTime.now().hour;
final response = await securePost(
{
'newEmail': newEmail,
'localHour': localHour,
},
'request-email-change',
);
// Remove loading indicator
if (mounted) Navigator.of(context).pop();
if (response == null) {
throw Exception('No response from server');
}
if (response.statusCode == 200) {
if (!mounted) return;
// Navigate to waiting screen
final success = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EmailChangeWaitingScreen(newEmail: newEmail),
),
);
// If email was changed successfully, refresh account info
if (success == true && mounted) {
await fetchAccountInfo();
}
} else {
final body = json.decode(response.body);
throw Exception(body['error'] ?? 'Failed to send verification email');
}
} catch (e) {
// Remove loading indicator if still showing
if (mounted && Navigator.of(context).canPop()) {
Navigator.of(context).pop();
}
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(errorSnackbar(e));
} finally {
emailController.dispose();
}
} else {
emailController.dispose();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).primaryColorLight,
foregroundColor: Colors.white,
title: Text(
'Account',
style: GoogleFonts.aBeeZee(),
),
),
body: isLoading
? Center(
child: CircularProgressIndicator(
color: Theme.of(context).primaryColorLight,
),
)
: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Account Info Section
Card(
elevation: 2,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Center(
child: CircleAvatar(
radius: 50,
backgroundColor: Theme.of(context).primaryColorLight,
child: Icon(
Icons.person,
size: 60,
color: Colors.white,
),
),
),
SizedBox(height: 20),
_buildInfoRow('Name', name ?? 'N/A'),
Divider(height: 30),
_buildInfoRow('Email', email ?? 'N/A'),
Divider(height: 30),
_buildInfoRow('Member Since', createdAt ?? 'N/A'),
],
),
),
),
SizedBox(height: 30),
// Account Options Section
Text(
'Account Options',
style: GoogleFonts.aBeeZee(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 15),
Card(
elevation: 2,
child: Column(
children: [
ListTile(
leading: Icon(Icons.email_outlined),
title: Text('Change Email'),
trailing: Icon(Icons.arrow_forward_ios, size: 16),
onTap: _handleChangeEmail,
),
Divider(height: 1),
ListTile(
leading: Icon(Icons.lock_outline),
title: Text('Change Password'),
trailing: Icon(Icons.arrow_forward_ios, size: 16),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChangePasswordScreen(),
),
);
},
),
],
),
),
SizedBox(height: 30),
// Danger Zone Section
Text(
'Danger Zone',
style: GoogleFonts.aBeeZee(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.red,
),
),
SizedBox(height: 15),
Card(
elevation: 2,
child: ListTile(
leading: Icon(Icons.delete_forever, color: Colors.red),
title: Text(
'Delete Account',
style: TextStyle(color: Colors.red),
),
trailing: Icon(Icons.arrow_forward_ios, size: 16, color: Colors.red),
onTap: _handleDeleteAccount,
),
),
],
),
),
),
);
}
Widget _buildInfoRow(String label, String value) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: TextStyle(
fontSize: 14,
color: Colors.grey[600],
fontWeight: FontWeight.w500,
),
),
SizedBox(height: 5),
Text(
value,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
),
),
],
);
}
}

View File

@@ -0,0 +1,195 @@
import 'dart:convert';
import 'package:blind_master/BlindMasterResources/error_snackbar.dart';
import 'package:blind_master/BlindMasterResources/secure_transmissions.dart';
import 'package:blind_master/BlindMasterResources/text_inputs.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class ChangePasswordScreen extends StatefulWidget {
const ChangePasswordScreen({super.key});
@override
State<ChangePasswordScreen> createState() => _ChangePasswordScreenState();
}
class _ChangePasswordScreenState extends State<ChangePasswordScreen> {
final oldPasswordController = TextEditingController();
final newPasswordController = TextEditingController();
final confirmPasswordController = TextEditingController();
final _formKey = GlobalKey<FormState>();
@override
void dispose() {
oldPasswordController.dispose();
newPasswordController.dispose();
confirmPasswordController.dispose();
super.dispose();
}
String? newPasswordValidator(String? input) {
if (input == null || input.isEmpty) {
return 'New password is required';
}
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 != newPasswordController.text) {
return 'Passwords do not match';
}
return null;
}
String? oldPasswordValidator(String? input) {
if (input == null || input.isEmpty) {
return 'Current password is required';
}
return null;
}
Future<void> handleChangePassword() async {
if (!_formKey.currentState!.validate()) {
return;
}
try {
// Show loading indicator
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return Center(
child: CircularProgressIndicator(
color: Theme.of(context).primaryColorLight,
),
);
},
);
final payload = {
'oldPassword': oldPasswordController.text,
'newPassword': newPasswordController.text,
};
final response = await securePost(payload, 'change_password');
// Remove loading indicator
if (mounted) Navigator.of(context).pop();
if (response == null) {
throw Exception('No response from server');
}
if (response.statusCode == 200) {
if (!mounted) return;
// Show success message
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
backgroundColor: Colors.green[700],
content: Text('Password changed successfully'),
duration: Duration(seconds: 2),
),
);
// Navigate back to account screen
Navigator.pop(context);
} else if (response.statusCode == 401) {
throw Exception('Current password is incorrect');
} else if (response.statusCode == 400) {
final body = json.decode(response.body);
throw Exception(body['error'] ?? 'Invalid request');
} else {
throw Exception('Failed to change password');
}
} catch (e) {
// Remove loading indicator if still showing
if (mounted && Navigator.of(context).canPop()) {
Navigator.of(context).pop();
}
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(errorSnackbar(e));
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).primaryColorLight,
foregroundColor: Colors.white,
title: Text(
'Change Password',
style: GoogleFonts.aBeeZee(),
),
),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Form(
key: _formKey,
autovalidateMode: AutovalidateMode.onUnfocus,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SizedBox(height: 20),
Text(
'Enter your current password and choose a new password',
style: TextStyle(
fontSize: 16,
color: Colors.grey[700],
),
textAlign: TextAlign.center,
),
SizedBox(height: 30),
BlindMasterMainInput(
'Current Password',
controller: oldPasswordController,
password: true,
validator: oldPasswordValidator,
),
SizedBox(height: 20),
Divider(),
SizedBox(height: 20),
BlindMasterMainInput(
'New Password',
controller: newPasswordController,
password: true,
validator: newPasswordValidator,
),
SizedBox(height: 20),
BlindMasterMainInput(
'Confirm New Password',
controller: confirmPasswordController,
password: true,
validator: confirmPasswordValidator,
),
SizedBox(height: 30),
ElevatedButton(
onPressed: handleChangePassword,
style: ElevatedButton.styleFrom(
backgroundColor: Theme.of(context).primaryColorLight,
foregroundColor: Colors.white,
padding: EdgeInsets.symmetric(vertical: 15),
),
child: Text(
'Change Password',
style: TextStyle(fontSize: 16),
),
),
],
),
),
),
),
);
}
}

View File

@@ -0,0 +1,73 @@
import 'dart:async';
import 'dart:convert';
import 'package:blind_master/BlindMasterResources/secure_transmissions.dart';
import 'package:flutter/material.dart';
import '../email_verification_waiting_screen.dart';
class EmailChangeWaitingScreen extends BaseVerificationWaitingScreen {
final String newEmail;
const EmailChangeWaitingScreen({super.key, required this.newEmail});
@override
State<EmailChangeWaitingScreen> createState() => _EmailChangeWaitingScreenState();
}
class _EmailChangeWaitingScreenState extends BaseVerificationWaitingScreenState<EmailChangeWaitingScreen> {
@override
String get title => "Verify New Email";
@override
String get mainMessage => "We've sent a verification link to:";
@override
String? get highlightedInfo => widget.newEmail;
@override
String get instructionMessage => "Click the link in the email to verify your new email address. This page will automatically update once verified.";
@override
String get successMessage => "Email changed successfully!";
@override
Future<bool> checkStatus() async {
final response = await secureGet('pending-email-status');
if (response == null) {
throw Exception('No response from server');
}
if (response.statusCode == 200) {
final body = json.decode(response.body);
return body['hasPending'] == false;
}
return false;
}
@override
Future<void> resendVerification() async {
final localHour = DateTime.now().hour;
final response = await securePost(
{
'newEmail': widget.newEmail,
'localHour': localHour,
},
'request-email-change',
);
if (response == null) {
throw Exception('No response from server');
}
if (response.statusCode != 200) {
final body = json.decode(response.body);
throw Exception(body['error'] ?? 'Failed to resend verification email');
}
}
@override
void onSuccess() {
Navigator.of(context).pop(true); // Return true to indicate success
}
}