1
0
forked from baron/baron-sso
Files
baron-sso/userfront/lib/features/auth/presentation/consent_screen.dart
2026-02-10 19:13:00 +09:00

385 lines
14 KiB
Dart

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:userfront/core/services/auth_proxy_service.dart';
import 'package:userfront/core/services/web_window.dart';
class ConsentScreen extends StatefulWidget {
final String consentChallenge;
const ConsentScreen({super.key, required this.consentChallenge});
@override
State<ConsentScreen> createState() => _ConsentScreenState();
}
class _ConsentScreenState extends State<ConsentScreen> {
Map<String, dynamic>? _consentInfo;
bool _isLoading = true;
bool _isSubmitting = false;
String? _error;
// 사용자가 선택한 스코프 목록
final Set<String> _selectedScopes = {};
// 권한별 설명 매핑 (동적으로 업데이트됨)
final Map<String, String> _scopeDescriptions = {
'openid': 'OpenID 인증 정보 (로그인 상태 확인)',
'profile': '기본 프로필 정보 (이름, 사용자 식별자)',
'email': '이메일 주소 (계정 식별 및 알림 용도)',
'offline_access': '오프라인 접근 (로그인 유지)',
'phone': '휴대폰 번호 (본인 인증 및 알림)',
};
// 필수 권한 목록 (동적으로 업데이트됨)
final Set<String> _mandatoryScopes = {'openid'};
@override
void initState() {
super.initState();
_fetchConsentInfo();
}
Future<void> _fetchConsentInfo() async {
try {
final info = await AuthProxyService.getConsentInfo(widget.consentChallenge);
// [Skip Logic] 백엔드에서 자동 승인되어 리다이렉트 URL이 온 경우 즉시 이동
if (info['redirectTo'] != null) {
webWindow.redirectTo(info['redirectTo']);
return;
}
// 백엔드에서 전달받은 커스텀 스코프 정보(scope_details) 적용
if (info['scope_details'] != null) {
final details = info['scope_details'] as Map<String, dynamic>;
details.forEach((scope, detail) {
if (detail is Map<String, dynamic>) {
// 설명 업데이트
if (detail['description'] != null && detail['description'].toString().isNotEmpty) {
_scopeDescriptions[scope] = detail['description'].toString();
}
// 필수 여부 업데이트
if (detail['mandatory'] == true) {
_mandatoryScopes.add(scope);
} else {
// openid는 기본적으로 필수지만 설정에서 굳이 껐다면?
// 안전을 위해 openid는 항상 필수로 유지하는 것이 좋지만,
// 여기서는 서버 설정을 존중하되 openid는 예외처리 할 수도 있음.
// 우선 서버 설정이 있으면 반영 (단, openid는 제거하지 않음)
if (scope != 'openid') {
_mandatoryScopes.remove(scope);
}
}
}
});
}
// 초기 선택 상태 설정: 모든 요청된 스코프를 기본 선택
final requestedScopes = (info['requested_scope'] as List<dynamic>?)?.cast<String>() ?? [];
_selectedScopes.addAll(requestedScopes);
setState(() {
_consentInfo = info;
_isLoading = false;
});
} catch (e) {
setState(() {
_error = '동의 정보를 불러오는데 실패했습니다: $e';
_isLoading = false;
});
}
}
Future<void> _acceptConsent() async {
setState(() {
_isSubmitting = true;
_error = null;
});
try {
// 선택된 스코프만 리스트로 변환하여 전송
final result = await AuthProxyService.acceptConsent(
widget.consentChallenge,
grantScope: _selectedScopes.toList(),
);
if (result['redirectTo'] != null) {
webWindow.redirectTo(result['redirectTo']);
} else {
setState(() {
_error = '동의가 처리되었으나, 리다이렉트 URL을 받지 못했습니다.';
_isSubmitting = false;
});
}
} catch (e) {
setState(() {
_error = '동의 처리에 실패했습니다: $e';
_isSubmitting = false;
});
}
}
Future<void> _onCancel() async {
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('동의 취소'),
content: const Text('권한 동의를 취소하면 해당 서비스를 이용할 수 없습니다. 취소하시겠습니까?'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('아니오'),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
style: TextButton.styleFrom(foregroundColor: Colors.red),
child: const Text('예, 취소합니다'),
),
],
),
);
if (confirmed == true) {
setState(() => _isSubmitting = true);
try {
final resp = await AuthProxyService.rejectConsent(widget.consentChallenge);
final redirectTo = resp['redirectTo'];
if (redirectTo != null) {
webWindow.redirectTo(redirectTo);
} else {
if (mounted) context.go('/');
}
} catch (e) {
setState(() => _isSubmitting = false);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('취소 처리 중 오류가 발생했습니다: $e')),
);
}
}
}
}
@override
Widget build(BuildContext context) {
// 배경색을 약간 어둡게 처리하거나, 전체적인 테마 색상을 사용
return Scaffold(
backgroundColor: Colors.grey[100],
body: Center(
child: _isLoading
? const CircularProgressIndicator()
: _error != null
? _buildErrorCard()
: _buildConsentCard(context),
),
);
}
Widget _buildErrorCard() {
return Card(
margin: const EdgeInsets.all(24),
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.error_outline, color: Colors.red, size: 48),
const SizedBox(height: 16),
Text(_error!, textAlign: TextAlign.center),
],
),
),
);
}
Widget _buildConsentCard(BuildContext context) {
final clientName = _consentInfo?['client']?['client_name'] ?? '알 수 없는 앱';
final clientId = _consentInfo?['client']?['client_id'] ?? '-';
final clientLogo = _consentInfo?['client']?['logo_uri'];
final requestedScopes = (_consentInfo?['requested_scope'] as List<dynamic>?)?.cast<String>() ?? [];
return SingleChildScrollView(
child: Container(
constraints: const BoxConstraints(maxWidth: 520),
margin: const EdgeInsets.all(16),
child: Card(
elevation: 8,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
child: Padding(
padding: const EdgeInsets.all(32.0),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// 1. 헤더 영역
const Text(
'접근 권한 요청',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
const SizedBox(height: 12),
Text(
'아래 서비스가 회원님의 계정 정보에 접근하려고 합니다.\n계속 진행하려면 동의 여부를 선택해 주세요.',
style: TextStyle(fontSize: 14, color: Colors.grey[600]),
textAlign: TextAlign.center,
),
const SizedBox(height: 32),
// 2. 서비스 정보 영역
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.grey[50],
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.grey[200]!),
),
child: Row(
children: [
if (clientLogo != null && clientLogo.toString().isNotEmpty)
Padding(
padding: const EdgeInsets.only(right: 16),
child: CircleAvatar(
radius: 24,
backgroundImage: NetworkImage(clientLogo),
backgroundColor: Colors.transparent,
),
)
else
const Padding(
padding: EdgeInsets.only(right: 16),
child: CircleAvatar(
radius: 24,
child: Icon(Icons.apps),
),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
clientName,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 4),
Text(
'클라이언트 ID: $clientId',
style: TextStyle(
fontSize: 12,
color: Colors.grey[500],
fontFamily: 'monospace',
),
),
],
),
),
],
),
),
const SizedBox(height: 32),
// 3. 권한 선택 영역
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'요청된 권한',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
Text(
'${requestedScopes.length}',
style: TextStyle(
fontSize: 14,
color: Theme.of(context).primaryColor,
fontWeight: FontWeight.w500,
),
),
],
),
const SizedBox(height: 8),
const Divider(),
...requestedScopes.map((scope) {
final isMandatory = _mandatoryScopes.contains(scope);
final description = _scopeDescriptions[scope] ?? scope;
final isSelected = _selectedScopes.contains(scope);
return CheckboxListTile(
title: Text(
scope, // 스코프 키 (예: openid)
style: const TextStyle(fontWeight: FontWeight.w500),
),
subtitle: Text(description),
value: isSelected,
onChanged: isMandatory
? null // 필수 항목은 변경 불가 (비활성화 상태로 체크됨)
: (bool? value) {
setState(() {
if (value == true) {
_selectedScopes.add(scope);
} else {
_selectedScopes.remove(scope);
}
});
},
controlAffinity: ListTileControlAffinity.leading,
contentPadding: EdgeInsets.zero,
activeColor: Theme.of(context).primaryColor,
);
}),
const Divider(),
const SizedBox(height: 32),
// 4. 버튼 영역
ElevatedButton(
onPressed: _isSubmitting ? null : _acceptConsent,
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
backgroundColor: const Color(0xFF1A1F2C), // 브랜드 컬러
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
elevation: 0,
),
child: _isSubmitting
? const SizedBox(
height: 20,
width: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
color: Colors.white,
),
)
: const Text(
'동의하고 계속하기',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
),
),
const SizedBox(height: 12),
OutlinedButton(
onPressed: _isSubmitting ? null : _onCancel,
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 16),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
),
child: const Text('취소'),
),
const SizedBox(height: 16),
Text(
'동의 후 자동으로 서비스로 이동합니다.',
style: TextStyle(fontSize: 12, color: Colors.grey[500]),
textAlign: TextAlign.center,
),
],
),
),
),
),
);
}
}