uaestats_fe/lib/config/sessionCheckScreen.dart

261 lines
8.2 KiB
Dart
Executable File

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:uae_stat/domain/entities/session_entity.dart';
import 'package:uae_stat/infrastructure/data/p_auth_repo.dart';
class AuthRepository {
final FlutterSecureStorage _secureStorage = const FlutterSecureStorage();
Future<String?> fetchLocallyStored() async {
return await _secureStorage.read(key: "FlutterSecureStorage.session");
}
}
class SessionCheckScreen extends StatefulWidget {
const SessionCheckScreen({Key? key}) : super(key: key);
@override
_SessionCheckScreenState createState() => _SessionCheckScreenState();
}
class _SessionCheckScreenState extends State<SessionCheckScreen> {
final PAuthRepo _authRepo = PAuthRepo();
final String playStoreUrl = "https://play.google.com/store/apps/details?id=ae.gov.fcsc.stats";
bool _isLoading = true;
bool _isLoginPath(String path) {
return path == '/login' || path.startsWith('/login?');
}
bool _isForgotPasswordPath(String path) {
return path.startsWith('/forgot-password/');
}
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
_checkSession();
});
}
Future<void> _checkSession() async {
final SessionEntity? session =
await _authRepo.fetchLocallyStored();
final uri = GoRouter.of(context)
.routeInformationProvider
.value
.uri;
final intendedPath = uri.queryParameters['intendedPath'];
final normalizedIntendedPath =
(intendedPath != null && intendedPath.isNotEmpty)
? Uri.decodeComponent(intendedPath)
: null;
if (session != null &&
session.freshness != SessionFreshness.expired) {
if (normalizedIntendedPath != null && normalizedIntendedPath.isNotEmpty) {
// Deep link to /login should open home when session is already valid.
if (_isLoginPath(normalizedIntendedPath)) {
context.go('/myhomepage');
} else {
context.go(normalizedIntendedPath);
}
} else {
context.go('/myhomepage');
}
} else {
if (normalizedIntendedPath != null && normalizedIntendedPath.isNotEmpty) {
// Forgot password links are public and should open directly.
if (_isForgotPasswordPath(normalizedIntendedPath)) {
context.go(normalizedIntendedPath);
} else {
context.go('/login?intendedPath=${Uri.encodeComponent(normalizedIntendedPath)}');
}
} else {
context.go('/login');
}
}
}
@override
@override
Widget build(BuildContext context) {
return _isLoading
? SplashScreen() // Show splash while loading
: SizedBox.shrink();
}
}
class SplashScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
final isDark = Theme.of(context).brightness == Brightness.dark;
return Scaffold(
backgroundColor: isDark ? null : Colors.white,
body: Container(
decoration: BoxDecoration(
color: isDark ? null : Colors.white,
image: isDark
? DecorationImage(
image: AssetImage(
'assets/splash_screen/background_splash_dark.png'), // 🔄 Add this background for dark mode
fit: BoxFit.cover,
)
: null,
),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// 🔄 White or normal logo depending on theme
Spacer(),
Image.asset(
isDark
? 'assets/splash_screen/FCSCLogo_dark.png'
: 'assets/splash_screen/FCSCLogo_light.png',
width: 150,
),
SizedBox(height: 20),
// Optional: Progress indicator or version
// CircularProgressIndicator(color: isDark ? Colors.white : Colors.black),
Spacer(),
Padding(
padding: const EdgeInsets.only(bottom: 24.0),
child: Column(
children: [
Text(
'© حقوق التأليف والنشر',
style: TextStyle(
color: isDark ? Colors.white70 : Colors.black54,
fontSize: 14,
fontFamily: 'NotoKufi',
),
),
],
),
),
],
),
),
),
);
}
}
// // import 'package:flutter/material.dart';
// // import 'package:go_router/go_router.dart';
// // import 'package:flutter_secure_storage/flutter_secure_storage.dart';
// // import 'package:uae_stat/infrastructure/data/p_auth_repo.dart';
// // import 'package:url_launcher/url_launcher.dart';
// //
// // class AuthRepository {
// // final FlutterSecureStorage _secureStorage = const FlutterSecureStorage();
// //
// // Future<String?> fetchLocallyStored() async {
// // return await _secureStorage.read(key: "FlutterSecureStorage.session");
// // }
// // }
// //
// // class SessionCheckScreen extends StatefulWidget {
// // const SessionCheckScreen({Key? key}) : super(key: key);
// //
// // @override
// // _SessionCheckScreenState createState() => _SessionCheckScreenState();
// // }
// //
// // class _SessionCheckScreenState extends State<SessionCheckScreen> {
// // final PAuthRepo _pAuthRepo = PAuthRepo();
// // final AuthRepository _authRepo = AuthRepository();
// // final String playStoreUrl = "https://play.google.com/store/apps/details?id=ae.gov.fcsc.stats";
// //
// // @override
// // void initState() {
// // super.initState();
// // WidgetsBinding.instance.addPostFrameCallback((_) {
// // _checkSessionAndHandleLink();
// // });
// // }
// //
// // Future<void> _checkSessionAndHandleLink() async {
// // try {
// // final session = await _authRepo.fetchLocallyStored();
// //
// // // Check if user is not logged in
// // if (session == null || session.isEmpty) {
// // _handleUnauthenticatedUser();
// // return;
// // }
// //
// // // User is authenticated, process the shared link
// // final GoRouterState state = GoRouterState.of(context);
// // final String? sharedLink = state.uri.toString().isNotEmpty && state.uri.path != '/'
// // ? state.uri.toString()
// // : null;
// //
// // if (sharedLink != null) {
// // // Validate if the link is a valid app route
// // final Uri parsedUri = Uri.parse(sharedLink);
// // final String path = parsedUri.path;
// //
// // if (mounted) {
// // GoRouter.of(context).go(path);
// // }
// // } else {
// // // Default route for authenticated users with no specific link
// // if (mounted) {
// // GoRouter.of(context).go('/myhomepage');
// // }
// // }
// // } catch (e) {
// // print("Error processing link: $e");
// // _handleUnauthenticatedUser();
// // }
// // }
// //
// // void _handleUnauthenticatedUser() {
// // final GoRouterState state = GoRouterState.of(context);
// // final String? sharedLink = state.uri.toString().isNotEmpty && state.uri.path != '/'
// // ? state.uri.toString()
// // : null;
// //
// // if (sharedLink != null) {
// // // Store the intended destination and redirect to login
// // if (mounted) {
// // GoRouter.of(context).go('/login', extra: {'redirectTo': sharedLink});
// // }
// // } else {
// // // No specific link, just go to login
// // if (mounted) {
// // GoRouter.of(context).go('/login');
// // }
// // }
// // }
// //
// // Future<void> _redirectToPlayStore() async {
// // final Uri url = Uri.parse(playStoreUrl);
// //
// // if (await canLaunchUrl(url)) {
// // await launchUrl(url, mode: LaunchMode.externalApplication);
// // }
// // }
// //
// // @override
// // Widget build(BuildContext context) {
// // return const Scaffold(
// // body: Center(
// // child: CircularProgressIndicator(),
// // ),
// // );
// // }
// // }