1
0
forked from baron/baron-sso
Files
baron-sso/frontend/lib/features/auth/presentation/login_screen.dart

599 lines
22 KiB
Dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:descope/descope.dart';
import 'package:go_router/go_router.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'package:qr_flutter/qr_flutter.dart';
import '../../../core/services/audit_service.dart';
import '../../../core/services/web_auth_integration.dart';
import '../../../core/services/auth_proxy_service.dart';
class LoginScreen extends ConsumerStatefulWidget {
final String? verificationToken;
const LoginScreen({super.key, this.verificationToken});
@override
ConsumerState<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends ConsumerState<LoginScreen>
with SingleTickerProviderStateMixin {
late TabController _tabController;
final TextEditingController _emailController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
final TextEditingController _phoneController = TextEditingController();
final TextEditingController _smsCodeController = TextEditingController();
bool _smsSent = false;
String? _redirectUrl;
// QR Login Variables
String? _qrImageBase64;
String? _qrPendingRef;
bool _isQrLoading = false;
Timer? _qrPollingTimer;
int _qrRemainingSeconds = 0;
Timer? _qrCountdownTimer;
@override
void initState() {
super.initState();
_tabController = TabController(length: 3, vsync: this, initialIndex: 1);
_tabController.addListener(_handleTabSelection);
// Check for tokens (Path Parameter or Legacy Query Parameter)
WidgetsBinding.instance.addPostFrameCallback((_) {
if (widget.verificationToken != null) {
_verifyToken(widget.verificationToken!);
} else {
final uri = Uri.base;
if (uri.queryParameters.containsKey('t')) {
_verifyToken(uri.queryParameters['t']!);
}
}
final uri = Uri.base;
if (uri.queryParameters.containsKey('redirect_url')) {
_redirectUrl = uri.queryParameters['redirect_url'];
}
});
}
void _handleTabSelection() {
if (_tabController.index == 2 && _qrPendingRef == null) {
_startQrFlow();
} else if (_tabController.index != 2) {
_stopQrPolling();
}
}
Future<void> _startQrFlow() async {
if (_isQrLoading) return;
setState(() {
_isQrLoading = true;
_qrImageBase64 = null;
_qrRemainingSeconds = 0;
});
try {
final res = await AuthProxyService.initQrLogin();
if (mounted) {
setState(() {
_qrImageBase64 = res['qrCode'];
_qrPendingRef = res['pendingRef'];
_qrRemainingSeconds = res['expiresIn'] ?? 300;
_isQrLoading = false;
});
_startQrPolling();
_startCountdown();
}
} catch (e) {
_showError("Failed to init QR: $e");
if (mounted) setState(() => _isQrLoading = false);
}
}
void _startCountdown() {
_qrCountdownTimer?.cancel();
_qrCountdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
if (!mounted || _qrRemainingSeconds <= 0) {
timer.cancel();
if (_qrRemainingSeconds <= 0) _stopQrPolling();
return;
}
setState(() {
_qrRemainingSeconds--;
});
});
}
void _startQrPolling() {
_qrPollingTimer?.cancel();
_qrPollingTimer = Timer.periodic(const Duration(milliseconds: 1500), (timer) async {
if (_qrPendingRef == null || !mounted || _qrRemainingSeconds <= 0) {
timer.cancel();
return;
}
try {
final res = await AuthProxyService.pollQrStatus(_qrPendingRef!);
if (res['status'] == 'ok' && res['sessionJwt'] != null) {
timer.cancel();
_qrCountdownTimer?.cancel();
_onLoginSuccess(res['sessionJwt']);
}
} catch (e) {
debugPrint("[QR] Polling error: $e");
}
});
}
void _stopQrPolling() {
_qrPollingTimer?.cancel();
_qrPollingTimer = null;
_qrCountdownTimer?.cancel();
_qrCountdownTimer = null;
_qrPendingRef = null;
}
String _formatTime(int seconds) {
final m = seconds ~/ 60;
final s = seconds % 60;
return "${m.toString().padLeft(2, '0')}:${s.toString().padLeft(2, '0')}";
}
Future<void> _verifyToken(String token) async {
debugPrint("[Auth] Starting verification for token: $token");
try {
// Use Backend to verify the token (Backend-Driven Flow)
await AuthProxyService.verifyMagicLink(token);
debugPrint("[Auth] Verification successful for token: $token");
if (mounted) {
_showSuccessDialog();
}
} catch (e) {
debugPrint("[Auth] Verification FAILED for token: $token. Error: $e");
if (mounted) {
_showError("Verification failed: $e");
}
}
}
void _showSuccessDialog() {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => const AlertDialog(
title: Text("Authentication Successful"),
content: Text("You can close this tab and return to the application."),
),
);
}
@override
void dispose() {
_stopQrPolling();
_tabController.dispose();
_emailController.dispose();
_passwordController.dispose();
_phoneController.dispose();
_smsCodeController.dispose();
super.dispose();
}
Future<void> _handleEmailLogin() async {
final email = _emailController.text.trim();
if (email.isEmpty) return;
final password = _passwordController.text;
if (password.isNotEmpty) {
debugPrint("[Auth] Attempting Email/Password login for: $email");
try {
final authResponse = await Descope.password.signIn(
loginId: email,
password: password,
);
final session = DescopeSession.fromAuthenticationResponse(authResponse);
Descope.sessionManager.manageSession(session);
debugPrint("[Auth] Email login successful");
if (mounted) _onLoginSuccess(session.sessionToken.jwt);
} catch (e) {
debugPrint("[Auth] Email login failed: $e");
_showError("Email/Password Login Failed: $e");
}
} else {
debugPrint("[Auth] Initiating Email Enchanted Link for: $email");
_initiateDescopeLinkFlow(email, isSms: false);
}
}
Future<void> _handleSmsLogin() async {
final rawPhone = _phoneController.text.trim();
if (rawPhone.isEmpty) return;
String phone = rawPhone.replaceAll(RegExp(r'[-\s]'), '');
if (phone.startsWith('010')) {
phone = '+82${phone.substring(1)}'; // Convert 010 to +8210
}
debugPrint("[Auth] Initiating SMS Enchanted Link for: $phone");
try {
if (mounted) {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => const Center(child: CircularProgressIndicator()),
);
}
// 1. Init via Backend API
final initResponse = await AuthProxyService.initEnchantedLink(phone);
final pendingRef = initResponse['pendingRef'];
debugPrint("[Auth] SMS Sent. PendingRef: $pendingRef");
if (mounted) {
Navigator.of(context).pop(); // Close Loading
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => AlertDialog(
title: const Text("SMS Sent"),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text("Please check the link sent to your phone."),
const SizedBox(height: 16),
const LinearProgressIndicator(),
const SizedBox(height: 16),
TextButton(
onPressed: () {
debugPrint("[Auth] Polling canceled by user");
Navigator.of(context).pop();
},
child: const Text("Cancel")
)
],
),
),
);
// 2. Poll Backend manually
_pollForSession(pendingRef);
}
} catch (e) {
debugPrint("[Auth] SMS initialization failed: $e");
if (mounted && Navigator.canPop(context)) Navigator.of(context).pop();
_showError("Failed to send SMS: $e");
}
}
Future<void> _pollForSession(String pendingRef) async {
int attempts = 0;
const maxAttempts = 60; // 2 minutes
debugPrint("[Auth] Starting poll for ref: $pendingRef");
while (attempts < maxAttempts && mounted) {
await Future.delayed(const Duration(seconds: 2));
attempts++;
try {
final result = await AuthProxyService.pollEnchantedLink(pendingRef);
if (result['status'] == 'ok') {
final jwt = result['sessionJwt'];
if (jwt != null) {
debugPrint("[Auth] Polling SUCCESS. Token received.");
// Descope SDK 세션 강제 주입
// Note: DescopeUser in 0.9.11 requires 18 positional arguments.
final dummyUser = DescopeUser(
'unknown', // userId
[], // loginIds
0, // createdAt
'User', // name
null, // picture (Uri?)
'', // email
false, // isVerifiedEmail
'', // phone
false, // isVerifiedPhone
{}, // customAttributes
'', // givenName
'', // middleName
'', // familyName
false, // hasPassword
'enabled', // status
[], // roleNames
[], // ssoAppIds
[], // oauthProviders (List<String>)
);
final session = DescopeSession.fromJwt(jwt, jwt, dummyUser);
Descope.sessionManager.manageSession(session);
if (mounted) {
Navigator.of(context).pop(); // Close Polling Dialog
_onLoginSuccess(jwt);
}
return;
}
}
} catch (e) {
debugPrint("[Auth] Polling error (attempt $attempts): $e");
}
}
if (mounted) {
debugPrint("[Auth] Polling timed out for ref: $pendingRef");
Navigator.of(context).pop(); // Close Polling Dialog
_showError("Login timed out.");
}
}
Future<void> _initiateDescopeLinkFlow(String loginId, {required bool isSms}) async {
try {
if (mounted) {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => const Center(child: CircularProgressIndicator()),
);
}
// 1. Init via Descope SDK
final frontendUrl = dotenv.env['FRONTEND_URL'] ?? 'http://ssologin.hmac.kr';
final signUpOrInResponse = await Descope.enchantedLink.signUpOrIn(
loginId: loginId,
redirectUrl: "$frontendUrl/auth/callback",
);
if (mounted) {
Navigator.of(context).pop(); // Close Loading
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => AlertDialog(
title: Text(isSms ? "SMS Sent" : "Email Sent"),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text("We sent a login link to ${isSms ? loginId.split('@')[0] : loginId}"),
const SizedBox(height: 16),
// For SMS, we might not get a Link ID in the message if the template doesn't include it.
// But Enchanted Link always has one.
Text(
"Security Number: ${signUpOrInResponse.linkId}",
style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: Colors.blue),
),
const SizedBox(height: 8),
const Text("Click the matching number."),
const SizedBox(height: 16),
const LinearProgressIndicator(),
],
),
),
);
// 2. Poll via Descope SDK
final authResponse = await Descope.enchantedLink.pollForSession(pendingRef: signUpOrInResponse.pendingRef);
final session = DescopeSession.fromAuthenticationResponse(authResponse);
Descope.sessionManager.manageSession(session);
if (mounted) {
Navigator.of(context).pop(); // Close Dialog
_onLoginSuccess(session.sessionToken.jwt);
}
}
} catch (e) {
if (mounted && Navigator.canPop(context)) Navigator.of(context).pop();
_showError("Login Failed: $e");
}
}
void _onLoginSuccess(String token) {
if (!mounted) return;
// Record Audit Log
AuditService.logEvent(
userId: "unknown", // In real apps, parse token to get user ID
eventType: "LOGIN_SUCCESS",
status: "SUCCESS",
details: "User logged in via Baron SSO",
);
if (WebAuthIntegration.isPopup()) {
WebAuthIntegration.sendLoginSuccess(token);
_showError("Login Successful! You can close this window.");
} else if (_redirectUrl != null && _redirectUrl!.isNotEmpty) {
final target = "$_redirectUrl?token=$token";
launchUrlString(target, webOnlyWindowName: '_self');
} else {
// Standalone mode: Go to dashboard to act as an auth platform
if (mounted) context.go('/dashboard');
}
}
void _showError(String message) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(message), backgroundColor: Colors.red),
);
try {
AuthProxyService.logError(message);
} catch (e) {
// ignore
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: LayoutBuilder(
builder: (context, constraints) {
return SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(minHeight: constraints.maxHeight),
child: Center(
child: Container(
constraints: const BoxConstraints(maxWidth: 400),
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
"Baron SSO",
style: GoogleFonts.outfit(
fontSize: 32,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 40),
TabBar(
controller: _tabController,
tabs: const [
Tab(text: "이메일"),
Tab(text: "전화번호"),
Tab(text: "QR 코드"),
],
),
const SizedBox(height: 24),
SizedBox(
height: 350,
child: TabBarView(
controller: _tabController,
children: [
// Email Form
Padding(
padding: const EdgeInsets.only(top: 16.0),
child: Column(
children: [
TextField(
controller: _emailController,
decoration: const InputDecoration(
labelText: "이메일",
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.email_outlined),
),
),
const SizedBox(height: 16),
TextField(
controller: _passwordController,
obscureText: true,
decoration: const InputDecoration(
labelText: "비밀번호 (선택)",
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.lock_outline),
),
),
const SizedBox(height: 24),
FilledButton(
onPressed: _handleEmailLogin,
style: FilledButton.styleFrom(
minimumSize: const Size.fromHeight(50),
),
child: const Text("로그인 / 링크 전송"),
),
],
),
),
// Phone Form
Padding(
padding: const EdgeInsets.only(top: 16.0),
child: Column(
children: [
TextField(
controller: _phoneController,
decoration: const InputDecoration(
labelText: "휴대폰 번호",
hintText: "010-1234-5678",
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.phone_android),
),
),
const SizedBox(height: 24),
FilledButton(
onPressed: _handleSmsLogin,
style: FilledButton.styleFrom(
minimumSize: const Size.fromHeight(50),
),
child: const Text("로그인 링크 전송"),
),
const SizedBox(height: 16),
const Text(
"입력하신 번호로 로그인 링크를 문자로 보내드립니다.",
style: TextStyle(color: Colors.grey, fontSize: 12),
textAlign: TextAlign.center,
),
],
),
),
// QR Login View
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (_isQrLoading)
const CircularProgressIndicator()
else if (_qrImageBase64 != null)
Column(
children: [
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade300),
borderRadius: BorderRadius.circular(12),
),
child: QrImageView(
data: _qrImageBase64!,
version: QrVersions.auto,
size: 200.0,
),
),
const SizedBox(height: 12),
Text(
_qrRemainingSeconds > 0
? "남은 시간: ${_formatTime(_qrRemainingSeconds)}"
: "QR 코드 만료됨",
style: TextStyle(
color: _qrRemainingSeconds > 30 ? Colors.blue : Colors.red,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
const Text(
"모바일 앱으로 스캔하세요",
style: TextStyle(color: Colors.grey, fontSize: 12),
),
TextButton(
onPressed: _startQrFlow,
child: const Text("QR 코드 새로고침")
),
],
)
else
const Text("QR 코드를 불러오지 못했습니다."),
],
),
],
),
),
],
),
),
),
),
);
},
),
);
}
}