67 lines
1.8 KiB
Dart
67 lines
1.8 KiB
Dart
import 'dart:convert';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
|
import '../../auth/data/token_storage.dart';
|
|
import '../../../main.dart';
|
|
import 'package:go_router/go_router.dart';
|
|
|
|
class SplashScreen extends ConsumerStatefulWidget {
|
|
const SplashScreen({super.key});
|
|
@override
|
|
ConsumerState<SplashScreen> createState() => _SplashState();
|
|
}
|
|
|
|
class _SplashState extends ConsumerState<SplashScreen> {
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
_boot();
|
|
}
|
|
|
|
Future<void> _boot() async {
|
|
final tokens = ref.read(tokenStorageProvider);
|
|
// 1) Versuch: vorhandenes Access prüfen
|
|
final access = await tokens.access;
|
|
final isValid = _isJwtValid(access);
|
|
|
|
if (!isValid) {
|
|
// 2) Refresh versuchen
|
|
await tokens.refreshAccess();
|
|
}
|
|
|
|
final access2 = await tokens.access;
|
|
final authed = _isJwtValid(access2);
|
|
|
|
if (!mounted) return;
|
|
if (authed) {
|
|
context.go('/igel');
|
|
} else {
|
|
context.go('/login');
|
|
}
|
|
}
|
|
|
|
bool _isJwtValid(String? jwt) {
|
|
if (jwt == null || jwt.isEmpty) return false;
|
|
try {
|
|
final parts = jwt.split('.');
|
|
if (parts.length != 3) return false;
|
|
final payload = jsonDecode(
|
|
utf8.decode(base64Url.decode(base64Url.normalize(parts[1]))))
|
|
as Map<String, dynamic>;
|
|
final exp = (payload['exp'] as num?)?.toInt();
|
|
if (exp == null) return true; // kein exp => als gültig betrachten
|
|
final now = DateTime.now().millisecondsSinceEpoch ~/ 1000;
|
|
return now < exp - 15; // kleine Toleranz
|
|
} catch (_) {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return const Scaffold(
|
|
body: Center(child: CircularProgressIndicator()),
|
|
);
|
|
}
|
|
}
|