From b65ecc1b24a79e88c59a3469c7b8d76ad8d1c7d3 Mon Sep 17 00:00:00 2001 From: chan Date: Fri, 16 Jan 2026 17:42:59 +0900 Subject: [PATCH 1/4] =?UTF-8?q?qr=20=EB=A1=9C=EA=B7=B8=EC=9D=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/cmd/server/main.go | 3 + backend/internal/domain/auth_models.go | 6 + backend/internal/handler/auth_handler.go | 99 +++++++++- .../lib/core/services/auth_proxy_service.dart | 45 +++++ .../auth/presentation/approve_qr_screen.dart | 117 ++++++++++++ .../auth/presentation/login_screen.dart | 178 +++++++++++++++++- frontend/lib/main.dart | 11 +- frontend/pubspec.yaml | 1 + 8 files changed, 446 insertions(+), 14 deletions(-) create mode 100644 frontend/lib/features/auth/presentation/approve_qr_screen.dart diff --git a/backend/cmd/server/main.go b/backend/cmd/server/main.go index bbdedced..8951cb40 100644 --- a/backend/cmd/server/main.go +++ b/backend/cmd/server/main.go @@ -132,6 +132,9 @@ func main() { auth.Post("/magic-link/verify", authHandler.VerifyMagicLink) auth.Post("/sms", authHandler.SendSms) auth.Post("/verify-sms", authHandler.VerifySms) + auth.Post("/qr/init", authHandler.InitQRLogin) + auth.Post("/qr/poll", authHandler.PollQRLogin) + auth.Post("/qr/approve", authHandler.ScanQRLogin) // Admin Routes admin := api.Group("/admin") diff --git a/backend/internal/domain/auth_models.go b/backend/internal/domain/auth_models.go index 9da4b79c..89992130 100644 --- a/backend/internal/domain/auth_models.go +++ b/backend/internal/domain/auth_models.go @@ -24,4 +24,10 @@ type EnchantedLinkPollResponse struct { type MagicLinkVerifyRequest struct { Token string `json:"token"` +} + +type QRInitResponse struct { + QRCode string `json:"qrCode"` // Base64 or URL + PendingRef string `json:"pendingRef"` + ExpiresIn int `json:"expiresIn"` } \ No newline at end of file diff --git a/backend/internal/handler/auth_handler.go b/backend/internal/handler/auth_handler.go index 29bc67b4..ca220a1e 100644 --- a/backend/internal/handler/auth_handler.go +++ b/backend/internal/handler/auth_handler.go @@ -132,7 +132,7 @@ func (h *AuthHandler) InitEnchantedLink(c *fiber.Ctx) error { loginID := strings.ReplaceAll(req.LoginID, "-", "") loginID = strings.ReplaceAll(loginID, " ", "") - + // Generate secure tokens token := GenerateSecureToken(3) pendingRef := GenerateSecureToken(3) @@ -150,7 +150,7 @@ func (h *AuthHandler) InitEnchantedLink(c *fiber.Ctx) error { } link := fmt.Sprintf("%s/verify/%s", frontendURL, token) content := fmt.Sprintf("[Baron SSO] 로그인 링크: %s", link) - + log.Printf("[Enchanted] Sending SMS to %s via Naver Cloud", loginID) if err := h.SmsService.SendSms(loginID, content); err != nil { @@ -230,8 +230,8 @@ func (h *AuthHandler) VerifyMagicLink(c *fiber.Ctx) error { if strings.HasPrefix(searchPhone, "010") { searchPhone = "+82" + searchPhone[1:] } else if strings.HasPrefix(searchPhone, "82") { - searchPhone = "+" + searchPhone - } + searchPhone = "+" + searchPhone + } } log.Printf("[Verify] Searching for user with phone: %s", searchPhone) @@ -239,10 +239,10 @@ func (h *AuthHandler) VerifyMagicLink(c *fiber.Ctx) error { Phones: []string{searchPhone}, Limit: 1, } - + var targetLoginID string users, _, errSearch := h.DescopeClient.Management.User().SearchAll(context.Background(), searchOptions) - + if errSearch == nil && len(users) > 0 { if len(users[0].LoginIDs) > 0 { targetLoginID = users[0].LoginIDs[0] @@ -264,7 +264,7 @@ func (h *AuthHandler) VerifyMagicLink(c *fiber.Ctx) error { if err != nil { if strings.Contains(err.Error(), "User not found") || strings.Contains(err.Error(), "E062108") { log.Printf("[Verify] User %s not found. Creating...", targetLoginID) - + // Create User with Explicit Phone Attribute userObj := &descope.UserRequest{} if strings.Contains(targetLoginID, "@") { @@ -278,7 +278,7 @@ func (h *AuthHandler) VerifyMagicLink(c *fiber.Ctx) error { log.Printf("[Verify] Failed to create user: %v", errCreate) return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Failed to create new user"}) } - + embeddedToken, err = h.DescopeClient.Management.User().GenerateEmbeddedLink(context.Background(), targetLoginID, nil, 0) if err != nil { log.Printf("[Verify] Failed to generate token after creation: %v", err) @@ -304,12 +304,93 @@ func (h *AuthHandler) VerifyMagicLink(c *fiber.Ctx) error { "jwt": sessionToken, }) h.RedisService.Set(prefixSession+pendingRef, string(sessionData), defaultExpiration) - + return c.JSON(fiber.Map{ "token": sessionToken, "message": "Login successful", }) } + +// InitQRLogin - Step 1: Web 패널에서 QR 로그인 세션을 생성합니다. +func (h *AuthHandler) InitQRLogin(c *fiber.Ctx) error { + pendingRef := GenerateSecureToken(16) + + // QR 코드 페이로드를 실제 접속 가능한 URL로 변경합니다. + frontendURL := os.Getenv("FRONTEND_URL") + if frontendURL == "" { + frontendURL = "https://ssologin.hmac.kr" + } + qrPayload := fmt.Sprintf("%s/approve?ref=%s", frontendURL, pendingRef) + + log.Printf("[QR] Init: PendingRef=%s, URL=%s", pendingRef, qrPayload) + + // Redis에 초기 상태 저장 (5분 만료) + h.RedisService.Set(prefixSession+pendingRef, fmt.Sprintf(`{"status":"%s"}`, statusPending), 5*time.Minute) + + return c.JSON(fiber.Map{ + "qrCode": qrPayload, // 프론트엔드에서 이 텍스트로 QR을 생성하거나, 이미지를 반환 + "pendingRef": pendingRef, + "expiresIn": 300, + }) +} + +// PollQRLogin - Step 2: 웹에서 승인 여부를 폴링합니다. +func (h *AuthHandler) PollQRLogin(c *fiber.Ctx) error { + var req struct { + PendingRef string `json:"pendingRef"` + } + if err := c.BodyParser(&req); err != nil { + return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Invalid body"}) + } + + val, err := h.RedisService.Get(prefixSession + req.PendingRef) + if err != nil || val == "" { + return c.JSON(fiber.Map{"status": "expired"}) + } + + var data map[string]string + json.Unmarshal([]byte(val), &data) + + if data["status"] == statusSuccess { + return c.JSON(fiber.Map{ + "status": "ok", + "sessionJwt": data["jwt"], + }) + } + + return c.JSON(fiber.Map{"status": statusPending}) +} + +// ScanQRLogin - Step 3: 모바일 앱에서 QR 스캔 후 승인할 때 호출합니다. +// (이미 로그인된 세션이 필요함) +func (h *AuthHandler) ScanQRLogin(c *fiber.Ctx) error { + var req struct { + PendingRef string `json:"pendingRef"` + Token string `json:"token"` // 모바일 사용자의 세션 토큰 (검증용) + } + if err := c.BodyParser(&req); err != nil { + return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "Invalid body"}) + } + + log.Printf("[QR] Scan & Approve: PendingRef=%s", req.PendingRef) + + // 1. Redis에서 세션 확인 + val, err := h.RedisService.Get(prefixSession + req.PendingRef) + if err != nil || val == "" { + return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "Session expired or not found"}) + } + + // 2. 모바일 유저의 토큰으로 새 세션 토큰(웹용)을 발행하거나 그대로 전달 + + sessionData, _ := json.Marshal(map[string]string{ + "status": statusSuccess, + "jwt": req.Token, + }) + h.RedisService.Set(prefixSession+req.PendingRef, string(sessionData), 5*time.Minute) + + return c.JSON(fiber.Map{"message": "QR Login Approved"}) +} + // ProxyToDescope (Placeholder) func (h *AuthHandler) ProxyToDescope(c *fiber.Ctx, path string, payload interface{}) error { return c.Status(501).SendString("Descope Proxy Disabled") diff --git a/frontend/lib/core/services/auth_proxy_service.dart b/frontend/lib/core/services/auth_proxy_service.dart index 0fa208d8..c2833446 100644 --- a/frontend/lib/core/services/auth_proxy_service.dart +++ b/frontend/lib/core/services/auth_proxy_service.dart @@ -99,6 +99,51 @@ class AuthProxyService { } } + static Future> initQrLogin() async { + final url = Uri.parse('$_baseUrl/api/v1/auth/qr/init'); + final response = await http.post( + url, + headers: {'Content-Type': 'application/json'}, + ); + + if (response.statusCode == 200) { + return jsonDecode(response.body); + } else { + throw Exception('Failed to init QR login: ${response.body}'); + } + } + + static Future> pollQrStatus(String pendingRef) async { + final url = Uri.parse('$_baseUrl/api/v1/auth/qr/poll'); + final response = await http.post( + url, + headers: {'Content-Type': 'application/json'}, + body: jsonEncode({'pendingRef': pendingRef}), + ); + + if (response.statusCode == 200) { + return jsonDecode(response.body); + } else { + throw Exception('QR Polling failed: ${response.body}'); + } + } + + static Future approveQrLogin(String pendingRef, String token) async { + final url = Uri.parse('$_baseUrl/api/v1/auth/qr/approve'); // Mapping to ScanQRLogin on backend + final response = await http.post( + url, + headers: {'Content-Type': 'application/json'}, + body: jsonEncode({ + 'pendingRef': pendingRef, + 'token': token, + }), + ); + + if (response.statusCode != 200) { + throw Exception('QR Approval failed: ${response.body}'); + } + } + static Future checkAdminAuth(String adminPassword) async { final url = Uri.parse('$_baseUrl/api/v1/admin/check'); try { diff --git a/frontend/lib/features/auth/presentation/approve_qr_screen.dart b/frontend/lib/features/auth/presentation/approve_qr_screen.dart new file mode 100644 index 00000000..eda1ab12 --- /dev/null +++ b/frontend/lib/features/auth/presentation/approve_qr_screen.dart @@ -0,0 +1,117 @@ +import 'package:flutter/material.dart'; +import 'package:descope/descope.dart'; +import 'package:go_router/go_router.dart'; +import '../../../../core/services/auth_proxy_service.dart'; + +class ApproveQrScreen extends StatefulWidget { + final String? pendingRef; + const ApproveQrScreen({super.key, this.pendingRef}); + + @override + State createState() => _ApproveQrScreenState(); +} + +class _ApproveQrScreenState extends State { + bool _isLoading = false; + String? _message; + bool _success = false; + + Future _handleApprove() async { + if (widget.pendingRef == null) return; + + final session = Descope.sessionManager.session; + if (session == null || session.refreshToken.isExpired) { + setState(() => _message = "Please log in on your phone first."); + context.go('/'); // Redirect to login + return; + } + + setState(() { + _isLoading = true; + _message = null; + }); + // jwt 유효성 확인 + try { + await AuthProxyService.approveQrLogin( + widget.pendingRef!, + session.sessionToken.jwt, + ); + setState(() { + _success = true; + _message = "Login Approved! Your browser should now be logged in."; + }); + } catch (e) { + setState(() => _message = "Error: $e"); + } finally { + setState(() => _isLoading = false); + } + } + + @override + Widget build(BuildContext context) { + final isLoggedIn = Descope.sessionManager.session?.refreshToken.isExpired == false; + + return Scaffold( + appBar: AppBar(title: const Text("QR Login Approval")), + body: Center( + child: Padding( + padding: const EdgeInsets.all(24.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.phonelink_lock, size: 80, color: Colors.blue), + const SizedBox(height: 24), + const Text( + "Web Login Request", + style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold), + ), + const SizedBox(height: 16), + Text( + "A computer is trying to log in using this QR code.", + textAlign: TextAlign.center, + style: TextStyle(color: Colors.grey.shade600), + ), + const SizedBox(height: 40), + + if (_message != null) + Padding( + padding: const EdgeInsets.only(bottom: 20), + child: Text( + _message!, + style: TextStyle(color: _success ? Colors.green : Colors.red, fontWeight: FontWeight.bold), + textAlign: TextAlign.center, + ), + ), + + if (!_success) + FilledButton.icon( + onPressed: _isLoading || !isLoggedIn ? null : _handleApprove, + icon: const Icon(Icons.check_circle), + label: const Text("Approve Login"), + style: FilledButton.styleFrom( + minimumSize: const Size.fromHeight(60), + backgroundColor: Colors.blue, + ), + ), + + if (!isLoggedIn && !_success) + Padding( + padding: const EdgeInsets.only(top: 16), + child: TextButton( + onPressed: () => context.go('/'), + child: const Text("Login on this device first"), + ), + ), + + if (_success) + FilledButton( + onPressed: () => context.go('/dashboard'), + child: const Text("Go to My Dashboard"), + ), + ], + ), + ), + ), + ); + } +} diff --git a/frontend/lib/features/auth/presentation/login_screen.dart b/frontend/lib/features/auth/presentation/login_screen.dart index 710e6698..5fb49e47 100644 --- a/frontend/lib/features/auth/presentation/login_screen.dart +++ b/frontend/lib/features/auth/presentation/login_screen.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; @@ -5,6 +6,7 @@ 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'; @@ -27,10 +29,19 @@ class _LoginScreenState extends ConsumerState 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: 2, vsync: this, initialIndex: 1); + _tabController = TabController(length: 3, vsync: this, initialIndex: 1); + _tabController.addListener(_handleTabSelection); // Check for tokens (Path Parameter or Legacy Query Parameter) WidgetsBinding.instance.addPostFrameCallback((_) { @@ -50,6 +61,89 @@ class _LoginScreenState extends ConsumerState }); } + void _handleTabSelection() { + if (_tabController.index == 2 && _qrPendingRef == null) { + _startQrFlow(); + } else if (_tabController.index != 2) { + _stopQrPolling(); + } + } + + Future _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 _verifyToken(String token) async { debugPrint("[Auth] Starting verification for token: $token"); try { @@ -81,6 +175,7 @@ class _LoginScreenState extends ConsumerState @override void dispose() { + _stopQrPolling(); _tabController.dispose(); _emailController.dispose(); _passwordController.dispose(); @@ -192,6 +287,32 @@ class _LoginScreenState extends ConsumerState 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) + ); + final session = DescopeSession.fromJwt(jwt, jwt, dummyUser); + Descope.sessionManager.manageSession(session); + if (mounted) { Navigator.of(context).pop(); // Close Polling Dialog _onLoginSuccess(jwt); @@ -287,11 +408,12 @@ class _LoginScreenState extends ConsumerState if (WebAuthIntegration.isPopup()) { WebAuthIntegration.sendLoginSuccess(token); _showError("Login Successful! You can close this window."); - } else if (_redirectUrl != null) { + } else if (_redirectUrl != null && _redirectUrl!.isNotEmpty) { final target = "$_redirectUrl?token=$token"; launchUrlString(target, webOnlyWindowName: '_self'); } else { - _showError("Login Successful (Token Received)"); + // Standalone mode: Go to dashboard to act as an auth platform + if (mounted) context.go('/dashboard'); } } @@ -333,12 +455,13 @@ class _LoginScreenState extends ConsumerState tabs: const [ Tab(text: "Email"), Tab(text: "Phone (SMS)"), + Tab(text: "QR"), ], ), const SizedBox(height: 24), SizedBox( - height: 300, + height: 350, child: TabBarView( controller: _tabController, children: [ @@ -402,6 +525,53 @@ class _LoginScreenState extends ConsumerState ), ], ), + + // 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 + ? "Remaining Time: ${_formatTime(_qrRemainingSeconds)}" + : "QR Code Expired", + style: TextStyle( + color: _qrRemainingSeconds > 30 ? Colors.blue : Colors.red, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 8), + const Text( + "Scan with your mobile app", + style: TextStyle(color: Colors.grey, fontSize: 12), + ), + TextButton( + onPressed: _startQrFlow, + child: const Text("Refresh QR") + ), + ], + ) + else + const Text("Failed to load QR code."), + ], + ), ], ), ), diff --git a/frontend/lib/main.dart b/frontend/lib/main.dart index 89ece320..81e37ab6 100644 --- a/frontend/lib/main.dart +++ b/frontend/lib/main.dart @@ -7,6 +7,7 @@ import 'package:go_router/go_router.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:flutter_web_plugins/url_strategy.dart'; import 'features/auth/presentation/login_screen.dart'; +import 'features/auth/presentation/approve_qr_screen.dart'; import 'features/dashboard/presentation/dashboard_screen.dart'; import 'features/admin/presentation/user_management_screen.dart'; import 'core/services/auth_proxy_service.dart'; @@ -79,6 +80,14 @@ final _router = GoRouter( return LoginScreen(verificationToken: token); }, ), + GoRoute( + path: '/approve', + builder: (context, state) { + final ref = state.uri.queryParameters['ref']; + _routerLogger.info("Navigating to /approve with ref: $ref"); + return ApproveQrScreen(pendingRef: ref); + }, + ), GoRoute( path: '/dashboard', builder: (context, state) { @@ -98,7 +107,7 @@ final _router = GoRouter( final isLoggedIn = Descope.sessionManager.session?.refreshToken.isExpired == false; final path = state.uri.path; - final isLoggingIn = path == '/' || path.startsWith('/verify/') || path.startsWith('/admin/'); + final isLoggingIn = path == '/' || path.startsWith('/verify/') || path.startsWith('/admin/') || path == '/approve'; _routerLogger.fine("Redirect check - Path: $path, IsLoggedIn: $isLoggedIn"); diff --git a/frontend/pubspec.yaml b/frontend/pubspec.yaml index 5dedbd77..1f13a129 100644 --- a/frontend/pubspec.yaml +++ b/frontend/pubspec.yaml @@ -43,6 +43,7 @@ dependencies: url_launcher: ^6.3.2 logging: ^1.2.0 logger: ^2.0.0 + qr_flutter: ^4.1.0 dev_dependencies: flutter_test: From ebfd60f81ad239975b9d50e77a714234f6e4487f Mon Sep 17 00:00:00 2001 From: chan Date: Mon, 19 Jan 2026 11:16:01 +0900 Subject: [PATCH 2/4] =?UTF-8?q?input=20=EB=A0=88=EC=9D=B4=EC=95=84?= =?UTF-8?q?=EC=9B=83=20,=20=ED=95=9C=EA=B8=80=20=EB=B2=88=EC=97=AD=20=20?= =?UTF-8?q?=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth/presentation/login_screen.dart | 293 +++++++++--------- 1 file changed, 154 insertions(+), 139 deletions(-) diff --git a/frontend/lib/features/auth/presentation/login_screen.dart b/frontend/lib/features/auth/presentation/login_screen.dart index 5fb49e47..01ccb57e 100644 --- a/frontend/lib/features/auth/presentation/login_screen.dart +++ b/frontend/lib/features/auth/presentation/login_screen.dart @@ -432,152 +432,167 @@ class _LoginScreenState extends ConsumerState @override Widget build(BuildContext context) { return Scaffold( - body: 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: "Email"), - Tab(text: "Phone (SMS)"), - Tab(text: "QR"), - ], - ), - const SizedBox(height: 24), - - SizedBox( - height: 350, - child: TabBarView( - controller: _tabController, - children: [ - // Email Form - Column( - children: [ - TextField( - controller: _emailController, - decoration: const InputDecoration( - labelText: "Email", - border: OutlineInputBorder(), - prefixIcon: Icon(Icons.email_outlined), - ), + 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, ), - const SizedBox(height: 16), - TextField( - controller: _passwordController, - obscureText: true, - decoration: const InputDecoration( - labelText: "Password (Optional)", - 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("Sign In / Send Link"), - ), - ], - ), + textAlign: TextAlign.center, + ), + const SizedBox(height: 40), - // Phone Form - Column( - children: [ - TextField( - controller: _phoneController, - decoration: const InputDecoration( - labelText: "Phone Number", - hintText: "010-1234-5678", - border: OutlineInputBorder(), - prefixIcon: Icon(Icons.phone_android), + 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("로그인 / 링크 전송"), + ), + ], + ), ), - ), - const SizedBox(height: 24), - FilledButton( - onPressed: _handleSmsLogin, - style: FilledButton.styleFrom( - minimumSize: const Size.fromHeight(50), - ), - child: const Text("Send Login Link"), - ), - const SizedBox(height: 16), - const Text( - "We will send a login link to your phone via SMS.", - 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, - ), + // 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, + ), + ], ), - const SizedBox(height: 12), - Text( - _qrRemainingSeconds > 0 - ? "Remaining Time: ${_formatTime(_qrRemainingSeconds)}" - : "QR Code Expired", - style: TextStyle( - color: _qrRemainingSeconds > 30 ? Colors.blue : Colors.red, - fontWeight: FontWeight.bold, - ), - ), - const SizedBox(height: 8), - const Text( - "Scan with your mobile app", - style: TextStyle(color: Colors.grey, fontSize: 12), - ), - TextButton( - onPressed: _startQrFlow, - child: const Text("Refresh QR") - ), - ], - ) - else - const Text("Failed to load QR code."), - ], - ), - ], + ), + + // 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 코드를 불러오지 못했습니다."), + ], + ), + ], + ), + ), + ], + ), ), ), - ], - ), - ), + ), + ); + }, ), ); } From 27b8ff2ac1cfc2d67a919459581715b95a22d351 Mon Sep 17 00:00:00 2001 From: chan Date: Mon, 19 Jan 2026 15:09:07 +0900 Subject: [PATCH 3/4] =?UTF-8?q?=EB=8C=80=EC=8B=9C=EB=B3=B4=EB=93=9C=20qr?= =?UTF-8?q?=20=ED=8E=98=EC=9D=B4=EC=A7=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../android/app/src/main/AndroidManifest.xml | 1 + frontend/ios/Runner/Info.plist | 2 + .../lib/core/notifiers/auth_notifier.dart | 9 ++ .../lib/core/services/auth_proxy_service.dart | 6 +- .../auth/presentation/approve_qr_screen.dart | 5 + .../auth/presentation/login_screen.dart | 68 ++++++++-- .../presentation/login_success_screen.dart | 63 +++++++++ .../auth/presentation/qr_scan_screen.dart | 122 ++++++++++++++++++ .../presentation/dashboard_screen.dart | 72 +++++++++-- frontend/lib/main.dart | 10 ++ frontend/pubspec.yaml | 1 + 11 files changed, 338 insertions(+), 21 deletions(-) create mode 100644 frontend/lib/core/notifiers/auth_notifier.dart create mode 100644 frontend/lib/features/auth/presentation/login_success_screen.dart create mode 100644 frontend/lib/features/auth/presentation/qr_scan_screen.dart diff --git a/frontend/android/app/src/main/AndroidManifest.xml b/frontend/android/app/src/main/AndroidManifest.xml index 0fd500e3..e8d342e9 100644 --- a/frontend/android/app/src/main/AndroidManifest.xml +++ b/frontend/android/app/src/main/AndroidManifest.xml @@ -1,4 +1,5 @@ + CADisableMinimumFrameDurationOnPhone + NSCameraUsageDescription + This app requires camera access to scan QR codes for login. UIApplicationSupportsIndirectInputEvents diff --git a/frontend/lib/core/notifiers/auth_notifier.dart b/frontend/lib/core/notifiers/auth_notifier.dart new file mode 100644 index 00000000..24282ca5 --- /dev/null +++ b/frontend/lib/core/notifiers/auth_notifier.dart @@ -0,0 +1,9 @@ +import 'package:flutter/foundation.dart'; + +class AuthNotifier extends ChangeNotifier { + static final AuthNotifier instance = AuthNotifier(); + + void notify() { + notifyListeners(); + } +} diff --git a/frontend/lib/core/services/auth_proxy_service.dart b/frontend/lib/core/services/auth_proxy_service.dart index c2833446..85361e62 100644 --- a/frontend/lib/core/services/auth_proxy_service.dart +++ b/frontend/lib/core/services/auth_proxy_service.dart @@ -48,7 +48,7 @@ class AuthProxyService { } } - static Future verifyMagicLink(String token) async { + static Future> verifyMagicLink(String token) async { final url = Uri.parse('$_baseUrl/api/v1/auth/magic-link/verify'); final response = await http.post( @@ -59,7 +59,9 @@ class AuthProxyService { }), ); - if (response.statusCode != 200) { + if (response.statusCode == 200) { + return jsonDecode(response.body); + } else { throw Exception('Verification failed: ${response.body}'); } } diff --git a/frontend/lib/features/auth/presentation/approve_qr_screen.dart b/frontend/lib/features/auth/presentation/approve_qr_screen.dart index eda1ab12..c60a31be 100644 --- a/frontend/lib/features/auth/presentation/approve_qr_screen.dart +++ b/frontend/lib/features/auth/presentation/approve_qr_screen.dart @@ -40,6 +40,11 @@ class _ApproveQrScreenState extends State { _success = true; _message = "Login Approved! Your browser should now be logged in."; }); + + // Automatically go to dashboard after a short delay + Future.delayed(const Duration(seconds: 1), () { + if (mounted) context.go('/dashboard'); + }); } catch (e) { setState(() => _message = "Error: $e"); } finally { diff --git a/frontend/lib/features/auth/presentation/login_screen.dart b/frontend/lib/features/auth/presentation/login_screen.dart index 01ccb57e..7c76a480 100644 --- a/frontend/lib/features/auth/presentation/login_screen.dart +++ b/frontend/lib/features/auth/presentation/login_screen.dart @@ -10,6 +10,7 @@ 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'; +import '../../../core/notifiers/auth_notifier.dart'; class LoginScreen extends ConsumerStatefulWidget { final String? verificationToken; @@ -122,7 +123,33 @@ class _LoginScreenState extends ConsumerState if (res['status'] == 'ok' && res['sessionJwt'] != null) { timer.cancel(); _qrCountdownTimer?.cancel(); - _onLoginSuccess(res['sessionJwt']); + + final jwt = res['sessionJwt']; + // Create Dummy User & Session for Descope SDK + 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) + ); + final session = DescopeSession.fromJwt(jwt, jwt, dummyUser); + Descope.sessionManager.manageSession(session); + + _onLoginSuccess(jwt); } } catch (e) { debugPrint("[QR] Polling error: $e"); @@ -148,11 +175,20 @@ class _LoginScreenState extends ConsumerState debugPrint("[Auth] Starting verification for token: $token"); try { // Use Backend to verify the token (Backend-Driven Flow) - await AuthProxyService.verifyMagicLink(token); + final res = await AuthProxyService.verifyMagicLink(token); + final jwt = res['token']; debugPrint("[Auth] Verification successful for token: $token"); - if (mounted) { - _showSuccessDialog(); + if (jwt != null && mounted) { + // Create Dummy User & Session for Descope SDK to log in this tab + final dummyUser = DescopeUser( + 'unknown', [], 0, 'User', null, '', false, '', false, {}, '', '', '', false, 'enabled', [], [], [], + ); + final session = DescopeSession.fromJwt(jwt, jwt, dummyUser); + Descope.sessionManager.manageSession(session); + + // Notify and Go to Dashboard + _onLoginSuccess(jwt); } } catch (e) { debugPrint("[Auth] Verification FAILED for token: $token. Error: $e"); @@ -405,15 +441,25 @@ class _LoginScreenState extends ConsumerState 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) { + // 1. Handle Redirect Flow (Redirect to another app) + 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'); + return; + } + + // 2. Handle Popup Flow (Send message to opener) + if (WebAuthIntegration.isPopup()) { + WebAuthIntegration.sendLoginSuccess(token); + // If this window was truly a popup for another app, it should close now. + // If it's still here, we allow it to fall through to the dashboard. + } + + // 3. Standalone mode: Go to dashboard + // We call notify() to update the router's state, and go() to ensure navigation. + AuthNotifier.instance.notify(); + if (mounted) { + context.go('/dashboard'); } } diff --git a/frontend/lib/features/auth/presentation/login_success_screen.dart b/frontend/lib/features/auth/presentation/login_success_screen.dart new file mode 100644 index 00000000..7ca7293a --- /dev/null +++ b/frontend/lib/features/auth/presentation/login_success_screen.dart @@ -0,0 +1,63 @@ +import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; +import 'package:google_fonts/google_fonts.dart'; + +class LoginSuccessScreen extends StatelessWidget { + const LoginSuccessScreen({super.key}); + + @override + Widget build(BuildContext context) { + return Scaffold( + body: Center( + child: Padding( + padding: const EdgeInsets.all(24.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.check_circle_outline, size: 80, color: Colors.green), + const SizedBox(height: 24), + Text( + "로그인 완료", + style: GoogleFonts.outfit( + fontSize: 32, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 16), + const Text( + "성공적으로 로그인되었습니다.", + textAlign: TextAlign.center, + style: TextStyle(color: Colors.grey, fontSize: 16), + ), + const SizedBox(height: 48), + + // 이 버튼이 QR 카메라를 켜는 버튼입니다. + FilledButton.icon( + onPressed: () { + context.push('/qr-scan'); + }, + icon: const Icon(Icons.camera_alt, size: 28), + label: const Text("QR 인증 (카메라 켜기)"), + style: FilledButton.styleFrom( + minimumSize: const Size.fromHeight(80), // 버튼 높이를 더 크게 + backgroundColor: Colors.blue.shade700, + textStyle: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + ), + ), + ), + const SizedBox(height: 24), + TextButton( + onPressed: () { + context.go('/dashboard'); + }, + child: const Text("나중에 하기 (대시보드로 이동)", style: TextStyle(color: Colors.grey)), + ), + ], + ), + ), + ), + ); + } +} diff --git a/frontend/lib/features/auth/presentation/qr_scan_screen.dart b/frontend/lib/features/auth/presentation/qr_scan_screen.dart new file mode 100644 index 00000000..d750808d --- /dev/null +++ b/frontend/lib/features/auth/presentation/qr_scan_screen.dart @@ -0,0 +1,122 @@ +import 'package:flutter/material.dart'; +import 'package:mobile_scanner/mobile_scanner.dart'; +import 'package:go_router/go_router.dart'; +import 'package:logging/logging.dart'; +import 'package:descope/descope.dart'; +import '../../../core/services/auth_proxy_service.dart'; + +class QRScanScreen extends StatefulWidget { + const QRScanScreen({super.key}); + + @override + State createState() => _QRScanScreenState(); +} + +class _QRScanScreenState extends State { + final _log = Logger('QRScanScreen'); + final MobileScannerController controller = MobileScannerController( + detectionSpeed: DetectionSpeed.noDuplicates, + ); + bool _isScanned = false; + + @override + void dispose() { + controller.dispose(); + super.dispose(); + } + + Future _onDetect(BarcodeCapture capture) async { + if (_isScanned) return; + + final List barcodes = capture.barcodes; + for (final barcode in barcodes) { + if (barcode.rawValue != null) { + _isScanned = true; + String qrData = barcode.rawValue!; + String pendingRef = qrData; + + // URL 형식이라면 'ref' 파라미터 추출 시도 + if (qrData.startsWith('http')) { + try { + final uri = Uri.parse(qrData); + if (uri.queryParameters.containsKey('ref')) { + pendingRef = uri.queryParameters['ref']!; + } + } catch (e) { + _log.warning('Failed to parse QR URL: $qrData', e); + } + } + + _log.info('QR Code detected raw: $qrData, ref: $pendingRef'); + + final sessionToken = Descope.sessionManager.session?.sessionToken.jwt; + if (sessionToken == null) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('로그인이 필요합니다.'), backgroundColor: Colors.red), + ); + context.pop(); + } + return; + } + + try { + // Call backend API to approve login with clean ref + await AuthProxyService.approveQrLogin(pendingRef, sessionToken); + + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('로그인 승인 완료!'), + backgroundColor: Colors.green, + ), + ); + // Wait a bit and go back + await Future.delayed(const Duration(milliseconds: 500)); + if (mounted) context.pop(); + } + } catch (e) { + _log.severe("QR Approval Failed", e); + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('승인 실패: $e'), backgroundColor: Colors.red), + ); + // Allow rescanning after a delay + await Future.delayed(const Duration(seconds: 2)); + _isScanned = false; + } + } + break; + } + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Scan QR Code'), + leading: IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () => context.pop(), + ), + ), + body: MobileScanner( + controller: controller, + onDetect: _onDetect, + errorBuilder: (context, error, child) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.error, color: Colors.red, size: 50), + const SizedBox(height: 10), + Text('Camera Error: ${error.errorCode}'), + ], + ), + ); + }, + ), + ); + } +} \ No newline at end of file diff --git a/frontend/lib/features/dashboard/presentation/dashboard_screen.dart b/frontend/lib/features/dashboard/presentation/dashboard_screen.dart index f429b836..e125b046 100644 --- a/frontend/lib/features/dashboard/presentation/dashboard_screen.dart +++ b/frontend/lib/features/dashboard/presentation/dashboard_screen.dart @@ -2,13 +2,19 @@ import 'package:flutter/material.dart'; import 'package:descope/descope.dart'; import 'package:go_router/go_router.dart'; import 'package:google_fonts/google_fonts.dart'; +import '../../../../core/notifiers/auth_notifier.dart'; class DashboardScreen extends StatelessWidget { const DashboardScreen({super.key}); Future _logout(BuildContext context) async { + // ignore: use_build_context_synchronously Descope.sessionManager.clearSession(); - if (context.mounted) context.go('/'); + AuthNotifier.instance.notify(); + } + + void _onScanQR(BuildContext context) { + context.push('/scan'); } @override @@ -17,8 +23,12 @@ class DashboardScreen extends StatelessWidget { final userName = user?.name ?? user?.email ?? user?.phone ?? 'User'; return Scaffold( + backgroundColor: Colors.grey[50], appBar: AppBar( title: Text('Baron Launcher', style: GoogleFonts.outfit(fontWeight: FontWeight.bold)), + elevation: 0, + backgroundColor: Colors.white, + foregroundColor: Colors.black, actions: [ IconButton( icon: const Icon(Icons.logout), @@ -28,13 +38,59 @@ class DashboardScreen extends StatelessWidget { ], ), body: Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Text('Dashboard Loaded Successfully', style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold)), - const SizedBox(height: 20), - Text('Welcome, $userName'), - ], + child: Padding( + padding: const EdgeInsets.all(24.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.check_circle_outline, size: 80, color: Colors.green), + const SizedBox(height: 24), + Text( + '로그인 성공!', + style: GoogleFonts.notoSans( + fontSize: 28, + fontWeight: FontWeight.bold, + color: const Color(0xFF1A1F2C), + ), + ), + const SizedBox(height: 8), + Text( + '반갑습니다, $userName님', + style: GoogleFonts.notoSans( + fontSize: 16, + color: Colors.grey[600], + ), + ), + const SizedBox(height: 48), + + // QR Camera Button + SizedBox( + width: double.infinity, + height: 56, + child: ElevatedButton.icon( + onPressed: () => _onScanQR(context), + icon: const Icon(Icons.qr_code_scanner, size: 28), + label: Text( + 'QR 스캔하기', + style: GoogleFonts.notoSans(fontSize: 18, fontWeight: FontWeight.w600), + ), + style: ElevatedButton.styleFrom( + backgroundColor: const Color(0xFF1A1F2C), + foregroundColor: Colors.white, + elevation: 2, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + ), + ), + ), + ), + const SizedBox(height: 16), + const Text( + 'PC 화면의 QR 코드를 스캔하여 로그인하세요.', + style: TextStyle(color: Colors.grey, fontSize: 13), + ), + ], + ), ), ), ); diff --git a/frontend/lib/main.dart b/frontend/lib/main.dart index 81e37ab6..f235ba21 100644 --- a/frontend/lib/main.dart +++ b/frontend/lib/main.dart @@ -8,10 +8,12 @@ import 'package:google_fonts/google_fonts.dart'; import 'package:flutter_web_plugins/url_strategy.dart'; import 'features/auth/presentation/login_screen.dart'; import 'features/auth/presentation/approve_qr_screen.dart'; +import 'features/auth/presentation/qr_scan_screen.dart'; import 'features/dashboard/presentation/dashboard_screen.dart'; import 'features/admin/presentation/user_management_screen.dart'; import 'core/services/auth_proxy_service.dart'; import 'core/services/logger_service.dart'; +import 'core/notifiers/auth_notifier.dart'; import 'package:logging/logging.dart'; final _log = Logger('Main'); @@ -64,6 +66,7 @@ final _routerLogger = Logger('Router'); final _router = GoRouter( initialLocation: '/', debugLogDiagnostics: true, // Enable diagnostic logs + refreshListenable: AuthNotifier.instance, routes: [ GoRoute( path: '/', @@ -95,6 +98,13 @@ final _router = GoRouter( return const DashboardScreen(); }, ), + GoRoute( + path: '/scan', + builder: (context, state) { + _routerLogger.info("Navigating to /scan"); + return const QRScanScreen(); + }, + ), GoRoute( path: '/admin/users', builder: (context, state) { diff --git a/frontend/pubspec.yaml b/frontend/pubspec.yaml index 1f13a129..3217012f 100644 --- a/frontend/pubspec.yaml +++ b/frontend/pubspec.yaml @@ -44,6 +44,7 @@ dependencies: logging: ^1.2.0 logger: ^2.0.0 qr_flutter: ^4.1.0 + mobile_scanner: ^6.0.0 dev_dependencies: flutter_test: From 3c41c0dc62b7841788206b7ae8bbfaab1ccf4976 Mon Sep 17 00:00:00 2001 From: chan Date: Mon, 19 Jan 2026 17:04:48 +0900 Subject: [PATCH 4/4] =?UTF-8?q?aws=20ses=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.sample | 6 + backend/go.mod | 15 ++ backend/go.sum | 30 +++ backend/internal/domain/email_models.go | 6 + backend/internal/handler/auth_handler.go | 46 +++- backend/internal/service/ses_service.go | 79 ++++++ .../auth/presentation/login_screen.dart | 255 ++++++------------ .../presentation/dashboard_screen.dart | 19 +- 8 files changed, 268 insertions(+), 188 deletions(-) create mode 100644 backend/internal/domain/email_models.go create mode 100644 backend/internal/service/ses_service.go diff --git a/.env.sample b/.env.sample index 27dd2650..783920b6 100644 --- a/.env.sample +++ b/.env.sample @@ -34,4 +34,10 @@ NAVER_CLOUD_SECRET_KEY=ncp_iam_... NAVER_CLOUD_SERVICE_ID=ncp:sms:kr:...:... NAVER_SENDER_PHONE_NUMBER=... +# --- AWS SES Configuration --- +AWS_REGION=ap-northeast-2 +AWS_ACCESS_KEY_ID=... +AWS_SECRET_ACCESS_KEY=... +AWS_SES_SENDER=no-reply@baron.co.kr + ADMIN_PASSWORD=admin \ No newline at end of file diff --git a/backend/go.mod b/backend/go.mod index 23af349f..bfcd6854 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -12,6 +12,21 @@ require ( require ( github.com/ClickHouse/ch-go v0.69.0 // indirect github.com/andybalholm/brotli v1.2.0 // indirect + github.com/aws/aws-sdk-go-v2 v1.41.1 // indirect + github.com/aws/aws-sdk-go-v2/config v1.32.7 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.19.7 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 // indirect + github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17 // indirect + github.com/aws/aws-sdk-go-v2/service/ses v1.34.18 // indirect + github.com/aws/aws-sdk-go-v2/service/signin v1.0.5 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.30.9 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.41.6 // indirect + github.com/aws/smithy-go v1.24.0 // indirect github.com/bwmarrin/snowflake v0.3.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/decred/dcrd/dcrec/secp256k1/v4 v4.4.0 // indirect diff --git a/backend/go.sum b/backend/go.sum index f23f6c51..5b47a91c 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -4,6 +4,36 @@ github.com/ClickHouse/clickhouse-go/v2 v2.42.0 h1:MdujEfIrpXesQUH0k0AnuVtJQXk6RZ github.com/ClickHouse/clickhouse-go/v2 v2.42.0/go.mod h1:riWnuo4YMVdajYll0q6FzRBomdyCrXyFY3VXeXczA8s= github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ= github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= +github.com/aws/aws-sdk-go-v2 v1.41.1 h1:ABlyEARCDLN034NhxlRUSZr4l71mh+T5KAeGh6cerhU= +github.com/aws/aws-sdk-go-v2 v1.41.1/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0= +github.com/aws/aws-sdk-go-v2/config v1.32.7 h1:vxUyWGUwmkQ2g19n7JY/9YL8MfAIl7bTesIUykECXmY= +github.com/aws/aws-sdk-go-v2/config v1.32.7/go.mod h1:2/Qm5vKUU/r7Y+zUk/Ptt2MDAEKAfUtKc1+3U1Mo3oY= +github.com/aws/aws-sdk-go-v2/credentials v1.19.7 h1:tHK47VqqtJxOymRrNtUXN5SP/zUTvZKeLx4tH6PGQc8= +github.com/aws/aws-sdk-go-v2/credentials v1.19.7/go.mod h1:qOZk8sPDrxhf+4Wf4oT2urYJrYt3RejHSzgAquYeppw= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17 h1:I0GyV8wiYrP8XpA70g1HBcQO1JlQxCMTW9npl5UbDHY= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17/go.mod h1:tyw7BOl5bBe/oqvoIeECFJjMdzXoa/dfVz3QQ5lgHGA= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 h1:xOLELNKGp2vsiteLsvLPwxC+mYmO6OZ8PYgiuPJzF8U= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17/go.mod h1:5M5CI3D12dNOtH3/mk6minaRwI2/37ifCURZISxA/IQ= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 h1:WWLqlh79iO48yLkj1v3ISRNiv+3KdQoZ6JWyfcsyQik= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17/go.mod h1:EhG22vHRrvF8oXSTYStZhJc1aUgKtnJe+aOiFEV90cM= +github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 h1:WKuaxf++XKWlHWu9ECbMlha8WOEGm0OUEZqm4K/Gcfk= +github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4/go.mod h1:ZWy7j6v1vWGmPReu0iSGvRiise4YI5SkR3OHKTZ6Wuc= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 h1:0ryTNEdJbzUCEWkVXEXoqlXV72J5keC1GvILMOuD00E= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4/go.mod h1:HQ4qwNZh32C3CBeO6iJLQlgtMzqeG17ziAA/3KDJFow= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17 h1:RuNSMoozM8oXlgLG/n6WLaFGoea7/CddrCfIiSA+xdY= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17/go.mod h1:F2xxQ9TZz5gDWsclCtPQscGpP0VUOc8RqgFM3vDENmU= +github.com/aws/aws-sdk-go-v2/service/ses v1.34.18 h1:2Lnd3ZNTyWpFJJM55y0mP0aESovm+vFuFEwLijucUL8= +github.com/aws/aws-sdk-go-v2/service/ses v1.34.18/go.mod h1:BLwHw6wdkA6NfnW/cFaVcvpwdIXHLAkpe6nsLF9BVww= +github.com/aws/aws-sdk-go-v2/service/signin v1.0.5 h1:VrhDvQib/i0lxvr3zqlUwLwJP4fpmpyD9wYG1vfSu+Y= +github.com/aws/aws-sdk-go-v2/service/signin v1.0.5/go.mod h1:k029+U8SY30/3/ras4G/Fnv/b88N4mAfliNn08Dem4M= +github.com/aws/aws-sdk-go-v2/service/sso v1.30.9 h1:v6EiMvhEYBoHABfbGB4alOYmCIrcgyPPiBE1wZAEbqk= +github.com/aws/aws-sdk-go-v2/service/sso v1.30.9/go.mod h1:yifAsgBxgJWn3ggx70A3urX2AN49Y5sJTD1UQFlfqBw= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13 h1:gd84Omyu9JLriJVCbGApcLzVR3XtmC4ZDPcAI6Ftvds= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13/go.mod h1:sTGThjphYE4Ohw8vJiRStAcu3rbjtXRsdNB0TvZ5wwo= +github.com/aws/aws-sdk-go-v2/service/sts v1.41.6 h1:5fFjR/ToSOzB2OQ/XqWpZBmNvmP/pJ1jOWYlFDJTjRQ= +github.com/aws/aws-sdk-go-v2/service/sts v1.41.6/go.mod h1:qgFDZQSD/Kys7nJnVqYlWKnh0SSdMjAi0uSwON4wgYQ= +github.com/aws/smithy-go v1.24.0 h1:LpilSUItNPFr1eY85RYgTIg5eIEPtvFbskaFcmmIUnk= +github.com/aws/smithy-go v1.24.0/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0= github.com/bwmarrin/snowflake v0.3.0 h1:xm67bEhkKh6ij1790JB83OujPR5CzNe8QuQqAgISZN0= github.com/bwmarrin/snowflake v0.3.0/go.mod h1:NdZxfVWX+oR6y2K0o6qAYv6gIOP9rjG0/E9WsDpxqwE= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= diff --git a/backend/internal/domain/email_models.go b/backend/internal/domain/email_models.go new file mode 100644 index 00000000..f6ec18e7 --- /dev/null +++ b/backend/internal/domain/email_models.go @@ -0,0 +1,6 @@ +package domain + +// EmailService defines the interface for sending emails. +type EmailService interface { + SendEmail(to, subject, body string) error +} diff --git a/backend/internal/handler/auth_handler.go b/backend/internal/handler/auth_handler.go index ca220a1e..5b8700d2 100644 --- a/backend/internal/handler/auth_handler.go +++ b/backend/internal/handler/auth_handler.go @@ -35,6 +35,7 @@ const ( type AuthHandler struct { ProjectID string SmsService domain.SmsService + EmailService domain.EmailService RedisService *service.RedisService DescopeClient *client.DescopeClient } @@ -71,6 +72,7 @@ func NewAuthHandler() *AuthHandler { return &AuthHandler{ ProjectID: projectID, SmsService: service.NewSmsService(), + EmailService: service.NewEmailService(), RedisService: redisService, DescopeClient: descopeClient, } @@ -143,24 +145,52 @@ func (h *AuthHandler) InitEnchantedLink(c *fiber.Ctx) error { h.RedisService.Set(prefixSession+pendingRef, fmt.Sprintf(`{"status":"%s"}`, statusPending), defaultExpiration) h.RedisService.Set(prefixToken+token, fmt.Sprintf(`{"pendingRef":"%s","loginId":"%s"}`, pendingRef, loginID), defaultExpiration) - // Send SMS + // Generate Link frontendURL := os.Getenv("FRONTEND_URL") if frontendURL == "" { frontendURL = "http://ssologin.hmac.kr" } link := fmt.Sprintf("%s/verify/%s", frontendURL, token) - content := fmt.Sprintf("[Baron SSO] 로그인 링크: %s", link) - log.Printf("[Enchanted] Sending SMS to %s via Naver Cloud", loginID) + // Route based on LoginID type + if strings.Contains(loginID, "@") { + // Send Email + if h.EmailService == nil { + log.Printf("[Enchanted] Email Service not configured") + return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Email service not configured"}) + } - if err := h.SmsService.SendSms(loginID, content); err != nil { - log.Printf("[Enchanted] SMS Failed: %v", err) - return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Failed to send SMS"}) + subject := "[Baron SSO] 로그인 링크" + body := fmt.Sprintf(` +
+

Baron SSO 로그인

+

안녕하세요,

+

아래 버튼을 클릭하여 로그인을 완료해 주세요. 이 링크는 5분 동안 유효합니다.

+ +

만약 본인이 요청하지 않았다면 이 메일을 무시하셔도 됩니다.

+
+ `, link) + + log.Printf("[Enchanted] Sending Email to %s via AWS SES", loginID) + if err := h.EmailService.SendEmail(loginID, subject, body); err != nil { + log.Printf("[Enchanted] Email Failed: %v", err) + return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Failed to send Email"}) + } + } else { + // Send SMS + content := fmt.Sprintf("[Baron SSO] 로그인 링크: %s", link) + log.Printf("[Enchanted] Sending SMS to %s via Naver Cloud", loginID) + + if err := h.SmsService.SendSms(loginID, content); err != nil { + log.Printf("[Enchanted] SMS Failed: %v", err) + return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": "Failed to send SMS"}) + } } - log.Printf("[Enchanted] SMS sent successfully to %s", loginID) return c.JSON(fiber.Map{ - "linkId": "SMS Sent", + "linkId": "Sent", "pendingRef": pendingRef, "maskedEmail": loginID, }) diff --git a/backend/internal/service/ses_service.go b/backend/internal/service/ses_service.go new file mode 100644 index 00000000..5eb11660 --- /dev/null +++ b/backend/internal/service/ses_service.go @@ -0,0 +1,79 @@ +package service + +import ( + "context" + "fmt" + "log" + "os" + + "baron-sso-backend/internal/domain" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/credentials" + "github.com/aws/aws-sdk-go-v2/service/ses" + "github.com/aws/aws-sdk-go-v2/service/ses/types" +) + +type SesServiceImpl struct { + client *ses.Client + sender string +} + +func NewEmailService() domain.EmailService { + region := os.Getenv("AWS_REGION") + accessKey := os.Getenv("AWS_ACCESS_KEY_ID") + secretKey := os.Getenv("AWS_SECRET_ACCESS_KEY") + sender := os.Getenv("AWS_SES_SENDER") + + if region == "" || accessKey == "" || secretKey == "" { + log.Println("[EmailService] AWS configuration missing, email service will not work") + return nil + } + + cfg, err := config.LoadDefaultConfig(context.TODO(), + config.WithRegion(region), + config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKey, secretKey, "")), + ) + if err != nil { + log.Printf("[EmailService] Failed to load AWS config: %v", err) + return nil + } + + return &SesServiceImpl{ + client: ses.NewFromConfig(cfg), + sender: sender, + } +} + +func (s *SesServiceImpl) SendEmail(to, subject, body string) error { + if s == nil || s.client == nil { + return fmt.Errorf("email service not initialized") + } + + input := &ses.SendEmailInput{ + Destination: &types.Destination{ + ToAddresses: []string{to}, + }, + Message: &types.Message{ + Body: &types.Body{ + Html: &types.Content{ + Charset: aws.String("UTF-8"), + Data: aws.String(body), + }, + }, + Subject: &types.Content{ + Charset: aws.String("UTF-8"), + Data: aws.String(subject), + }, + }, + Source: aws.String(s.sender), + } + + _, err := s.client.SendEmail(context.TODO(), input) + if err != nil { + log.Printf("[EmailService] Failed to send email to %s: %v", to, err) + } else { + log.Printf("[EmailService] Email sent successfully to %s", to) + } + return err +} diff --git a/frontend/lib/features/auth/presentation/login_screen.dart b/frontend/lib/features/auth/presentation/login_screen.dart index 7c76a480..bd805a65 100644 --- a/frontend/lib/features/auth/presentation/login_screen.dart +++ b/frontend/lib/features/auth/presentation/login_screen.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; @@ -23,10 +24,8 @@ class LoginScreen extends ConsumerStatefulWidget { class _LoginScreenState extends ConsumerState with SingleTickerProviderStateMixin { late TabController _tabController; - final TextEditingController _emailController = TextEditingController(); - final TextEditingController _passwordController = TextEditingController(); - final TextEditingController _phoneController = TextEditingController(); - final TextEditingController _smsCodeController = TextEditingController(); + final TextEditingController _idController = TextEditingController(); + final TextEditingController _smsCodeController = TextEditingController(); // Keep if needed for verification inputs later? Actually not used in link flow. bool _smsSent = false; String? _redirectUrl; @@ -41,7 +40,7 @@ class _LoginScreenState extends ConsumerState @override void initState() { super.initState(); - _tabController = TabController(length: 3, vsync: this, initialIndex: 1); + _tabController = TabController(length: 2, vsync: this); _tabController.addListener(_handleTabSelection); // Check for tokens (Path Parameter or Legacy Query Parameter) @@ -62,10 +61,26 @@ class _LoginScreenState extends ConsumerState }); } + // Helper to decode JWT and get loginId + String _getLoginIdFromJwt(String jwt) { + try { + final parts = jwt.split('.'); + if (parts.length != 3) return 'User'; + + final payload = utf8.decode(base64Url.decode(base64Url.normalize(parts[1]))); + final data = json.decode(payload); + // Descope tokens usually have 'name', 'email', or 'sub' + return data['name'] ?? data['email'] ?? data['sub'] ?? 'User'; + } catch (e) { + debugPrint("[JWT] Decode error: $e"); + return 'User'; + } + } + void _handleTabSelection() { - if (_tabController.index == 2 && _qrPendingRef == null) { + if (_tabController.index == 1 && _qrPendingRef == null) { _startQrFlow(); - } else if (_tabController.index != 2) { + } else if (_tabController.index != 1) { _stopQrPolling(); } } @@ -125,12 +140,13 @@ class _LoginScreenState extends ConsumerState _qrCountdownTimer?.cancel(); final jwt = res['sessionJwt']; - // Create Dummy User & Session for Descope SDK + final displayName = _getLoginIdFromJwt(jwt); + // Create User & Session for Descope SDK final dummyUser = DescopeUser( 'unknown', // userId [], // loginIds 0, // createdAt - 'User', // name + displayName, // name null, // picture (Uri?) '', // email false, // isVerifiedEmail @@ -180,9 +196,10 @@ class _LoginScreenState extends ConsumerState debugPrint("[Auth] Verification successful for token: $token"); if (jwt != null && mounted) { - // Create Dummy User & Session for Descope SDK to log in this tab + final displayName = _getLoginIdFromJwt(jwt); + // Create User & Session for Descope SDK to log in this tab final dummyUser = DescopeUser( - 'unknown', [], 0, 'User', null, '', false, '', false, {}, '', '', '', false, 'enabled', [], [], [], + 'unknown', [], 0, displayName, null, '', false, '', false, {}, '', '', '', false, 'enabled', [], [], [], ); final session = DescopeSession.fromJwt(jwt, jwt, dummyUser); Descope.sessionManager.manageSession(session); @@ -213,49 +230,29 @@ class _LoginScreenState extends ConsumerState void dispose() { _stopQrPolling(); _tabController.dispose(); - _emailController.dispose(); - _passwordController.dispose(); - _phoneController.dispose(); + _idController.dispose(); _smsCodeController.dispose(); super.dispose(); } - Future _handleEmailLogin() async { - final email = _emailController.text.trim(); - if (email.isEmpty) return; + Future _handleLogin() async { + final input = _idController.text.trim(); + if (input.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"); + String loginId = input; + if (!input.contains('@')) { + // Format phone number if it's not an email + loginId = input.replaceAll(RegExp(r'[-\s]'), ''); + if (loginId.startsWith('010')) { + loginId = '+82${loginId.substring(1)}'; } - } else { - debugPrint("[Auth] Initiating Email Enchanted Link for: $email"); - _initiateDescopeLinkFlow(email, isSms: false); } + + debugPrint("[Auth] Initiating Enchanted Link for: $loginId"); + _startEnchantedFlow(loginId, isEmail: input.contains('@')); } - Future _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"); - + Future _startEnchantedFlow(String loginId, {required bool isEmail}) async { try { if (mounted) { showDialog( @@ -265,10 +262,10 @@ class _LoginScreenState extends ConsumerState ); } - // 1. Init via Backend API - final initResponse = await AuthProxyService.initEnchantedLink(phone); + // 1. Init via Backend API (Now handles both SMS and SES Email) + final initResponse = await AuthProxyService.initEnchantedLink(loginId); final pendingRef = initResponse['pendingRef']; - debugPrint("[Auth] SMS Sent. PendingRef: $pendingRef"); + debugPrint("[Auth] Link Sent. PendingRef: $pendingRef"); if (mounted) { Navigator.of(context).pop(); // Close Loading @@ -277,11 +274,13 @@ class _LoginScreenState extends ConsumerState context: context, barrierDismissible: false, builder: (context) => AlertDialog( - title: const Text("SMS Sent"), + title: Text(isEmail ? "이메일 전송됨" : "SMS 전송됨"), content: Column( mainAxisSize: MainAxisSize.min, children: [ - const Text("Please check the link sent to your phone."), + Text(isEmail + ? "입력하신 이메일로 로그인 링크를 보냈습니다." + : "입력하신 번호로 로그인 링크를 보냈습니다."), const SizedBox(height: 16), const LinearProgressIndicator(), const SizedBox(height: 16), @@ -290,7 +289,7 @@ class _LoginScreenState extends ConsumerState debugPrint("[Auth] Polling canceled by user"); Navigator.of(context).pop(); }, - child: const Text("Cancel") + child: const Text("취소") ) ], ), @@ -301,9 +300,9 @@ class _LoginScreenState extends ConsumerState _pollForSession(pendingRef); } } catch (e) { - debugPrint("[Auth] SMS initialization failed: $e"); + debugPrint("[Auth] Initialization failed: $e"); if (mounted && Navigator.canPop(context)) Navigator.of(context).pop(); - _showError("Failed to send SMS: $e"); + _showError("전송 실패: $e"); } } @@ -324,13 +323,14 @@ class _LoginScreenState extends ConsumerState if (jwt != null) { debugPrint("[Auth] Polling SUCCESS. Token received."); + final displayName = _getLoginIdFromJwt(jwt); // Descope SDK 세션 강제 주입 // Note: DescopeUser in 0.9.11 requires 18 positional arguments. final dummyUser = DescopeUser( 'unknown', // userId [], // loginIds 0, // createdAt - 'User', // name + displayName, // name null, // picture (Uri?) '', // email false, // isVerifiedEmail @@ -368,65 +368,15 @@ class _LoginScreenState extends ConsumerState } } - Future _initiateDescopeLinkFlow(String loginId, {required bool isSms}) async { + void _showError(String message) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(message), backgroundColor: Colors.red), + ); 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); - } - } + AuthProxyService.logError(message); } catch (e) { - if (mounted && Navigator.canPop(context)) Navigator.of(context).pop(); - _showError("Login Failed: $e"); + // ignore } } @@ -463,18 +413,6 @@ class _LoginScreenState extends ConsumerState } } - 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( @@ -504,8 +442,7 @@ class _LoginScreenState extends ConsumerState TabBar( controller: _tabController, tabs: const [ - Tab(text: "이메일"), - Tab(text: "전화번호"), + Tab(text: "로그인"), Tab(text: "QR 코드"), ], ), @@ -516,69 +453,35 @@ class _LoginScreenState extends ConsumerState child: TabBarView( controller: _tabController, children: [ - // Email Form + // Unified Login Form Padding( padding: const EdgeInsets.only(top: 16.0), child: Column( children: [ TextField( - controller: _emailController, + controller: _idController, decoration: const InputDecoration( - labelText: "이메일", + labelText: "이메일 또는 휴대폰 번호", + hintText: "", 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), + prefixIcon: Icon(Icons.person_outline), ), + onSubmitted: (_) => _handleLogin(), ), const SizedBox(height: 24), FilledButton( - onPressed: _handleEmailLogin, + onPressed: _handleLogin, style: FilledButton.styleFrom( minimumSize: const Size.fromHeight(50), ), - child: const Text("로그인 / 링크 전송"), + child: const Text("로그인 링크 전송"), + ), + const SizedBox(height: 16), + const Text( + "입력하신 정보로 로그인 링크를 전송합니다.", + style: TextStyle(color: Colors.grey, fontSize: 12), + textAlign: TextAlign.center, ), - ], - ), - ), - - // 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, - ), ], ), ), @@ -586,11 +489,13 @@ class _LoginScreenState extends ConsumerState // QR Login View Column( mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, children: [ if (_isQrLoading) const CircularProgressIndicator() else if (_qrImageBase64 != null) Column( + crossAxisAlignment: CrossAxisAlignment.center, children: [ Container( padding: const EdgeInsets.all(16), @@ -609,6 +514,7 @@ class _LoginScreenState extends ConsumerState _qrRemainingSeconds > 0 ? "남은 시간: ${_formatTime(_qrRemainingSeconds)}" : "QR 코드 만료됨", + textAlign: TextAlign.center, style: TextStyle( color: _qrRemainingSeconds > 30 ? Colors.blue : Colors.red, fontWeight: FontWeight.bold, @@ -617,6 +523,7 @@ class _LoginScreenState extends ConsumerState const SizedBox(height: 8), const Text( "모바일 앱으로 스캔하세요", + textAlign: TextAlign.center, style: TextStyle(color: Colors.grey, fontSize: 12), ), TextButton( @@ -626,7 +533,7 @@ class _LoginScreenState extends ConsumerState ], ) else - const Text("QR 코드를 불러오지 못했습니다."), + const Text("QR 코드를 불러오지 못했습니다.", textAlign: TextAlign.center), ], ), ], diff --git a/frontend/lib/features/dashboard/presentation/dashboard_screen.dart b/frontend/lib/features/dashboard/presentation/dashboard_screen.dart index e125b046..12de5b48 100644 --- a/frontend/lib/features/dashboard/presentation/dashboard_screen.dart +++ b/frontend/lib/features/dashboard/presentation/dashboard_screen.dart @@ -67,13 +67,8 @@ class DashboardScreen extends StatelessWidget { SizedBox( width: double.infinity, height: 56, - child: ElevatedButton.icon( + child: ElevatedButton( onPressed: () => _onScanQR(context), - icon: const Icon(Icons.qr_code_scanner, size: 28), - label: Text( - 'QR 스캔하기', - style: GoogleFonts.notoSans(fontSize: 18, fontWeight: FontWeight.w600), - ), style: ElevatedButton.styleFrom( backgroundColor: const Color(0xFF1A1F2C), foregroundColor: Colors.white, @@ -82,6 +77,18 @@ class DashboardScreen extends StatelessWidget { borderRadius: BorderRadius.circular(12), ), ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.qr_code_scanner, size: 28), + const SizedBox(width: 12), + Text( + 'QR 스캔하기', + style: GoogleFonts.notoSans(fontSize: 18, fontWeight: FontWeight.w600), + ), + const SizedBox(width: 40), // Icon size(28) + Spacing(12) to balance the centering + ], + ), ), ), const SizedBox(height: 16),