1
0
forked from baron/baron-sso

QR 로그인 구현 완료

This commit is contained in:
Lectom C Han
2026-01-29 16:35:08 +09:00
parent 77d4e9fd77
commit ff655dc7c7
8 changed files with 656 additions and 203 deletions

View File

@@ -16,13 +16,46 @@ class _ApproveQrScreenState extends State<ApproveQrScreen> {
bool _isLoading = false;
String? _message;
bool _success = false;
bool _isCheckingSession = false;
@override
void initState() {
super.initState();
_bootstrapCookieSession();
}
Future<bool> _bootstrapCookieSession() async {
if (AuthTokenStore.usesCookie()) {
return true;
}
if (_isCheckingSession) {
return false;
}
setState(() => _isCheckingSession = true);
try {
await AuthProxyService.checkCookieSession();
AuthTokenStore.setCookieMode(provider: 'ory');
return true;
} catch (_) {
return false;
} finally {
if (mounted) {
setState(() => _isCheckingSession = false);
}
}
}
Future<void> _handleApprove() async {
if (widget.pendingRef == null) return;
final storedToken = AuthTokenStore.getToken();
final session = Descope.sessionManager.session;
if (storedToken == null && (session == null || session.refreshToken.isExpired)) {
final usesCookie = AuthTokenStore.usesCookie();
var hasCookie = usesCookie;
if (storedToken == null && (session == null || session.refreshToken.isExpired) && !hasCookie) {
hasCookie = await _bootstrapCookieSession();
}
if (storedToken == null && (session == null || session.refreshToken.isExpired) && !hasCookie) {
setState(() => _message = "Please log in on your phone first.");
context.go('/signin'); // Redirect to login
return;
@@ -37,7 +70,8 @@ class _ApproveQrScreenState extends State<ApproveQrScreen> {
final token = storedToken ?? session?.sessionToken.jwt ?? '';
await AuthProxyService.approveQrLogin(
widget.pendingRef!,
token,
token: token,
withCredentials: hasCookie,
);
setState(() {
_success = true;
@@ -57,7 +91,10 @@ class _ApproveQrScreenState extends State<ApproveQrScreen> {
@override
Widget build(BuildContext context) {
final isLoggedIn = Descope.sessionManager.session?.refreshToken.isExpired == false;
final hasStoredToken = AuthTokenStore.getToken() != null;
final hasDescopeSession = Descope.sessionManager.session?.refreshToken.isExpired == false;
final usesCookie = AuthTokenStore.usesCookie();
final isLoggedIn = hasStoredToken || hasDescopeSession || usesCookie || _isCheckingSession;
return Scaffold(
appBar: AppBar(title: const Text("QR Login Approval")),

View File

@@ -288,33 +288,36 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
timer.cancel();
_qrCountdownTimer?.cancel();
final jwt = res['sessionJwt'];
final displayName = _getLoginIdFromJwt(jwt);
// Create User & Session for Descope SDK
final dummyUser = DescopeUser(
'unknown', // userId
[], // loginIds
0, // createdAt
displayName, // 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);
final token = res['sessionJwt'] as String;
final isJwt = token.split('.').length == 3;
if (isJwt) {
final displayName = _getLoginIdFromJwt(token);
// Create User & Session for Descope SDK
final dummyUser = DescopeUser(
'unknown', // userId
[], // loginIds
0, // createdAt
displayName, // 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(token, token, dummyUser);
Descope.sessionManager.manageSession(session);
}
_onLoginSuccess(jwt);
_onLoginSuccess(token);
}
} catch (e) {
debugPrint("[QR] Polling error: $e");
@@ -906,8 +909,10 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
controller: _shortCodePrefixController,
textCapitalization: TextCapitalization.characters,
decoration: const InputDecoration(
labelText: "AA",
labelText: "영문 2자리",
border: OutlineInputBorder(),
hintText: "AB",
hintStyle: TextStyle(color: Colors.grey),
),
maxLength: 2,
),
@@ -919,11 +924,13 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
controller: _shortCodeDigitsController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
labelText: "000000",
labelText: "숫자 6자리",
border: const OutlineInputBorder(),
hintText: _linkExpireSeconds > 0
hintText: "345678",
hintStyle: const TextStyle(color: Colors.grey),
suffixText: _linkExpireSeconds > 0
? "유효시간 ${_formatTime(_linkExpireSeconds)}"
: "000000",
: null,
),
maxLength: 6,
),

View File

@@ -19,6 +19,38 @@ class _QRScanScreenState extends State<QRScanScreen> {
detectionSpeed: DetectionSpeed.noDuplicates,
);
bool _isScanned = false;
bool _isCheckingSession = false;
bool _isProcessing = false;
bool? _isSuccess;
String? _resultMessage;
@override
void initState() {
super.initState();
_bootstrapCookieSession();
}
Future<bool> _bootstrapCookieSession() async {
if (AuthTokenStore.usesCookie()) {
return true;
}
if (_isCheckingSession) {
return false;
}
setState(() => _isCheckingSession = true);
try {
await AuthProxyService.checkCookieSession();
AuthTokenStore.setCookieMode(provider: 'ory');
return true;
} catch (e) {
_log.info('Cookie session check failed: $e');
return false;
} finally {
if (mounted) {
setState(() => _isCheckingSession = false);
}
}
}
@override
void dispose() {
@@ -33,6 +65,9 @@ class _QRScanScreenState extends State<QRScanScreen> {
for (final barcode in barcodes) {
if (barcode.rawValue != null) {
_isScanned = true;
if (mounted) {
setState(() => _isProcessing = true);
}
String qrData = barcode.rawValue!;
String pendingRef = qrData;
@@ -42,6 +77,12 @@ class _QRScanScreenState extends State<QRScanScreen> {
final uri = Uri.parse(qrData);
if (uri.queryParameters.containsKey('ref')) {
pendingRef = uri.queryParameters['ref']!;
} else if (uri.pathSegments.isNotEmpty) {
final segments = uri.pathSegments;
final qlIndex = segments.indexOf('ql');
if (qlIndex != -1 && qlIndex + 1 < segments.length) {
pendingRef = segments[qlIndex + 1];
}
}
} catch (e) {
_log.warning('Failed to parse QR URL: $qrData', e);
@@ -49,10 +90,15 @@ class _QRScanScreenState extends State<QRScanScreen> {
}
_log.info('QR Code detected raw: $qrData, ref: $pendingRef');
final approveRef = qrData;
final sessionToken = AuthTokenStore.getToken() ??
Descope.sessionManager.session?.sessionToken.jwt;
if (sessionToken == null) {
final storedToken = AuthTokenStore.getToken();
final sessionToken = storedToken ?? Descope.sessionManager.session?.sessionToken.jwt;
var usesCookie = AuthTokenStore.usesCookie();
if (sessionToken == null && !usesCookie) {
usesCookie = await _bootstrapCookieSession();
}
if (sessionToken == null && !usesCookie) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('로그인이 필요합니다.'), backgroundColor: Colors.red),
@@ -64,28 +110,27 @@ class _QRScanScreenState extends State<QRScanScreen> {
try {
// Call backend API to approve login with clean ref
await AuthProxyService.approveQrLogin(pendingRef, sessionToken);
await AuthProxyService.approveQrLogin(
approveRef,
token: sessionToken,
withCredentials: usesCookie,
);
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();
setState(() {
_isSuccess = true;
_resultMessage = 'QR 승인 완료! PC 화면에서 로그인이 진행됩니다.';
_isProcessing = false;
});
}
} 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;
setState(() {
_isSuccess = false;
_resultMessage = 'QR 승인 실패: $e';
_isProcessing = false;
});
}
}
break;
@@ -93,6 +138,58 @@ class _QRScanScreenState extends State<QRScanScreen> {
}
}
void _resetScan() {
setState(() {
_isScanned = false;
_isProcessing = false;
_isSuccess = null;
_resultMessage = null;
});
controller.start();
}
Widget _buildResultView() {
final success = _isSuccess == true;
final icon = success ? Icons.check_circle_outline : Icons.error_outline;
final color = success ? Colors.green : Colors.red;
final title = success ? '승인 완료' : '승인 실패';
final message = _resultMessage ?? '';
return Center(
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, color: color, size: 72),
const SizedBox(height: 16),
Text(
title,
style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold, color: color),
),
const SizedBox(height: 12),
Text(
message,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.black54),
),
const SizedBox(height: 24),
if (!success)
FilledButton(
onPressed: _resetScan,
child: const Text('다시 스캔'),
),
if (success)
FilledButton(
onPressed: () => context.pop(),
child: const Text('닫기'),
),
],
),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
@@ -103,22 +200,30 @@ class _QRScanScreenState extends State<QRScanScreen> {
onPressed: () => context.pop(),
),
),
body: MobileScanner(
controller: controller,
onDetect: _onDetect,
errorBuilder: (context, error, child) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
body: _isSuccess == null
? Stack(
children: [
const Icon(Icons.error, color: Colors.red, size: 50),
const SizedBox(height: 10),
Text('Camera Error: ${error.errorCode}'),
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}'),
],
),
);
},
),
if (_isProcessing || _isCheckingSession)
const Center(child: CircularProgressIndicator()),
],
),
);
},
),
)
: _buildResultView(),
);
}
}