feat(auth & contact): separate Vorname/Nachname in registration, pre-fill read-only profile in contact, and restrict contact messages to registered users
Build Android APK / Build Release APKs (push) Successful in 14m55s

This commit is contained in:
2026-09-14 11:29:12 +02:00
parent 33f7d1d36c
commit 23d10ae953
5 changed files with 310 additions and 84 deletions
+2 -2
View File
@@ -26,9 +26,9 @@ service cloud.firestore {
(resource.data.author_uid == request.auth.uid); (resource.data.author_uid == request.auth.uid);
} }
// Kontakt-Nachrichten: Jeder kann einsenden, Lesen nur berechtigte Nutzer // Kontakt-Nachrichten: Nur registrierte Nutzer können einsenden, Lesen für berechtigte Nutzer
match /ContactMessages/{document} { match /ContactMessages/{document} {
allow create: if true; allow create: if request.auth != null && request.auth.token.firebase.sign_in_provider != 'anonymous';
allow read, update, delete: if request.auth != null; allow read, update, delete: if request.auth != null;
} }
} }
+31 -9
View File
@@ -25,7 +25,8 @@ class _AuthDialogState extends State<AuthDialog>
final _loginPasswordController = TextEditingController(); final _loginPasswordController = TextEditingController();
// Register Controllers // Register Controllers
final _regNameController = TextEditingController(); final _regFirstNameController = TextEditingController();
final _regLastNameController = TextEditingController();
final _regEmailController = TextEditingController(); final _regEmailController = TextEditingController();
final _regPasswordController = TextEditingController(); final _regPasswordController = TextEditingController();
final _regConfirmPasswordController = TextEditingController(); final _regConfirmPasswordController = TextEditingController();
@@ -51,7 +52,8 @@ class _AuthDialogState extends State<AuthDialog>
_tabController.dispose(); _tabController.dispose();
_loginEmailController.dispose(); _loginEmailController.dispose();
_loginPasswordController.dispose(); _loginPasswordController.dispose();
_regNameController.dispose(); _regFirstNameController.dispose();
_regLastNameController.dispose();
_regEmailController.dispose(); _regEmailController.dispose();
_regPasswordController.dispose(); _regPasswordController.dispose();
_regConfirmPasswordController.dispose(); _regConfirmPasswordController.dispose();
@@ -93,13 +95,14 @@ class _AuthDialogState extends State<AuthDialog>
} }
Future<void> _handleRegister() async { Future<void> _handleRegister() async {
final name = _regNameController.text.trim(); final firstName = _regFirstNameController.text.trim();
final lastName = _regLastNameController.text.trim();
final email = _regEmailController.text.trim(); final email = _regEmailController.text.trim();
final password = _regPasswordController.text; final password = _regPasswordController.text;
final confirm = _regConfirmPasswordController.text; final confirm = _regConfirmPasswordController.text;
if (name.isEmpty || email.isEmpty || password.isEmpty) { if (firstName.isEmpty || lastName.isEmpty || email.isEmpty || password.isEmpty) {
setState(() => _errorMessage = 'Bitte alle Pflichtfelder ausfüllen.'); setState(() => _errorMessage = 'Bitte alle Pflichtfelder ausfüllen (Vorname, Nachname, E-Mail, Passwort).');
return; return;
} }
@@ -123,7 +126,8 @@ class _AuthDialogState extends State<AuthDialog>
final error = await auth.signUpWithEmail( final error = await auth.signUpWithEmail(
email: email, email: email,
password: password, password: password,
name: name, firstName: firstName,
lastName: lastName,
); );
if (!mounted) return; if (!mounted) return;
@@ -453,15 +457,33 @@ class _AuthDialogState extends State<AuthDialog>
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
TextField( Row(
controller: _regNameController, children: [
Expanded(
child: TextField(
controller: _regFirstNameController,
textCapitalization: TextCapitalization.words, textCapitalization: TextCapitalization.words,
decoration: const InputDecoration( decoration: const InputDecoration(
labelText: 'Name / Vorname', labelText: 'Vorname *',
prefixIcon: Icon(Icons.person_outline), prefixIcon: Icon(Icons.person_outline),
border: OutlineInputBorder(), border: OutlineInputBorder(),
), ),
), ),
),
const SizedBox(width: 10),
Expanded(
child: TextField(
controller: _regLastNameController,
textCapitalization: TextCapitalization.words,
decoration: const InputDecoration(
labelText: 'Nachname *',
prefixIcon: Icon(Icons.person_outline),
border: OutlineInputBorder(),
),
),
),
],
),
const SizedBox(height: 10), const SizedBox(height: 10),
TextField( TextField(
controller: _regEmailController, controller: _regEmailController,
+216 -54
View File
@@ -1,5 +1,8 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../services/auth_service.dart';
import '../services/firestore_service.dart'; import '../services/firestore_service.dart';
import 'auth_dialog.dart';
class ContactScreen extends StatefulWidget { class ContactScreen extends StatefulWidget {
const ContactScreen({super.key}); const ContactScreen({super.key});
@@ -29,11 +32,12 @@ class _ContactScreenState extends State<ContactScreen> {
super.dispose(); super.dispose();
} }
bool _isValidEmail(String email) { Future<void> _submitForm(AuthService auth) async {
return RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$').hasMatch(email); if (!auth.isRegisteredUser) {
await AuthDialog.show(context);
return;
} }
Future<void> _submitForm() async {
if (!_formKey.currentState!.validate() || _isSubmitting) return; if (!_formKey.currentState!.validate() || _isSubmitting) return;
setState(() { setState(() {
@@ -41,19 +45,27 @@ class _ContactScreenState extends State<ContactScreen> {
}); });
try { try {
final firstName = auth.firstName.isNotEmpty
? auth.firstName
: _firstNameController.text.trim();
final lastName = auth.lastName.isNotEmpty
? auth.lastName
: _lastNameController.text.trim();
final email = (auth.email != null && auth.email!.isNotEmpty)
? auth.email!
: _emailController.text.trim();
await _firestoreService.submitContactMessage( await _firestoreService.submitContactMessage(
firstName: _firstNameController.text.trim(), firstName: firstName,
lastName: _lastNameController.text.trim(), lastName: lastName,
email: _emailController.text.trim(), email: email,
phone: _phoneController.text.trim(), phone: _phoneController.text.trim(),
message: _messageController.text.trim(), message: _messageController.text.trim(),
authorUid: auth.user?.uid,
); );
if (!mounted) return; if (!mounted) return;
_firstNameController.clear();
_lastNameController.clear();
_emailController.clear();
_phoneController.clear(); _phoneController.clear();
_messageController.clear(); _messageController.clear();
@@ -82,6 +94,26 @@ class _ContactScreenState extends State<ContactScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final auth = Provider.of<AuthService>(context);
final isRegistered = auth.isRegisteredUser;
// Sync controllers with authenticated user details
if (isRegistered) {
if (_firstNameController.text != auth.firstName) {
_firstNameController.text = auth.firstName;
}
if (_lastNameController.text != auth.lastName) {
_lastNameController.text = auth.lastName;
}
if (_emailController.text != (auth.email ?? '')) {
_emailController.text = auth.email ?? '';
}
} else {
if (_firstNameController.text.isNotEmpty) _firstNameController.clear();
if (_lastNameController.text.isNotEmpty) _lastNameController.clear();
if (_emailController.text.isNotEmpty) _emailController.clear();
}
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('Kontakt Bürgerforum'), title: const Text('Kontakt Bürgerforum'),
@@ -94,20 +126,51 @@ class _ContactScreenState extends State<ContactScreen> {
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
if (!isRegistered) ...[
Card( Card(
color: Colors.blue.shade50, color: Colors.amber.shade50,
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)), borderRadius: BorderRadius.circular(12),
child: const Padding( side: BorderSide(color: Colors.amber.shade300),
padding: EdgeInsets.all(14.0), ),
child: Row( child: Padding(
padding: const EdgeInsets.all(14.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Icon(Icons.mail_outline, color: Colors.blue, size: 28), Row(
SizedBox(width: 12), children: [
Expanded( Icon(Icons.lock_outline,
child: Text( color: Colors.amber.shade900, size: 22),
'Hier kannst du direkt mit dem Bürgerforum Oggau in Kontakt treten. Wir freuen uns über deine Anregungen und Fragen!', const SizedBox(width: 8),
style: TextStyle(fontSize: 13), Text(
'Anmeldung erforderlich',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: Colors.amber.shade900,
),
),
],
),
const SizedBox(height: 6),
Text(
'Um eine Nachricht an das Bürgerforum zu senden, ist ein registriertes Benutzerkonto erforderlich. Deine Kontaktdaten werden dann automatisch hinterlegt.',
style: TextStyle(
fontSize: 13, color: Colors.grey.shade800),
),
const SizedBox(height: 12),
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: () => AuthDialog.show(context),
icon: const Icon(Icons.login),
label: const Text('Jetzt anmelden oder registrieren'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue.shade700,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 11),
),
), ),
), ),
], ],
@@ -115,33 +178,102 @@ class _ContactScreenState extends State<ContactScreen> {
), ),
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
] else ...[
Card(
color: Colors.blue.shade50,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: BorderSide(color: Colors.blue.shade100),
),
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Row(
children: [
Icon(Icons.verified_user_outlined,
color: Colors.blue.shade700, size: 24),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Angemeldet als ${auth.displayName ?? auth.email}',
style: const TextStyle(
fontSize: 13,
fontWeight: FontWeight.bold,
color: Colors.black87,
),
),
const SizedBox(height: 2),
Text(
'Deine Kontaktdaten sind automatisch hinterlegt.',
style: TextStyle(
fontSize: 12, color: Colors.grey.shade700),
),
],
),
),
],
),
),
),
const SizedBox(height: 16),
],
Row( Row(
children: [ children: [
Expanded( Expanded(
child: TextFormField( child: TextFormField(
controller: _firstNameController, controller: _firstNameController,
decoration: const InputDecoration( readOnly: true,
labelText: 'Vorname *', style: TextStyle(
border: OutlineInputBorder(), color: isRegistered
? Colors.black87
: Colors.grey.shade600,
fontWeight: isRegistered
? FontWeight.w500
: FontWeight.normal,
), ),
validator: (value) => decoration: InputDecoration(
(value == null || value.trim().isEmpty) labelText: 'Vorname *',
? 'Bitte Vorname eingeben' hintText:
isRegistered ? null : 'Wird automatisch ausgefüllt',
filled: true,
fillColor: Colors.grey.shade100,
prefixIcon: const Icon(Icons.person_outline),
suffixIcon: isRegistered
? const Icon(Icons.lock_outline,
size: 18, color: Colors.grey)
: null, : null,
border: const OutlineInputBorder(),
),
), ),
), ),
const SizedBox(width: 12), const SizedBox(width: 12),
Expanded( Expanded(
child: TextFormField( child: TextFormField(
controller: _lastNameController, controller: _lastNameController,
decoration: const InputDecoration( readOnly: true,
labelText: 'Nachname *', style: TextStyle(
border: OutlineInputBorder(), color: isRegistered
? Colors.black87
: Colors.grey.shade600,
fontWeight: isRegistered
? FontWeight.w500
: FontWeight.normal,
), ),
validator: (value) => decoration: InputDecoration(
(value == null || value.trim().isEmpty) labelText: 'Nachname *',
? 'Bitte Nachname eingeben' hintText:
isRegistered ? null : 'Wird automatisch ausgefüllt',
filled: true,
fillColor: Colors.grey.shade100,
prefixIcon: const Icon(Icons.person_outline),
suffixIcon: isRegistered
? const Icon(Icons.lock_outline,
size: 18, color: Colors.grey)
: null, : null,
border: const OutlineInputBorder(),
),
), ),
), ),
], ],
@@ -149,41 +281,58 @@ class _ContactScreenState extends State<ContactScreen> {
const SizedBox(height: 12), const SizedBox(height: 12),
TextFormField( TextFormField(
controller: _emailController, controller: _emailController,
keyboardType: TextInputType.emailAddress, readOnly: true,
decoration: const InputDecoration( style: TextStyle(
color: isRegistered ? Colors.black87 : Colors.grey.shade600,
fontWeight:
isRegistered ? FontWeight.w500 : FontWeight.normal,
),
decoration: InputDecoration(
labelText: 'E-Mail-Adresse *', labelText: 'E-Mail-Adresse *',
border: OutlineInputBorder(), hintText:
isRegistered ? null : 'Wird durch Anmeldung ausgefüllt',
filled: true,
fillColor: Colors.grey.shade100,
prefixIcon: const Icon(Icons.email_outlined),
suffixIcon: isRegistered
? const Icon(Icons.lock_outline,
size: 18, color: Colors.grey)
: null,
helperText: isRegistered
? 'Antworten des Bürgerforums gehen an diese E-Mail'
: null,
border: const OutlineInputBorder(),
), ),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Bitte E-Mail-Adresse eingeben';
}
if (!_isValidEmail(value.trim())) {
return 'Bitte eine gültige E-Mail eingeben';
}
return null;
},
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
TextFormField( TextFormField(
controller: _phoneController, controller: _phoneController,
keyboardType: TextInputType.phone, keyboardType: TextInputType.phone,
decoration: const InputDecoration( enabled: isRegistered,
decoration: InputDecoration(
labelText: 'Rückrufnummer (optional)', labelText: 'Rückrufnummer (optional)',
border: OutlineInputBorder(), prefixIcon: const Icon(Icons.phone_outlined),
border: const OutlineInputBorder(),
helperText: isRegistered
? 'Optional für eventuelle telefonische Rückfragen'
: null,
filled: !isRegistered,
fillColor: !isRegistered ? Colors.grey.shade100 : null,
), ),
), ),
const SizedBox(height: 12), const SizedBox(height: 12),
TextFormField( TextFormField(
controller: _messageController, controller: _messageController,
maxLines: 5, maxLines: 5,
decoration: const InputDecoration( enabled: isRegistered,
decoration: InputDecoration(
labelText: 'Ihr Anliegen / Ihre Nachricht *', labelText: 'Ihr Anliegen / Ihre Nachricht *',
alignLabelWithHint: true, alignLabelWithHint: true,
border: OutlineInputBorder(), border: const OutlineInputBorder(),
filled: !isRegistered,
fillColor: !isRegistered ? Colors.grey.shade100 : null,
), ),
validator: (value) => validator: (value) => (value == null || value.trim().isEmpty)
(value == null || value.trim().isEmpty)
? 'Bitte Ihre Nachricht eingeben' ? 'Bitte Ihre Nachricht eingeben'
: null, : null,
), ),
@@ -201,16 +350,29 @@ class _ContactScreenState extends State<ContactScreen> {
width: double.infinity, width: double.infinity,
height: 48, height: 48,
child: ElevatedButton.icon( child: ElevatedButton.icon(
onPressed: _isSubmitting ? null : _submitForm, onPressed: !isRegistered
? () => AuthDialog.show(context)
: (_isSubmitting ? null : () => _submitForm(auth)),
style: ElevatedButton.styleFrom(
backgroundColor: isRegistered
? Colors.blue.shade800
: Colors.grey.shade700,
foregroundColor: Colors.white,
),
icon: _isSubmitting icon: _isSubmitting
? const SizedBox( ? const SizedBox(
width: 20, width: 20,
height: 20, height: 20,
child: CircularProgressIndicator(strokeWidth: 2), child: CircularProgressIndicator(
strokeWidth: 2, color: Colors.white),
) )
: const Icon(Icons.send), : Icon(!isRegistered ? Icons.login : Icons.send),
label: Text( label: Text(
_isSubmitting ? 'Wird gesendet...' : 'Nachricht absenden', !isRegistered
? 'Anmelden zum Absenden'
: (_isSubmitting
? 'Wird gesendet...'
: 'Nachricht absenden'),
style: const TextStyle(fontSize: 16), style: const TextStyle(fontSize: 16),
), ),
), ),
+44 -4
View File
@@ -18,6 +18,29 @@ class AuthService extends ChangeNotifier {
String? get email => _user?.email; String? get email => _user?.email;
String? get displayName => _user?.displayName; String? get displayName => _user?.displayName;
String? _cachedFirstName;
String? _cachedLastName;
String get firstName {
if (_cachedFirstName != null && _cachedFirstName!.isNotEmpty) {
return _cachedFirstName!;
}
final name = _user?.displayName ?? '';
if (name.isEmpty) return '';
final parts = name.trim().split(RegExp(r'\s+'));
return parts.isNotEmpty ? parts.first : '';
}
String get lastName {
if (_cachedLastName != null && _cachedLastName!.isNotEmpty) {
return _cachedLastName!;
}
final name = _user?.displayName ?? '';
if (name.isEmpty) return '';
final parts = name.trim().split(RegExp(r'\s+'));
return parts.length > 1 ? parts.sublist(1).join(' ') : '';
}
AuthService() { AuthService() {
_initAuth(); _initAuth();
} }
@@ -25,6 +48,8 @@ class AuthService extends ChangeNotifier {
Future<void> _initAuth() async { Future<void> _initAuth() async {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
_isCommunityUnlocked = prefs.getBool(_prefKeyUnlocked) ?? false; _isCommunityUnlocked = prefs.getBool(_prefKeyUnlocked) ?? false;
_cachedFirstName = prefs.getString('user_first_name');
_cachedLastName = prefs.getString('user_last_name');
_auth.authStateChanges().listen((User? user) { _auth.authStateChanges().listen((User? user) {
_user = user; _user = user;
@@ -80,11 +105,12 @@ class AuthService extends ChangeNotifier {
} }
} }
/// Sign up with Email, Password, and Full Name /// Sign up with Email, Password, First Name, and Last Name
Future<String?> signUpWithEmail({ Future<String?> signUpWithEmail({
required String email, required String email,
required String password, required String password,
required String name, required String firstName,
required String lastName,
}) async { }) async {
try { try {
final credential = await _auth.createUserWithEmailAndPassword( final credential = await _auth.createUserWithEmailAndPassword(
@@ -93,9 +119,18 @@ class AuthService extends ChangeNotifier {
); );
_user = credential.user; _user = credential.user;
if (_user != null) { if (_user != null) {
if (name.isNotEmpty) { final cleanFirst = firstName.trim();
await _user!.updateDisplayName(name.trim()); final cleanLast = lastName.trim();
final fullName = '$cleanFirst $cleanLast'.trim();
if (fullName.isNotEmpty) {
await _user!.updateDisplayName(fullName);
} }
_cachedFirstName = cleanFirst;
_cachedLastName = cleanLast;
final prefs = await SharedPreferences.getInstance();
await prefs.setString('user_first_name', cleanFirst);
await prefs.setString('user_last_name', cleanLast);
// Send email verification so user verifies they own the email address // Send email verification so user verifies they own the email address
try { try {
await _user!.sendEmailVerification(); await _user!.sendEmailVerification();
@@ -169,6 +204,11 @@ class AuthService extends ChangeNotifier {
/// Sign out /// Sign out
Future<void> signOut() async { Future<void> signOut() async {
try { try {
final prefs = await SharedPreferences.getInstance();
await prefs.remove('user_first_name');
await prefs.remove('user_last_name');
_cachedFirstName = null;
_cachedLastName = null;
await _auth.signOut(); await _auth.signOut();
} catch (e) { } catch (e) {
if (kDebugMode) { if (kDebugMode) {
+2
View File
@@ -50,6 +50,7 @@ class FirestoreService {
required String email, required String email,
String? phone, String? phone,
required String message, required String message,
String? authorUid,
}) async { }) async {
await _firestore.collection('ContactMessages').add({ await _firestore.collection('ContactMessages').add({
'firstName': firstName, 'firstName': firstName,
@@ -57,6 +58,7 @@ class FirestoreService {
'email': email, 'email': email,
'phone': phone ?? '', 'phone': phone ?? '',
'message': message, 'message': message,
'author_uid': authorUid ?? '',
'createdDate': Timestamp.now(), 'createdDate': Timestamp.now(),
'status': 'Neu', 'status': 'Neu',
}); });