forked from baron/baron-sso
Merge commit 'e345570210aa0fc8acdb9cf042561f35f00812f0'
This commit is contained in:
@@ -2,6 +2,7 @@ import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
||||
import 'http_client.dart';
|
||||
import 'dart:html' as html;
|
||||
|
||||
class AuthProxyService {
|
||||
static String _envOrDefault(String key, String fallback) {
|
||||
@@ -196,23 +197,60 @@ class AuthProxyService {
|
||||
}
|
||||
}
|
||||
|
||||
static Future<Map<String, dynamic>> loginWithPassword(String loginId, String password) async {
|
||||
static Future<Map<String, dynamic>> loginWithPassword(String loginId, String password, {String? loginChallenge}) async {
|
||||
final url = Uri.parse('$_baseUrl/api/v1/auth/password/login');
|
||||
|
||||
final payload = {
|
||||
'loginId': loginId,
|
||||
'password': password,
|
||||
if (loginChallenge != null && loginChallenge.isNotEmpty) 'login_challenge': loginChallenge,
|
||||
};
|
||||
|
||||
final response = await http.post(
|
||||
url,
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode({
|
||||
'loginId': loginId,
|
||||
'password': password,
|
||||
}),
|
||||
body: jsonEncode(payload),
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = jsonDecode(response.body);
|
||||
if (data['redirectTo'] != null && data['redirectTo'].isNotEmpty) {
|
||||
html.window.location.href = data['redirectTo'];
|
||||
}
|
||||
return data;
|
||||
} else {
|
||||
final errorBody = jsonDecode(response.body);
|
||||
throw Exception(errorBody['error'] ?? 'Failed to login');
|
||||
}
|
||||
}
|
||||
static Future<Map<String, dynamic>> getConsentInfo(String consentChallenge) async {
|
||||
final url = Uri.parse('$_baseUrl/api/v1/auth/consent').replace(queryParameters: {'consent_challenge': consentChallenge});
|
||||
final response = await http.get(
|
||||
url,
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return jsonDecode(response.body);
|
||||
} else {
|
||||
final errorBody = jsonDecode(response.body);
|
||||
throw Exception(errorBody['error'] ?? 'Failed to login');
|
||||
throw Exception(errorBody['error'] ?? 'Failed to get consent info');
|
||||
}
|
||||
}
|
||||
|
||||
static Future<Map<String, dynamic>> acceptConsent(String consentChallenge) async {
|
||||
final url = Uri.parse('$_baseUrl/api/v1/auth/consent/accept');
|
||||
final response = await http.post(
|
||||
url,
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: jsonEncode({'consent_challenge': consentChallenge}),
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return jsonDecode(response.body);
|
||||
} else {
|
||||
final errorBody = jsonDecode(response.body);
|
||||
throw Exception(errorBody['error'] ?? 'Failed to accept consent');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
123
userfront/lib/features/auth/presentation/consent_screen.dart
Normal file
123
userfront/lib/features/auth/presentation/consent_screen.dart
Normal file
@@ -0,0 +1,123 @@
|
||||
import 'dart:html' as html;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:userfront/core/services/auth_proxy_service.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;
|
||||
String? _error;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_fetchConsentInfo();
|
||||
}
|
||||
|
||||
Future<void> _fetchConsentInfo() async {
|
||||
try {
|
||||
final info = await AuthProxyService.getConsentInfo(widget.consentChallenge);
|
||||
setState(() {
|
||||
_consentInfo = info;
|
||||
_isLoading = false;
|
||||
});
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_error = 'Failed to load consent information: $e';
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _acceptConsent() async {
|
||||
setState(() {
|
||||
_isLoading = true;
|
||||
_error = null;
|
||||
});
|
||||
try {
|
||||
final result =
|
||||
await AuthProxyService.acceptConsent(widget.consentChallenge);
|
||||
if (result['redirectTo'] != null) {
|
||||
html.window.location.href = result['redirectTo'];
|
||||
} else {
|
||||
setState(() {
|
||||
_error = 'Consent accepted, but no redirect URL received.';
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_error = 'Failed to accept consent: $e';
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Grant Access')),
|
||||
body: Center(
|
||||
child: _isLoading
|
||||
? const CircularProgressIndicator()
|
||||
: _error != null
|
||||
? Text(_error!, style: const TextStyle(color: Colors.red))
|
||||
: _consentInfo != null
|
||||
? Card(
|
||||
elevation: 4,
|
||||
margin: const EdgeInsets.all(16),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24.0),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
'${_consentInfo!['client']?['client_name'] ?? 'An application'} wants to access your account',
|
||||
style: Theme.of(context).textTheme.headlineSmall,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
const Text('This will allow the application to:'),
|
||||
const SizedBox(height: 16),
|
||||
if (_consentInfo!['requested_scope'] != null)
|
||||
...(_consentInfo!['requested_scope'] as List)
|
||||
.map((scope) => ListTile(
|
||||
leading: const Icon(Icons.check_circle_outline),
|
||||
title: Text(scope.toString()),
|
||||
))
|
||||
.toList(),
|
||||
const SizedBox(height: 24),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
|
||||
children: [
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
// TODO: Implement reject consent
|
||||
html.window.alert('Consent rejected. You can close this window.');
|
||||
},
|
||||
child: const Text('Deny'),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: _acceptConsent,
|
||||
child: const Text('Allow'),
|
||||
),
|
||||
],
|
||||
)
|
||||
],
|
||||
),
|
||||
),
|
||||
)
|
||||
: const Text('No consent information available.'),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
117
userfront/lib/features/auth/presentation/error_screen.dart
Normal file
117
userfront/lib/features/auth/presentation/error_screen.dart
Normal file
@@ -0,0 +1,117 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
class ErrorScreen extends StatelessWidget {
|
||||
final String? errorId;
|
||||
final String? errorCode;
|
||||
final String? description;
|
||||
|
||||
const ErrorScreen({
|
||||
super.key,
|
||||
this.errorId,
|
||||
this.errorCode,
|
||||
this.description,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final errorType = (errorCode == null || errorCode!.isEmpty)
|
||||
? 'unknown_error'
|
||||
: errorCode!;
|
||||
final title = errorCode == null || errorCode!.isEmpty
|
||||
? '인증 과정에서 오류가 발생했습니다'
|
||||
: '오류: $errorCode';
|
||||
final detail = description?.isNotEmpty == true
|
||||
? description!
|
||||
: '요청을 처리하는 중 문제가 발생했습니다. 잠시 후 다시 시도해 주세요.';
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: const Color(0xFFF7F8FA),
|
||||
body: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 560),
|
||||
child: Card(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 24),
|
||||
elevation: 0,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
side: const BorderSide(color: Color(0xFFE5E7EB)),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(28, 28, 28, 24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
title,
|
||||
style: theme.textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
color: const Color(0xFF111827),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
detail,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: const Color(0xFF4B5563),
|
||||
height: 1.5,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
'오류 종류: $errorType',
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: const Color(0xFF6B7280),
|
||||
),
|
||||
),
|
||||
if (errorId != null && errorId!.isNotEmpty) ...[
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
'오류 ID: $errorId',
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: const Color(0xFF6B7280),
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 20),
|
||||
Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 12,
|
||||
children: [
|
||||
ElevatedButton(
|
||||
onPressed: () => context.go('/login'),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: const Color(0xFF111827),
|
||||
foregroundColor: Colors.white,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
),
|
||||
child: const Text('로그인으로 이동'),
|
||||
),
|
||||
OutlinedButton(
|
||||
onPressed: () => context.go('/'),
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: const Color(0xFF111827),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
side: const BorderSide(color: Color(0xFFCBD5F5)),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
),
|
||||
child: const Text('홈으로 이동'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -10,10 +10,13 @@ import '../../../core/services/auth_proxy_service.dart';
|
||||
import '../../../core/services/auth_token_store.dart';
|
||||
import '../../../core/notifiers/auth_notifier.dart';
|
||||
import '../../profile/domain/notifiers/profile_notifier.dart';
|
||||
import 'dart:html' as html;
|
||||
|
||||
class LoginScreen extends ConsumerStatefulWidget {
|
||||
final String? verificationToken;
|
||||
const LoginScreen({super.key, this.verificationToken});
|
||||
final String? loginChallenge;
|
||||
|
||||
const LoginScreen({super.key, this.verificationToken, this.loginChallenge});
|
||||
|
||||
@override
|
||||
ConsumerState<LoginScreen> createState() => _LoginScreenState();
|
||||
@@ -26,6 +29,7 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
final TextEditingController _passwordLoginIdController = TextEditingController();
|
||||
final TextEditingController _passwordController = TextEditingController();
|
||||
String? _redirectUrl;
|
||||
String? _loginChallenge;
|
||||
|
||||
// QR Login Variables
|
||||
String? _qrImageBase64;
|
||||
@@ -58,14 +62,13 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// 탭 컨트롤러: 3개 탭, 기본 선택은 두 번째 탭("로그인 링크")
|
||||
_tabController = TabController(length: 3, vsync: this, initialIndex: 1);
|
||||
_tabController.addListener(_handleTabSelection);
|
||||
_drySendEnabled = _parseBoolParam(Uri.base.queryParameters['drySend']) && !AuthProxyService.isProdEnv;
|
||||
|
||||
// Check for tokens (Path Parameter or Legacy Query Parameter)
|
||||
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
final uri = Uri.base;
|
||||
_loginChallenge = widget.loginChallenge ?? uri.queryParameters['login_challenge'];
|
||||
final loginIdParam = uri.queryParameters['loginId'];
|
||||
final codeParam = uri.queryParameters['code'];
|
||||
final pendingRefParam = uri.queryParameters['pendingRef'];
|
||||
@@ -190,7 +193,6 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
});
|
||||
}
|
||||
|
||||
// JWT를 디코딩해 표시용 로그인 아이디 추출
|
||||
String _getLoginIdFromJwt(String jwt) {
|
||||
try {
|
||||
final parts = jwt.split('.');
|
||||
@@ -198,7 +200,6 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
|
||||
final payload = utf8.decode(base64Url.decode(base64Url.normalize(parts[1])));
|
||||
final data = json.decode(payload);
|
||||
// 일반적으로 name/email/sub 필드를 사용
|
||||
return data['name'] ?? data['email'] ?? data['sub'] ?? 'User';
|
||||
} catch (e) {
|
||||
debugPrint("[JWT] Decode error: $e");
|
||||
@@ -207,7 +208,6 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
}
|
||||
|
||||
void _handleTabSelection() {
|
||||
// QR 탭 (세 번째 탭, index 2)이 선택되었을 때 QR 플로우 시작
|
||||
if (_tabController.index == 2 && _qrPendingRef == null) {
|
||||
_startQrFlow();
|
||||
} else if (_tabController.index != 2) {
|
||||
@@ -626,7 +626,6 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
// 이메일/비밀번호 로그인 처리
|
||||
Future<void> _handlePasswordLogin() async {
|
||||
final input = _passwordLoginIdController.text.trim();
|
||||
final password = _passwordController.text.trim();
|
||||
@@ -637,14 +636,12 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
|
||||
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)}';
|
||||
}
|
||||
}
|
||||
|
||||
// 로딩 인디케이터 표시
|
||||
showDialog(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
@@ -652,15 +649,23 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
);
|
||||
|
||||
try {
|
||||
final res = await AuthProxyService.loginWithPassword(loginId, password);
|
||||
final res = await AuthProxyService.loginWithPassword(loginId, password, loginChallenge: _loginChallenge);
|
||||
final jwt = res['sessionJwt'];
|
||||
final provider = res['provider'] as String?;
|
||||
if (jwt != null && mounted) {
|
||||
Navigator.of(context).pop(); // 로딩 닫기
|
||||
final redirectTo = res['redirectTo'] as String?;
|
||||
|
||||
if (mounted) Navigator.of(context).pop();
|
||||
|
||||
if (redirectTo != null && redirectTo.isNotEmpty) {
|
||||
html.window.location.href = redirectTo;
|
||||
return;
|
||||
}
|
||||
|
||||
if (jwt != null) {
|
||||
_onLoginSuccess(jwt, provider: provider);
|
||||
}
|
||||
} catch (e) {
|
||||
if (mounted) Navigator.of(context).pop(); // 로딩 닫기
|
||||
if (mounted) Navigator.of(context).pop();
|
||||
if (e.toString().contains("User not registered")) {
|
||||
_showUnregisteredDialog();
|
||||
} else {
|
||||
@@ -669,14 +674,12 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
}
|
||||
}
|
||||
|
||||
// 로그인 링크 전송 처리
|
||||
Future<void> _handleLinkLogin() async {
|
||||
final input = _linkIdController.text.trim();
|
||||
if (input.isEmpty) return;
|
||||
|
||||
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)}';
|
||||
@@ -685,7 +688,6 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
|
||||
debugPrint("[Auth] Initiating Enchanted Link for: $loginId");
|
||||
|
||||
// 링크 전송 전 사용자 존재 여부 체크 (백엔드에서 이미 처리하지만 에러 핸들링을 위해)
|
||||
try {
|
||||
await _startEnchantedFlow(loginId, isEmail: input.contains('@'));
|
||||
} catch (e) {
|
||||
@@ -707,7 +709,6 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
);
|
||||
}
|
||||
|
||||
// 1. Init via Backend API
|
||||
final initResponse = await AuthProxyService.initEnchantedLink(
|
||||
loginId,
|
||||
codeOnly: codeOnly,
|
||||
@@ -727,13 +728,12 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
_lastLinkLoginId = loginId;
|
||||
_lastLinkIsEmail = isEmail;
|
||||
});
|
||||
Navigator.of(context).pop(); // Close Loading
|
||||
Navigator.of(context).pop();
|
||||
|
||||
_showInfo(isEmail
|
||||
? "입력하신 이메일로 로그인 링크를 보냈습니다."
|
||||
: "입력하신 번호로 로그인 링크를 보냈습니다.");
|
||||
|
||||
// 2. Poll Backend manually
|
||||
final initialInterval = (interval is int && interval > 0)
|
||||
? Duration(seconds: interval)
|
||||
: const Duration(seconds: 2);
|
||||
@@ -761,7 +761,7 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
|
||||
Future<void> _pollForSession(String pendingRef, {Duration? initialInterval}) async {
|
||||
int attempts = 0;
|
||||
const maxAttempts = 60; // 2 minutes
|
||||
const maxAttempts = 60;
|
||||
var pollInterval = initialInterval ?? const Duration(seconds: 2);
|
||||
debugPrint("[Auth] Starting poll for ref: $pendingRef");
|
||||
|
||||
@@ -789,7 +789,7 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
}
|
||||
if (result['error'] == 'expired_token') {
|
||||
if (mounted) {
|
||||
Navigator.of(context).pop(); // Close Polling Dialog
|
||||
Navigator.of(context).pop();
|
||||
_showError("Login timed out.");
|
||||
}
|
||||
return;
|
||||
@@ -820,7 +820,7 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
|
||||
if (mounted) {
|
||||
debugPrint("[Auth] Polling timed out for ref: $pendingRef");
|
||||
Navigator.of(context).pop(); // Close Polling Dialog
|
||||
Navigator.of(context).pop();
|
||||
_showError("Login timed out.");
|
||||
}
|
||||
}
|
||||
@@ -879,19 +879,16 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
AuthTokenStore.setToken(token, provider: providerName);
|
||||
AuthTokenStore.clearPendingProvider();
|
||||
|
||||
// 로그인 성공 직후 백엔드에서 전체 프로필 정보를 가져와 세션 업데이트
|
||||
try {
|
||||
await ref.read(profileProvider.notifier).loadProfile();
|
||||
} catch (e) {
|
||||
debugPrint("[Auth] Failed to pre-fetch profile: $e");
|
||||
}
|
||||
|
||||
// 1. Handle Popup Flow
|
||||
if (WebAuthIntegration.isPopup()) {
|
||||
debugPrint("[Auth] Popup detected. Notifying opener and attempting to close.");
|
||||
WebAuthIntegration.sendLoginSuccess(token);
|
||||
} else {
|
||||
// 2. Handle Redirect Flow
|
||||
if (_redirectUrl != null && _redirectUrl!.isNotEmpty) {
|
||||
debugPrint("[Auth] Redirecting standalone window to: $_redirectUrl");
|
||||
final target = "$_redirectUrl?token=$token";
|
||||
@@ -900,7 +897,6 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Standalone mode / Fallback
|
||||
debugPrint("[Auth] Login success. Navigating to root.");
|
||||
AuthNotifier.instance.notify();
|
||||
if (mounted) {
|
||||
@@ -908,7 +904,6 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
}
|
||||
}
|
||||
|
||||
// [New] 미등록 회원 안내 팝업
|
||||
void _showUnregisteredDialog() {
|
||||
showDialog(
|
||||
context: context,
|
||||
@@ -1010,7 +1005,6 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
child: TabBarView(
|
||||
controller: _tabController,
|
||||
children: [
|
||||
// 1. 이메일/비밀번호 로그인 폼
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 16.0),
|
||||
child: Column(
|
||||
@@ -1047,7 +1041,6 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
),
|
||||
),
|
||||
|
||||
// 2. 로그인 링크 전송 -> 전송 후 코드 입력으로 전환
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 16.0),
|
||||
child: Column(
|
||||
@@ -1188,7 +1181,6 @@ class _LoginScreenState extends ConsumerState<LoginScreen>
|
||||
),
|
||||
),
|
||||
|
||||
// 3. QR 로그인 뷰
|
||||
Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
|
||||
@@ -102,6 +102,37 @@ class ProfileRepository {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> changePassword({
|
||||
required String currentPassword,
|
||||
required String newPassword,
|
||||
}) async {
|
||||
final token = await _getToken();
|
||||
final useCookie = AuthTokenStore.usesCookie();
|
||||
if (token == null && !useCookie) throw Exception('No active session');
|
||||
|
||||
final url = Uri.parse('$_baseUrl/api/v1/user/me/password');
|
||||
final client = createHttpClient(withCredentials: useCookie);
|
||||
final headers = <String, String>{
|
||||
'Content-Type': 'application/json',
|
||||
};
|
||||
if (!useCookie && token != null) {
|
||||
headers['Authorization'] = 'Bearer $token';
|
||||
}
|
||||
final response = await client.post(
|
||||
url,
|
||||
headers: headers,
|
||||
body: jsonEncode({
|
||||
'currentPassword': currentPassword,
|
||||
'newPassword': newPassword,
|
||||
}),
|
||||
);
|
||||
client.close();
|
||||
|
||||
if (response.statusCode != 200) {
|
||||
throw Exception('Failed to change password: ${response.body}');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> verifyUpdateCode(String phone, String code) async {
|
||||
final token = await _getToken();
|
||||
final useCookie = AuthTokenStore.usesCookie();
|
||||
|
||||
@@ -26,6 +26,9 @@ class _ProfilePageState extends ConsumerState<ProfilePage> {
|
||||
TextEditingController? _phoneController;
|
||||
TextEditingController? _departmentController;
|
||||
TextEditingController? _codeController;
|
||||
TextEditingController? _currentPasswordController;
|
||||
TextEditingController? _newPasswordController;
|
||||
TextEditingController? _confirmPasswordController;
|
||||
final FocusNode _nameFocus = FocusNode();
|
||||
final FocusNode _departmentFocus = FocusNode();
|
||||
final FocusNode _phoneFocus = FocusNode();
|
||||
@@ -42,6 +45,13 @@ class _ProfilePageState extends ConsumerState<ProfilePage> {
|
||||
bool _isCodeSent = false;
|
||||
bool _isVerifying = false;
|
||||
|
||||
bool _isPasswordSaving = false;
|
||||
String? _passwordError;
|
||||
String? _passwordSuccess;
|
||||
bool _showCurrentPassword = false;
|
||||
bool _showNewPassword = false;
|
||||
bool _showConfirmPassword = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
@@ -97,6 +107,9 @@ class _ProfilePageState extends ConsumerState<ProfilePage> {
|
||||
_phoneController?.dispose();
|
||||
_departmentController?.dispose();
|
||||
_codeController?.dispose();
|
||||
_currentPasswordController?.dispose();
|
||||
_newPasswordController?.dispose();
|
||||
_confirmPasswordController?.dispose();
|
||||
_nameFocus.dispose();
|
||||
_departmentFocus.dispose();
|
||||
_phoneFocus.dispose();
|
||||
@@ -113,6 +126,9 @@ class _ProfilePageState extends ConsumerState<ProfilePage> {
|
||||
_nameController ??= TextEditingController(text: profile.name);
|
||||
_departmentController ??= TextEditingController(text: profile.department);
|
||||
_codeController ??= TextEditingController();
|
||||
_currentPasswordController ??= TextEditingController();
|
||||
_newPasswordController ??= TextEditingController();
|
||||
_confirmPasswordController ??= TextEditingController();
|
||||
|
||||
if (_phoneController == null) {
|
||||
_phoneController = TextEditingController(text: profile.phone);
|
||||
@@ -256,6 +272,54 @@ class _ProfilePageState extends ConsumerState<ProfilePage> {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _changePassword() async {
|
||||
if (_isPasswordSaving) return;
|
||||
final currentPassword = _currentPasswordController?.text.trim() ?? '';
|
||||
final newPassword = _newPasswordController?.text.trim() ?? '';
|
||||
final confirmPassword = _confirmPasswordController?.text.trim() ?? '';
|
||||
|
||||
if (currentPassword.isEmpty) {
|
||||
setState(() => _passwordError = '현재 비밀번호를 입력해 주세요.');
|
||||
return;
|
||||
}
|
||||
if (newPassword.isEmpty) {
|
||||
setState(() => _passwordError = '새 비밀번호를 입력해 주세요.');
|
||||
return;
|
||||
}
|
||||
if (newPassword != confirmPassword) {
|
||||
setState(() => _passwordError = '새 비밀번호가 일치하지 않습니다.');
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_passwordError = null;
|
||||
_passwordSuccess = null;
|
||||
_isPasswordSaving = true;
|
||||
});
|
||||
|
||||
try {
|
||||
await ref.read(profileRepositoryProvider).changePassword(
|
||||
currentPassword: currentPassword,
|
||||
newPassword: newPassword,
|
||||
);
|
||||
_currentPasswordController?.clear();
|
||||
_newPasswordController?.clear();
|
||||
_confirmPasswordController?.clear();
|
||||
setState(() {
|
||||
_passwordSuccess = '비밀번호가 변경되었습니다.';
|
||||
});
|
||||
} catch (e) {
|
||||
final message = e.toString().replaceFirst('Exception: ', '');
|
||||
setState(() {
|
||||
_passwordError = '비밀번호 변경 실패: $message';
|
||||
});
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() => _isPasswordSaving = false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _autoSaveIfEditing(UserProfile profile, String field) {
|
||||
if (_editingField != field) return;
|
||||
if (_isVerifying) return;
|
||||
@@ -693,6 +757,104 @@ class _ProfilePageState extends ConsumerState<ProfilePage> {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPasswordSection() {
|
||||
return _buildCard(
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'비밀번호 변경',
|
||||
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w700),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
const Text(
|
||||
'현재 비밀번호 확인 후 새 비밀번호로 변경합니다.',
|
||||
style: TextStyle(color: Color(0xFF6B7280)),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: _currentPasswordController,
|
||||
obscureText: !_showCurrentPassword,
|
||||
decoration: InputDecoration(
|
||||
labelText: '현재 비밀번호',
|
||||
border: const OutlineInputBorder(),
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(_showCurrentPassword ? Icons.visibility_off : Icons.visibility),
|
||||
onPressed: () => setState(() {
|
||||
_showCurrentPassword = !_showCurrentPassword;
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _newPasswordController,
|
||||
obscureText: !_showNewPassword,
|
||||
decoration: InputDecoration(
|
||||
labelText: '새 비밀번호',
|
||||
border: const OutlineInputBorder(),
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(_showNewPassword ? Icons.visibility_off : Icons.visibility),
|
||||
onPressed: () => setState(() {
|
||||
_showNewPassword = !_showNewPassword;
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _confirmPasswordController,
|
||||
obscureText: !_showConfirmPassword,
|
||||
decoration: InputDecoration(
|
||||
labelText: '새 비밀번호 확인',
|
||||
border: const OutlineInputBorder(),
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(_showConfirmPassword ? Icons.visibility_off : Icons.visibility),
|
||||
onPressed: () => setState(() {
|
||||
_showConfirmPassword = !_showConfirmPassword;
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (_passwordError != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
_passwordError!,
|
||||
style: const TextStyle(color: Colors.red),
|
||||
),
|
||||
],
|
||||
if (_passwordSuccess != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
_passwordSuccess!,
|
||||
style: const TextStyle(color: Colors.green),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 16),
|
||||
Row(
|
||||
children: [
|
||||
ElevatedButton(
|
||||
onPressed: _isPasswordSaving ? null : _changePassword,
|
||||
child: _isPasswordSaving
|
||||
? const SizedBox(
|
||||
width: 18,
|
||||
height: 18,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Text('비밀번호 변경'),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
TextButton(
|
||||
onPressed: () => context.go('/recovery'),
|
||||
child: const Text('비밀번호를 잊으셨나요?'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildContent(UserProfile profile, bool isUpdating) {
|
||||
return RefreshIndicator(
|
||||
onRefresh: () => ref.read(profileProvider.notifier).loadProfile(),
|
||||
@@ -754,6 +916,10 @@ class _ProfilePageState extends ConsumerState<ProfilePage> {
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 28),
|
||||
_buildSectionTitle('보안', '비밀번호를 안전하게 관리합니다.'),
|
||||
const SizedBox(height: 12),
|
||||
_buildPasswordSection(),
|
||||
if (isUpdating || _isVerifying) ...[
|
||||
const SizedBox(height: 24),
|
||||
const Center(child: CircularProgressIndicator()),
|
||||
|
||||
@@ -11,6 +11,7 @@ import 'features/auth/presentation/approve_qr_screen.dart';
|
||||
import 'features/auth/presentation/qr_scan_screen.dart';
|
||||
import 'features/auth/presentation/forgot_password_screen.dart';
|
||||
import 'features/auth/presentation/reset_password_screen.dart';
|
||||
import 'features/auth/presentation/error_screen.dart';
|
||||
import 'features/dashboard/presentation/dashboard_screen.dart';
|
||||
import 'features/admin/presentation/user_management_screen.dart';
|
||||
import 'features/profile/presentation/pages/profile_page.dart';
|
||||
@@ -19,6 +20,7 @@ import 'core/services/auth_token_store.dart';
|
||||
import 'core/services/logger_service.dart';
|
||||
import 'core/notifiers/auth_notifier.dart';
|
||||
import 'package:logging/logging.dart';
|
||||
import 'features/auth/presentation/consent_screen.dart';
|
||||
|
||||
final _log = Logger('Main');
|
||||
|
||||
@@ -90,9 +92,29 @@ final _router = GoRouter(
|
||||
GoRoute(
|
||||
path: '/signin',
|
||||
builder: (context, state) {
|
||||
_routerLogger.info("Navigating to /signin");
|
||||
final loginChallenge = state.uri.queryParameters['login_challenge'];
|
||||
_routerLogger.info("Navigating to /signin with login_challenge: $loginChallenge");
|
||||
return LoginScreen(key: state.pageKey, loginChallenge: loginChallenge);
|
||||
},
|
||||
),
|
||||
GoRoute(
|
||||
path: '/login',
|
||||
builder: (context, state) {
|
||||
_routerLogger.info("Navigating to /login");
|
||||
return LoginScreen(key: state.pageKey);
|
||||
}
|
||||
},
|
||||
),
|
||||
GoRoute(
|
||||
path: '/consent',
|
||||
builder: (BuildContext context, GoRouterState state) {
|
||||
final consentChallenge = state.uri.queryParameters['consent_challenge'];
|
||||
if (consentChallenge == null) {
|
||||
_routerLogger.warning("Consent screen loaded without a challenge.");
|
||||
return const Scaffold(body: Center(child: Text('Error: Consent challenge is missing.')));
|
||||
}
|
||||
_routerLogger.info("Navigating to /consent with challenge.");
|
||||
return ConsentScreen(consentChallenge: consentChallenge);
|
||||
},
|
||||
),
|
||||
GoRoute(
|
||||
path: '/signup',
|
||||
@@ -101,6 +123,13 @@ final _router = GoRouter(
|
||||
return const SignupScreen();
|
||||
},
|
||||
),
|
||||
GoRoute(
|
||||
path: '/registration',
|
||||
builder: (context, state) {
|
||||
_routerLogger.info("Navigating to /registration");
|
||||
return const SignupScreen();
|
||||
},
|
||||
),
|
||||
GoRoute(
|
||||
path: '/verify',
|
||||
builder: (context, state) {
|
||||
@@ -116,6 +145,13 @@ final _router = GoRouter(
|
||||
return LoginScreen(key: state.pageKey, verificationToken: token);
|
||||
},
|
||||
),
|
||||
GoRoute(
|
||||
path: '/verification',
|
||||
builder: (context, state) {
|
||||
_routerLogger.info("Navigating to /verification");
|
||||
return LoginScreen(key: state.pageKey);
|
||||
},
|
||||
),
|
||||
GoRoute(
|
||||
path: '/l/:shortCode',
|
||||
builder: (context, state) {
|
||||
@@ -131,6 +167,13 @@ final _router = GoRouter(
|
||||
return const ForgotPasswordScreen();
|
||||
},
|
||||
),
|
||||
GoRoute(
|
||||
path: '/recovery',
|
||||
builder: (context, state) {
|
||||
_routerLogger.info("Navigating to /recovery");
|
||||
return const ForgotPasswordScreen();
|
||||
},
|
||||
),
|
||||
GoRoute(
|
||||
// Supports both /reset-password and /reset-password?token=...
|
||||
path: '/reset-password',
|
||||
@@ -141,6 +184,28 @@ final _router = GoRouter(
|
||||
return const ResetPasswordScreen();
|
||||
},
|
||||
),
|
||||
GoRoute(
|
||||
path: '/error',
|
||||
builder: (context, state) {
|
||||
_routerLogger.info("Navigating to /error");
|
||||
final params = state.uri.queryParameters;
|
||||
return ErrorScreen(
|
||||
errorId: params['id'],
|
||||
errorCode: params['error'],
|
||||
description: params['error_description'] ?? params['message'],
|
||||
);
|
||||
},
|
||||
),
|
||||
GoRoute(
|
||||
path: '/settings',
|
||||
builder: (context, state) {
|
||||
_routerLogger.info("Navigating to /settings (disabled)");
|
||||
return const ErrorScreen(
|
||||
errorCode: 'settings_disabled',
|
||||
description: '현재 계정 설정 화면은 준비 중입니다.',
|
||||
);
|
||||
},
|
||||
),
|
||||
GoRoute(
|
||||
path: '/approve',
|
||||
builder: (context, state) {
|
||||
@@ -181,12 +246,19 @@ final _router = GoRouter(
|
||||
// Public paths that don't require login
|
||||
final isPublicPath = path == '/signin' ||
|
||||
path == '/signup' ||
|
||||
path == '/login' ||
|
||||
path == '/registration' ||
|
||||
path == '/verify' ||
|
||||
path == '/verification' ||
|
||||
path.startsWith('/verify/') ||
|
||||
path == '/approve' ||
|
||||
path.startsWith('/ql/') ||
|
||||
path == '/forgot-password' ||
|
||||
path == '/reset-password';
|
||||
path == '/recovery' ||
|
||||
path == '/reset-password' ||
|
||||
path == '/error' ||
|
||||
path == '/settings' ||
|
||||
path == '/consent'; // Consent page is public
|
||||
|
||||
_routerLogger.fine("Redirect check - Path: $path, IsLoggedIn: $isLoggedIn");
|
||||
|
||||
@@ -197,7 +269,12 @@ final _router = GoRouter(
|
||||
|
||||
// If not logged in and trying to access a protected page, redirect to /signin
|
||||
if (!isLoggedIn) {
|
||||
_routerLogger.info("Not logged in, redirecting to /signin");
|
||||
_routerLogger.info("Not logged in, redirecting to /signin");
|
||||
// Preserve OIDC challenge if present
|
||||
final loginChallenge = state.uri.queryParameters['login_challenge'];
|
||||
if (loginChallenge != null) {
|
||||
return '/signin?login_challenge=$loginChallenge';
|
||||
}
|
||||
return '/signin';
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user