1
0
forked from baron/baron-sso

log 추가

This commit is contained in:
2026-01-14 15:00:46 +09:00
parent da5a5bd25a
commit 2317eb857c
4 changed files with 110 additions and 55 deletions

View File

@@ -51,20 +51,17 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
}
Future<void> _verifyToken(String token) async {
debugPrint("[Auth] Starting verification for token: $token");
try {
// Use Backend to verify the token (Backend-Driven Flow)
// The backend will validate the local token, and then trigger Descope JWT generation.
// This approves the pending session for the Polling device.
await AuthProxyService.verifyMagicLink(token);
// Note: If this device (Mobile) also needs to login, we would need to
// parse the response from verifyMagicLink which contains the JWT.
// For now, we assume this action primarily approves the PC session.
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");
}
@@ -98,6 +95,7 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
final password = _passwordController.text;
if (password.isNotEmpty) {
debugPrint("[Auth] Attempting Email/Password login for: $email");
try {
final authResponse = await Descope.password.signIn(
loginId: email,
@@ -105,12 +103,14 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
);
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 {
// Email Enchanted Link (Descope Standard)
debugPrint("[Auth] Initiating Email Enchanted Link for: $email");
_initiateDescopeLinkFlow(email, isSms: false);
}
}
@@ -119,9 +119,8 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
final rawPhone = _phoneController.text.trim();
if (rawPhone.isEmpty) return;
// Sanitize phone number
String phone = rawPhone.replaceAll(RegExp(r'[-\s]'), '');
// Ensure 010 format if needed, but backend handles it too
debugPrint("[Auth] Initiating SMS Enchanted Link for: $phone");
try {
if (mounted) {
@@ -132,14 +131,14 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
);
}
// 1. Init via Backend API (Not Descope SDK)
// 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
// Show Waiting Dialog
showDialog(
context: context,
barrierDismissible: false,
@@ -154,7 +153,8 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
const SizedBox(height: 16),
TextButton(
onPressed: () {
Navigator.of(context).pop(); // Allow canceling
debugPrint("[Auth] Polling canceled by user");
Navigator.of(context).pop();
},
child: const Text("Cancel")
)
@@ -167,6 +167,7 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
_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");
}
@@ -175,6 +176,7 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
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));
@@ -186,12 +188,7 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
if (result['status'] == 'ok') {
final jwt = result['sessionJwt'];
if (jwt != null) {
// Note: Manually constructing DescopeSession can be complex due to abstract classes.
// In a real production app, you should use the SDK's built-in exchange/verify methods.
// For this prototype, we will proceed with the login success callback.
// If session management is required immediately, we'd need to match the specific
// SDK version's Token implementation.
debugPrint("[Auth] Polling SUCCESS. Token received.");
if (mounted) {
Navigator.of(context).pop(); // Close Polling Dialog
_onLoginSuccess(jwt);
@@ -200,13 +197,12 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
}
}
} catch (e) {
print("Polling error: $e");
// Continue polling even on temporary network error?
// Or break? Let's continue.
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.");
}
@@ -277,6 +273,14 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
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.");

View File

@@ -1,3 +1,4 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
@@ -7,11 +8,23 @@ import 'package:google_fonts/google_fonts.dart';
import 'package:flutter_web_plugins/url_strategy.dart';
import 'features/auth/presentation/login_screen.dart';
import 'features/dashboard/presentation/dashboard_screen.dart';
import 'core/services/auth_proxy_service.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
usePathUrlStrategy();
// 1. Global Error Handling
FlutterError.onError = (details) {
FlutterError.presentError(details);
AuthProxyService.logError("FLUTTER_ERROR: ${details.exception}\n${details.stack}");
};
PlatformDispatcher.instance.onError = (error, stack) {
AuthProxyService.logError("PLATFORM_ERROR: $error\n$stack");
return true;
};
// Load Env (Handling error if missing for now)
try {
await dotenv.load(fileName: ".env");
@@ -36,18 +49,29 @@ void main() async {
// Router Configuration
final _router = GoRouter(
initialLocation: '/',
debugLogDiagnostics: true, // Enable diagnostic logs
routes: [
GoRoute(path: '/', builder: (context, state) => const LoginScreen()),
GoRoute(
path: '/',
builder: (context, state) {
debugPrint("[Router] Navigating to root (LoginScreen)");
return const LoginScreen();
}
),
GoRoute(
path: '/verify/:token',
builder: (context, state) {
final token = state.pathParameters['token'];
debugPrint("[Router] Navigating to /verify with token: $token");
return LoginScreen(verificationToken: token);
},
),
GoRoute(
path: '/dashboard',
builder: (context, state) => const DashboardScreen(),
builder: (context, state) {
debugPrint("[Router] Navigating to /dashboard");
return const DashboardScreen();
},
),
],
redirect: (context, state) {
@@ -56,8 +80,16 @@ final _router = GoRouter(
final path = state.uri.path;
final isLoggingIn = path == '/' || path.startsWith('/verify/');
if (!isLoggedIn && !isLoggingIn) return '/';
if (isLoggedIn && path == '/') return '/dashboard';
debugPrint("[Router] Redirect check - Path: $path, IsLoggedIn: $isLoggedIn");
if (!isLoggedIn && !isLoggingIn) {
debugPrint("[Router] Not logged in, redirecting to /");
return '/';
}
if (isLoggedIn && path == '/') {
debugPrint("[Router] Logged in, redirecting to /dashboard");
return '/dashboard';
}
return null;
},