This commit is contained in:
Phuoc Nguyen
2025-10-10 17:36:10 +07:00
parent 04f7042b8d
commit bdaf0b96c5
82 changed files with 4753 additions and 329 deletions

View File

@@ -0,0 +1,15 @@
/// Authentication Feature
///
/// Complete authentication feature following clean architecture.
/// Includes login, registration, and user management.
///
/// Usage:
/// ```dart
/// import 'package:retail/features/auth/auth.dart';
/// ```
library;
// Export all layers
export 'data/data.dart';
export 'domain/domain.dart';
export 'presentation/presentation.dart';

View File

@@ -0,0 +1,8 @@
/// Export all auth data layer components
///
/// Contains data sources, models, and repository implementations
library;
export 'datasources/auth_remote_datasource.dart';
export 'models/models.dart';
export 'repositories/auth_repository_impl.dart';

View File

@@ -0,0 +1,9 @@
/// Export all auth data models
///
/// Contains DTOs and models for authentication data transfer
library;
export 'auth_response_model.dart';
export 'login_dto.dart';
export 'register_dto.dart';
export 'user_model.dart';

View File

@@ -0,0 +1,7 @@
/// Export all auth domain layer components
///
/// Contains entities and repository interfaces (no use cases yet)
library;
export 'entities/entities.dart';
export 'repositories/auth_repository.dart';

View File

@@ -0,0 +1,7 @@
/// Export all auth domain entities
///
/// Contains core business entities for authentication
library;
export 'auth_response.dart';
export 'user.dart';

View File

@@ -1,8 +1,11 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../providers/auth_provider.dart';
import '../widgets/widgets.dart';
import '../utils/validators.dart';
import 'register_page.dart';
/// Login page for user authentication
/// Login page with email and password authentication
class LoginPage extends ConsumerStatefulWidget {
const LoginPage({super.key});
@@ -12,9 +15,9 @@ class LoginPage extends ConsumerStatefulWidget {
class _LoginPageState extends ConsumerState<LoginPage> {
final _formKey = GlobalKey<FormState>();
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
bool _obscurePassword = true;
final _emailController = TextEditingController(text: 'admin@retailpos.com');
final _passwordController = TextEditingController(text: 'Admin123!');
bool _rememberMe = false;
@override
void dispose() {
@@ -24,8 +27,15 @@ class _LoginPageState extends ConsumerState<LoginPage> {
}
Future<void> _handleLogin() async {
if (!_formKey.currentState!.validate()) return;
// Dismiss keyboard
FocusScope.of(context).unfocus();
// Validate form
if (!_formKey.currentState!.validate()) {
return;
}
// Attempt login
final success = await ref.read(authProvider.notifier).login(
email: _emailController.text.trim(),
password: _passwordController.text,
@@ -33,135 +43,196 @@ class _LoginPageState extends ConsumerState<LoginPage> {
if (!mounted) return;
if (success) {
// Navigate to home or show success
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Login successful!')),
);
// TODO: Navigate to home page
} else {
final errorMessage = ref.read(authProvider).errorMessage;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(errorMessage ?? 'Login failed'),
backgroundColor: Colors.red,
),
);
// Show error if login failed
if (!success) {
final authState = ref.read(authProvider);
if (authState.errorMessage != null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(authState.errorMessage!),
backgroundColor: Theme.of(context).colorScheme.error,
behavior: SnackBarBehavior.floating,
action: SnackBarAction(
label: 'Dismiss',
textColor: Colors.white,
onPressed: () {},
),
),
);
}
}
// Navigation is handled by AuthWrapper
}
void _navigateToRegister() {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => const RegisterPage(),
),
);
}
void _handleForgotPassword() {
// TODO: Implement forgot password functionality
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Forgot password feature coming soon!'),
behavior: SnackBarBehavior.floating,
),
);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final authState = ref.watch(authProvider);
final isLoading = authState.isLoading;
return Scaffold(
appBar: AppBar(
title: const Text('Login'),
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Logo or app name
Icon(
Icons.shopping_cart,
size: 80,
color: Theme.of(context).primaryColor,
),
const SizedBox(height: 16),
Text(
'Retail POS',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.headlineMedium,
),
const SizedBox(height: 48),
// Email field
TextFormField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(
labelText: 'Email',
prefixIcon: Icon(Icons.email),
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your email';
}
if (!value.contains('@')) {
return 'Please enter a valid email';
}
return null;
},
),
const SizedBox(height: 16),
// Password field
TextFormField(
controller: _passwordController,
obscureText: _obscurePassword,
decoration: InputDecoration(
labelText: 'Password',
prefixIcon: const Icon(Icons.lock),
border: const OutlineInputBorder(),
suffixIcon: IconButton(
icon: Icon(
_obscurePassword
? Icons.visibility
: Icons.visibility_off,
return GestureDetector(
onTap: () => FocusScope.of(context).unfocus(),
child: Scaffold(
body: SafeArea(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24.0),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 400),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Header with logo and title
const AuthHeader(
title: 'Retail POS',
subtitle: 'Welcome back! Please login to continue.',
),
onPressed: () {
setState(() {
_obscurePassword = !_obscurePassword;
});
},
),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your password';
}
if (value.length < 8) {
return 'Password must be at least 8 characters';
}
return null;
},
),
const SizedBox(height: 24),
const SizedBox(height: 48),
// Login button
FilledButton(
onPressed: authState.isLoading ? null : _handleLogin,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: authState.isLoading
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
// Email field
AuthTextField(
controller: _emailController,
label: 'Email',
hint: 'Enter your email',
keyboardType: TextInputType.emailAddress,
textInputAction: TextInputAction.next,
prefixIcon: Icons.email_outlined,
validator: AuthValidators.validateEmail,
enabled: !isLoading,
autofocus: true,
),
const SizedBox(height: 16),
// Password field
PasswordField(
controller: _passwordController,
label: 'Password',
hint: 'Enter your password',
textInputAction: TextInputAction.done,
validator: AuthValidators.validateLoginPassword,
onFieldSubmitted: (_) => _handleLogin(),
enabled: !isLoading,
),
const SizedBox(height: 8),
// Remember me and forgot password row
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
// Remember me checkbox
Row(
children: [
Checkbox(
value: _rememberMe,
onChanged: isLoading
? null
: (value) {
setState(() {
_rememberMe = value ?? false;
});
},
),
Text(
'Remember me',
style: theme.textTheme.bodyMedium,
),
],
),
// Forgot password link
TextButton(
onPressed: isLoading ? null : _handleForgotPassword,
child: Text(
'Forgot Password?',
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.primary,
fontWeight: FontWeight.w600,
),
),
)
: const Text('Login'),
),
],
),
const SizedBox(height: 24),
// Login button
AuthButton(
onPressed: _handleLogin,
text: 'Login',
isLoading: isLoading,
),
const SizedBox(height: 24),
// Divider
Row(
children: [
Expanded(
child: Divider(
color: theme.colorScheme.onSurface.withOpacity(0.2),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Text(
'OR',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurface.withOpacity(0.5),
),
),
),
Expanded(
child: Divider(
color: theme.colorScheme.onSurface.withOpacity(0.2),
),
),
],
),
const SizedBox(height: 24),
// Register link
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"Don't have an account? ",
style: theme.textTheme.bodyMedium,
),
TextButton(
onPressed: isLoading ? null : _navigateToRegister,
child: Text(
'Register',
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.primary,
fontWeight: FontWeight.bold,
),
),
),
],
),
],
),
),
const SizedBox(height: 16),
// Register link
TextButton(
onPressed: () {
// TODO: Navigate to register page
// Navigator.push(context, MaterialPageRoute(builder: (_) => const RegisterPage()));
},
child: const Text('Don\'t have an account? Register'),
),
],
),
),
),
),

View File

@@ -0,0 +1,7 @@
/// Export all auth presentation pages
///
/// Contains all screens related to authentication
library;
export 'login_page.dart';
export 'register_page.dart';

View File

@@ -1,8 +1,10 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../providers/auth_provider.dart';
import '../widgets/widgets.dart';
import '../utils/validators.dart';
/// Register page for new user registration
/// Registration page for new users
class RegisterPage extends ConsumerStatefulWidget {
const RegisterPage({super.key});
@@ -16,8 +18,7 @@ class _RegisterPageState extends ConsumerState<RegisterPage> {
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
final _confirmPasswordController = TextEditingController();
bool _obscurePassword = true;
bool _obscureConfirmPassword = true;
bool _acceptTerms = false;
@override
void dispose() {
@@ -29,8 +30,27 @@ class _RegisterPageState extends ConsumerState<RegisterPage> {
}
Future<void> _handleRegister() async {
if (!_formKey.currentState!.validate()) return;
// Dismiss keyboard
FocusScope.of(context).unfocus();
// Validate form
if (!_formKey.currentState!.validate()) {
return;
}
// Check terms acceptance
if (!_acceptTerms) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: const Text('Please accept the terms and conditions'),
backgroundColor: Theme.of(context).colorScheme.error,
behavior: SnackBarBehavior.floating,
),
);
return;
}
// Attempt registration
final success = await ref.read(authProvider.notifier).register(
name: _nameController.text.trim(),
email: _emailController.text.trim(),
@@ -40,191 +60,241 @@ class _RegisterPageState extends ConsumerState<RegisterPage> {
if (!mounted) return;
if (success) {
// Navigate to home or show success
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Registration successful!')),
);
// TODO: Navigate to home page
} else {
final errorMessage = ref.read(authProvider).errorMessage;
// Show success message
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(errorMessage ?? 'Registration failed'),
backgroundColor: Colors.red,
content: const Text('Registration successful!'),
backgroundColor: Theme.of(context).colorScheme.primary,
behavior: SnackBarBehavior.floating,
),
);
// Navigation is handled by AuthWrapper
} else {
// Show error message
final authState = ref.read(authProvider);
if (authState.errorMessage != null) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(authState.errorMessage!),
backgroundColor: Theme.of(context).colorScheme.error,
behavior: SnackBarBehavior.floating,
action: SnackBarAction(
label: 'Dismiss',
textColor: Colors.white,
onPressed: () {},
),
),
);
}
}
}
void _navigateBackToLogin() {
Navigator.of(context).pop();
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final authState = ref.watch(authProvider);
final isLoading = authState.isLoading;
return Scaffold(
appBar: AppBar(
title: const Text('Register'),
),
body: SafeArea(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const SizedBox(height: 24),
// Logo or app name
Icon(
Icons.shopping_cart,
size: 80,
color: Theme.of(context).primaryColor,
),
const SizedBox(height: 16),
Text(
'Create Account',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.headlineMedium,
),
const SizedBox(height: 48),
// Name field
TextFormField(
controller: _nameController,
decoration: const InputDecoration(
labelText: 'Full Name',
prefixIcon: Icon(Icons.person),
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your name';
}
if (value.length < 2) {
return 'Name must be at least 2 characters';
}
return null;
},
),
const SizedBox(height: 16),
// Email field
TextFormField(
controller: _emailController,
keyboardType: TextInputType.emailAddress,
decoration: const InputDecoration(
labelText: 'Email',
prefixIcon: Icon(Icons.email),
border: OutlineInputBorder(),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your email';
}
if (!value.contains('@')) {
return 'Please enter a valid email';
}
return null;
},
),
const SizedBox(height: 16),
// Password field
TextFormField(
controller: _passwordController,
obscureText: _obscurePassword,
decoration: InputDecoration(
labelText: 'Password',
prefixIcon: const Icon(Icons.lock),
border: const OutlineInputBorder(),
suffixIcon: IconButton(
icon: Icon(
_obscurePassword
? Icons.visibility
: Icons.visibility_off,
return GestureDetector(
onTap: () => FocusScope.of(context).unfocus(),
child: Scaffold(
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: isLoading ? null : _navigateBackToLogin,
),
),
body: SafeArea(
child: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24.0),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 400),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Header
const AuthHeader(
title: 'Create Account',
subtitle: 'Join us and start managing your retail business.',
),
onPressed: () {
setState(() {
_obscurePassword = !_obscurePassword;
});
},
),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your password';
}
if (value.length < 8) {
return 'Password must be at least 8 characters';
}
// Check for uppercase, lowercase, and number
if (!RegExp(r'(?=.*[a-z])(?=.*[A-Z])(?=.*\d)').hasMatch(value)) {
return 'Password must contain uppercase, lowercase, and number';
}
return null;
},
),
const SizedBox(height: 16),
const SizedBox(height: 40),
// Confirm password field
TextFormField(
controller: _confirmPasswordController,
obscureText: _obscureConfirmPassword,
decoration: InputDecoration(
labelText: 'Confirm Password',
prefixIcon: const Icon(Icons.lock_outline),
border: const OutlineInputBorder(),
suffixIcon: IconButton(
icon: Icon(
_obscureConfirmPassword
? Icons.visibility
: Icons.visibility_off,
// Name field
AuthTextField(
controller: _nameController,
label: 'Full Name',
hint: 'Enter your full name',
keyboardType: TextInputType.name,
textInputAction: TextInputAction.next,
prefixIcon: Icons.person_outline,
validator: AuthValidators.validateName,
enabled: !isLoading,
autofocus: true,
),
onPressed: () {
setState(() {
_obscureConfirmPassword = !_obscureConfirmPassword;
});
},
),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please confirm your password';
}
if (value != _passwordController.text) {
return 'Passwords do not match';
}
return null;
},
),
const SizedBox(height: 24),
const SizedBox(height: 16),
// Register button
FilledButton(
onPressed: authState.isLoading ? null : _handleRegister,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: authState.isLoading
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
// Email field
AuthTextField(
controller: _emailController,
label: 'Email',
hint: 'Enter your email',
keyboardType: TextInputType.emailAddress,
textInputAction: TextInputAction.next,
prefixIcon: Icons.email_outlined,
validator: AuthValidators.validateEmail,
enabled: !isLoading,
),
const SizedBox(height: 16),
// Password field
PasswordField(
controller: _passwordController,
label: 'Password',
hint: 'Create a strong password',
textInputAction: TextInputAction.next,
validator: AuthValidators.validatePassword,
enabled: !isLoading,
),
const SizedBox(height: 16),
// Confirm password field
PasswordField(
controller: _confirmPasswordController,
label: 'Confirm Password',
hint: 'Re-enter your password',
textInputAction: TextInputAction.done,
validator: (value) => AuthValidators.validateConfirmPassword(
value,
_passwordController.text,
),
onFieldSubmitted: (_) => _handleRegister(),
enabled: !isLoading,
),
const SizedBox(height: 16),
// Terms and conditions checkbox
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Checkbox(
value: _acceptTerms,
onChanged: isLoading
? null
: (value) {
setState(() {
_acceptTerms = value ?? false;
});
},
),
Expanded(
child: Padding(
padding: const EdgeInsets.only(top: 12),
child: GestureDetector(
onTap: isLoading
? null
: () {
setState(() {
_acceptTerms = !_acceptTerms;
});
},
child: Text.rich(
TextSpan(
text: 'I agree to the ',
style: theme.textTheme.bodyMedium,
children: [
TextSpan(
text: 'Terms and Conditions',
style: TextStyle(
color: theme.colorScheme.primary,
fontWeight: FontWeight.w600,
),
),
const TextSpan(text: ' and '),
TextSpan(
text: 'Privacy Policy',
style: TextStyle(
color: theme.colorScheme.primary,
fontWeight: FontWeight.w600,
),
),
],
),
),
),
),
)
: const Text('Register'),
),
],
),
const SizedBox(height: 24),
// Register button
AuthButton(
onPressed: _handleRegister,
text: 'Create Account',
isLoading: isLoading,
),
const SizedBox(height: 24),
// Divider
Row(
children: [
Expanded(
child: Divider(
color: theme.colorScheme.onSurface.withOpacity(0.2),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Text(
'OR',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurface.withOpacity(0.5),
),
),
),
Expanded(
child: Divider(
color: theme.colorScheme.onSurface.withOpacity(0.2),
),
),
],
),
const SizedBox(height: 24),
// Login link
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Already have an account? ',
style: theme.textTheme.bodyMedium,
),
TextButton(
onPressed: isLoading ? null : _navigateBackToLogin,
child: Text(
'Login',
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.primary,
fontWeight: FontWeight.bold,
),
),
),
],
),
],
),
),
const SizedBox(height: 16),
// Login link
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text('Already have an account? Login'),
),
],
),
),
),
),

View File

@@ -0,0 +1,7 @@
/// Export all authentication presentation layer components
library;
export 'pages/pages.dart';
export 'providers/auth_provider.dart';
export 'utils/validators.dart';
export 'widgets/widgets.dart';

View File

@@ -1,14 +1,44 @@
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../../../core/di/injection_container.dart';
import '../../../../core/network/dio_client.dart';
import '../../../../core/storage/secure_storage.dart';
import '../../data/datasources/auth_remote_datasource.dart';
import '../../data/repositories/auth_repository_impl.dart';
import '../../domain/entities/user.dart';
import '../../domain/repositories/auth_repository.dart';
part 'auth_provider.g.dart';
/// Provider for DioClient (singleton)
@Riverpod(keepAlive: true)
DioClient dioClient(Ref ref) {
return DioClient();
}
/// Provider for SecureStorage (singleton)
@Riverpod(keepAlive: true)
SecureStorage secureStorage(Ref ref) {
return SecureStorage();
}
/// Provider for AuthRemoteDataSource
@Riverpod(keepAlive: true)
AuthRemoteDataSource authRemoteDataSource(Ref ref) {
final dioClient = ref.watch(dioClientProvider);
return AuthRemoteDataSourceImpl(dioClient: dioClient);
}
/// Provider for AuthRepository
@riverpod
@Riverpod(keepAlive: true)
AuthRepository authRepository(Ref ref) {
return sl<AuthRepository>();
final remoteDataSource = ref.watch(authRemoteDataSourceProvider);
final secureStorage = ref.watch(secureStorageProvider);
final dioClient = ref.watch(dioClientProvider);
return AuthRepositoryImpl(
remoteDataSource: remoteDataSource,
secureStorage: secureStorage,
dioClient: dioClient,
);
}
/// Auth state class
@@ -45,14 +75,15 @@ class AuthState {
class Auth extends _$Auth {
@override
AuthState build() {
_checkAuthStatus();
// Don't call async operations in build
// Use a separate method to initialize auth state
return const AuthState();
}
AuthRepository get _repository => ref.read(authRepositoryProvider);
/// Check if user is authenticated on app start
Future<void> _checkAuthStatus() async {
/// Initialize auth state - call this on app start
Future<void> initialize() async {
state = state.copyWith(isLoading: true);
final isAuthenticated = await _repository.isAuthenticated();

View File

@@ -8,6 +8,151 @@ part of 'auth_provider.dart';
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
/// Provider for DioClient (singleton)
@ProviderFor(dioClient)
const dioClientProvider = DioClientProvider._();
/// Provider for DioClient (singleton)
final class DioClientProvider
extends $FunctionalProvider<DioClient, DioClient, DioClient>
with $Provider<DioClient> {
/// Provider for DioClient (singleton)
const DioClientProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'dioClientProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$dioClientHash();
@$internal
@override
$ProviderElement<DioClient> $createElement($ProviderPointer pointer) =>
$ProviderElement(pointer);
@override
DioClient create(Ref ref) {
return dioClient(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(DioClient value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<DioClient>(value),
);
}
}
String _$dioClientHash() => r'895f0dc2f8d5eab562ad65390e5c6d4a1f722b0d';
/// Provider for SecureStorage (singleton)
@ProviderFor(secureStorage)
const secureStorageProvider = SecureStorageProvider._();
/// Provider for SecureStorage (singleton)
final class SecureStorageProvider
extends $FunctionalProvider<SecureStorage, SecureStorage, SecureStorage>
with $Provider<SecureStorage> {
/// Provider for SecureStorage (singleton)
const SecureStorageProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'secureStorageProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$secureStorageHash();
@$internal
@override
$ProviderElement<SecureStorage> $createElement($ProviderPointer pointer) =>
$ProviderElement(pointer);
@override
SecureStorage create(Ref ref) {
return secureStorage(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(SecureStorage value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<SecureStorage>(value),
);
}
}
String _$secureStorageHash() => r'5c9908c0046ad0e39469ee7acbb5540397b36693';
/// Provider for AuthRemoteDataSource
@ProviderFor(authRemoteDataSource)
const authRemoteDataSourceProvider = AuthRemoteDataSourceProvider._();
/// Provider for AuthRemoteDataSource
final class AuthRemoteDataSourceProvider
extends
$FunctionalProvider<
AuthRemoteDataSource,
AuthRemoteDataSource,
AuthRemoteDataSource
>
with $Provider<AuthRemoteDataSource> {
/// Provider for AuthRemoteDataSource
const AuthRemoteDataSourceProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'authRemoteDataSourceProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$authRemoteDataSourceHash();
@$internal
@override
$ProviderElement<AuthRemoteDataSource> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
AuthRemoteDataSource create(Ref ref) {
return authRemoteDataSource(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(AuthRemoteDataSource value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<AuthRemoteDataSource>(value),
);
}
}
String _$authRemoteDataSourceHash() =>
r'83759467bf61c03cf433b26d1126b19ab1d2b493';
/// Provider for AuthRepository
@ProviderFor(authRepository)
@@ -25,7 +170,7 @@ final class AuthRepositoryProvider
argument: null,
retry: null,
name: r'authRepositoryProvider',
isAutoDispose: true,
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@@ -52,7 +197,7 @@ final class AuthRepositoryProvider
}
}
String _$authRepositoryHash() => r'0483b13ac95333b56a1a82f6c9fdb64ae46f287d';
String _$authRepositoryHash() => r'5a333f81441082dd473e9089124aa65fda42be7b';
/// Auth state notifier provider
@@ -89,7 +234,7 @@ final class AuthProvider extends $NotifierProvider<Auth, AuthState> {
}
}
String _$authHash() => r'c88e150224fa855ed0ddfba30bef9e2b289f329d';
String _$authHash() => r'67ba3b381308cce5e693827ad22db940840c3978';
/// Auth state notifier provider

View File

@@ -0,0 +1,86 @@
/// Form validators for authentication
class AuthValidators {
AuthValidators._();
/// Validates email format
static String? validateEmail(String? value) {
if (value == null || value.isEmpty) {
return 'Email is required';
}
final emailRegex = RegExp(
r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
);
if (!emailRegex.hasMatch(value)) {
return 'Please enter a valid email address';
}
return null;
}
/// Validates password strength
/// Requirements: min 8 characters, at least one uppercase, one lowercase, one number
static String? validatePassword(String? value) {
if (value == null || value.isEmpty) {
return 'Password is required';
}
if (value.length < 8) {
return 'Password must be at least 8 characters';
}
if (!RegExp(r'[A-Z]').hasMatch(value)) {
return 'Password must contain at least one uppercase letter';
}
if (!RegExp(r'[a-z]').hasMatch(value)) {
return 'Password must contain at least one lowercase letter';
}
if (!RegExp(r'[0-9]').hasMatch(value)) {
return 'Password must contain at least one number';
}
return null;
}
/// Validates name field
static String? validateName(String? value) {
if (value == null || value.isEmpty) {
return 'Name is required';
}
if (value.length < 2) {
return 'Name must be at least 2 characters';
}
if (value.length > 50) {
return 'Name must not exceed 50 characters';
}
return null;
}
/// Validates password confirmation
static String? validateConfirmPassword(String? value, String password) {
if (value == null || value.isEmpty) {
return 'Please confirm your password';
}
if (value != password) {
return 'Passwords do not match';
}
return null;
}
/// Simple password validator for login (no strength requirements)
static String? validateLoginPassword(String? value) {
if (value == null || value.isEmpty) {
return 'Password is required';
}
return null;
}
}

View File

@@ -0,0 +1,58 @@
import 'package:flutter/material.dart';
/// Custom elevated button for authentication actions
class AuthButton extends StatelessWidget {
const AuthButton({
super.key,
required this.onPressed,
required this.text,
this.isLoading = false,
this.enabled = true,
});
final VoidCallback? onPressed;
final String text;
final bool isLoading;
final bool enabled;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return SizedBox(
width: double.infinity,
height: 50,
child: ElevatedButton(
onPressed: (enabled && !isLoading) ? onPressed : null,
style: ElevatedButton.styleFrom(
backgroundColor: theme.colorScheme.primary,
foregroundColor: theme.colorScheme.onPrimary,
disabledBackgroundColor:
theme.colorScheme.onSurface.withOpacity(0.12),
disabledForegroundColor:
theme.colorScheme.onSurface.withOpacity(0.38),
elevation: 2,
shadowColor: theme.colorScheme.primary.withOpacity(0.3),
),
child: isLoading
? SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
valueColor: AlwaysStoppedAnimation<Color>(
theme.colorScheme.onPrimary,
),
),
)
: Text(
text,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
color: theme.colorScheme.onPrimary,
),
),
),
);
}
}

View File

@@ -0,0 +1,59 @@
import 'package:flutter/material.dart';
/// Auth header widget displaying app logo and welcome text
class AuthHeader extends StatelessWidget {
const AuthHeader({
super.key,
required this.title,
required this.subtitle,
});
final String title;
final String subtitle;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Column(
mainAxisSize: MainAxisSize.min,
children: [
// App logo/icon
Container(
width: 100,
height: 100,
decoration: BoxDecoration(
color: theme.colorScheme.primaryContainer,
borderRadius: BorderRadius.circular(20),
),
child: Icon(
Icons.store,
size: 60,
color: theme.colorScheme.primary,
),
),
const SizedBox(height: 24),
// Title
Text(
title,
style: theme.textTheme.displaySmall?.copyWith(
fontWeight: FontWeight.bold,
color: theme.colorScheme.onSurface,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 8),
// Subtitle
Text(
subtitle,
style: theme.textTheme.bodyLarge?.copyWith(
color: theme.colorScheme.onSurface.withOpacity(0.6),
),
textAlign: TextAlign.center,
),
],
);
}
}

View File

@@ -0,0 +1,65 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// Custom text field for authentication forms
class AuthTextField extends StatelessWidget {
const AuthTextField({
super.key,
required this.controller,
required this.label,
this.hint,
this.validator,
this.keyboardType,
this.textInputAction,
this.onFieldSubmitted,
this.prefixIcon,
this.enabled = true,
this.autofocus = false,
this.inputFormatters,
});
final TextEditingController controller;
final String label;
final String? hint;
final String? Function(String?)? validator;
final TextInputType? keyboardType;
final TextInputAction? textInputAction;
final void Function(String)? onFieldSubmitted;
final IconData? prefixIcon;
final bool enabled;
final bool autofocus;
final List<TextInputFormatter>? inputFormatters;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return TextFormField(
controller: controller,
validator: validator,
keyboardType: keyboardType,
textInputAction: textInputAction,
onFieldSubmitted: onFieldSubmitted,
enabled: enabled,
autofocus: autofocus,
inputFormatters: inputFormatters,
style: theme.textTheme.bodyLarge,
decoration: InputDecoration(
labelText: label,
hintText: hint,
prefixIcon: prefixIcon != null
? Icon(prefixIcon, color: theme.colorScheme.primary)
: null,
labelStyle: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurface.withOpacity(0.7),
),
hintStyle: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurface.withOpacity(0.4),
),
errorStyle: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.error,
),
),
);
}
}

View File

@@ -0,0 +1,36 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../providers/auth_provider.dart';
import '../pages/login_page.dart';
/// Wrapper widget that checks authentication status
/// Shows login page if not authenticated, otherwise shows child widget
class AuthWrapper extends ConsumerWidget {
const AuthWrapper({
super.key,
required this.child,
});
final Widget child;
@override
Widget build(BuildContext context, WidgetRef ref) {
final authState = ref.watch(authProvider);
// Show loading indicator while checking auth status
if (authState.isLoading && authState.user == null) {
return const Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
}
// Show child widget if authenticated, otherwise show login page
if (authState.isAuthenticated) {
return child;
} else {
return const LoginPage();
}
}
}

View File

@@ -0,0 +1,78 @@
import 'package:flutter/material.dart';
/// Password field with show/hide toggle
class PasswordField extends StatefulWidget {
const PasswordField({
super.key,
required this.controller,
required this.label,
this.hint,
this.validator,
this.textInputAction,
this.onFieldSubmitted,
this.enabled = true,
this.autofocus = false,
});
final TextEditingController controller;
final String label;
final String? hint;
final String? Function(String?)? validator;
final TextInputAction? textInputAction;
final void Function(String)? onFieldSubmitted;
final bool enabled;
final bool autofocus;
@override
State<PasswordField> createState() => _PasswordFieldState();
}
class _PasswordFieldState extends State<PasswordField> {
bool _obscureText = true;
void _toggleVisibility() {
setState(() {
_obscureText = !_obscureText;
});
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return TextFormField(
controller: widget.controller,
validator: widget.validator,
obscureText: _obscureText,
textInputAction: widget.textInputAction,
onFieldSubmitted: widget.onFieldSubmitted,
enabled: widget.enabled,
autofocus: widget.autofocus,
style: theme.textTheme.bodyLarge,
decoration: InputDecoration(
labelText: widget.label,
hintText: widget.hint,
prefixIcon: Icon(
Icons.lock_outline,
color: theme.colorScheme.primary,
),
suffixIcon: IconButton(
icon: Icon(
_obscureText ? Icons.visibility : Icons.visibility_off,
color: theme.colorScheme.onSurface.withOpacity(0.6),
),
onPressed: _toggleVisibility,
),
labelStyle: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurface.withOpacity(0.7),
),
hintStyle: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurface.withOpacity(0.4),
),
errorStyle: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.error,
),
),
);
}
}

View File

@@ -0,0 +1,6 @@
/// Export file for all auth widgets
export 'auth_button.dart';
export 'auth_header.dart';
export 'auth_text_field.dart';
export 'auth_wrapper.dart';
export 'password_field.dart';