Kakao 로그인을 SDK와 서버 커스텀 토큰으로 · sFPI 일 집계 직후 Stage 승급 판정
This commit is contained in:
@@ -1,11 +1,17 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:cloud_functions/cloud_functions.dart';
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:firebase_auth/firebase_auth.dart' as fb;
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:google_sign_in/google_sign_in.dart' as gsi;
|
||||
import 'package:kakao_flutter_sdk_user/kakao_flutter_sdk_user.dart' as kakao;
|
||||
import 'package:sign_in_with_apple/sign_in_with_apple.dart' as apple;
|
||||
|
||||
import '../../core/data/backend.dart';
|
||||
import '../../core/firebase/firebase_boot.dart';
|
||||
import 'auth.dart';
|
||||
import '../../core/i18n/app_locale.dart';
|
||||
@@ -199,7 +205,8 @@ final class AppleSignInProvider
|
||||
kIsWeb || defaultTargetPlatform == TargetPlatform.android;
|
||||
}
|
||||
|
||||
/// 카카오·LINE — Firebase Auth 의 OpenID Connect 제공자(`oidc.kakao` · `oidc.line`).
|
||||
/// LINE — Firebase Auth 의 OpenID Connect 제공자(`oidc.line`). 카카오도 이 경로였으나
|
||||
/// Android 앱 전환 문제로 [KakaoSignInProvider] 로 옮겼다(클래스는 제공자 무관이라 그대로 둔다).
|
||||
///
|
||||
/// 두 회사 모두 OIDC 표준(issuer `https://kauth.kakao.com` · `https://access.line.me`)을
|
||||
/// 지원해 Firebase 가 코드 교환·ID 토큰 검증까지 맡는다. 앱은 SDK 없이
|
||||
@@ -219,6 +226,7 @@ final class OidcSignInProvider implements SocialAuthProvider {
|
||||
this.provider, {
|
||||
required this.providerId,
|
||||
this.scopes = const [],
|
||||
this.androidParameters = const {},
|
||||
this.firebaseAuth,
|
||||
});
|
||||
|
||||
@@ -233,6 +241,12 @@ final class OidcSignInProvider implements SocialAuthProvider {
|
||||
/// KOE205 로 로그인 자체를 막는다.
|
||||
final List<String> scopes;
|
||||
|
||||
/// Android 에서만 인가 URL 에 붙일 파라미터. Android Custom Tab 은 다른 앱으로
|
||||
/// 넘어갔다 돌아오면 콜백이 일반 Chrome 탭에서 열려 Firebase 핸들러가
|
||||
/// 「missing initial state」로 끝난다 — 앱 전환을 막는 공식 파라미터를 여기 둔다.
|
||||
/// iOS 는 정상이라 건드리지 않는다.
|
||||
final Map<String, String> androidParameters;
|
||||
|
||||
/// 테스트 주입용. 기본은 [fb.FirebaseAuth.instance].
|
||||
final fb.FirebaseAuth? firebaseAuth;
|
||||
|
||||
@@ -248,6 +262,9 @@ final class OidcSignInProvider implements SocialAuthProvider {
|
||||
for (final scope in scopes) {
|
||||
p.addScope(scope);
|
||||
}
|
||||
if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) {
|
||||
p.setCustomParameters(androidParameters);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
@@ -256,8 +273,11 @@ final class OidcSignInProvider implements SocialAuthProvider {
|
||||
final missing = missingConfig;
|
||||
if (missing.isNotEmpty) return AuthNotConfigured(provider, missing);
|
||||
try {
|
||||
final result = await (firebaseAuth ?? fb.FirebaseAuth.instance)
|
||||
.signInWithProvider(authProvider);
|
||||
final result = await untilAbandoned(
|
||||
(firebaseAuth ?? fb.FirebaseAuth.instance).signInWithProvider(
|
||||
authProvider,
|
||||
),
|
||||
);
|
||||
return AuthSucceeded(_toAccount(result.user, provider));
|
||||
} on fb.FirebaseAuthException catch (error) {
|
||||
if (isWebFlowCancelled(error)) return const AuthCancelled();
|
||||
@@ -275,11 +295,190 @@ final class OidcSignInProvider implements SocialAuthProvider {
|
||||
}
|
||||
}
|
||||
|
||||
/// 카카오 네이티브 앱 키. `config/kakao.env` 를 `--dart-define-from-file` 로 넘긴다
|
||||
/// (같은 파일을 Android manifestPlaceholders · iOS xcconfig 가 읽는다).
|
||||
const kakaoNativeAppKey = String.fromEnvironment('FANUZU_KAKAO_NATIVE_APP_KEY');
|
||||
|
||||
/// 카카오 — 공식 SDK 로그인 + 서버 커스텀 토큰(`fnAuthKakao`). iOS·Android 같은 경로다.
|
||||
///
|
||||
/// Firebase OIDC(`oidc.kakao`) 웹 흐름은 Android 에서 「카카오톡으로 로그인」을 고르면
|
||||
/// 콜백이 Custom Tab 밖(일반 Chrome)에서 열려 「missing initial state」로 깨진다. 카카오에는
|
||||
/// 앱 전환을 막는 파라미터가 없어서, SDK 가 카카오톡(없으면 카카오계정)으로 로그인해 받은
|
||||
/// 액세스 토큰을 서버가 카카오 API 로 검증하고 커스텀 토큰을 내준다.
|
||||
///
|
||||
/// 서버는 사용자 제공자 정보에 `oidc.kakao` 를 그대로 남긴다 — OIDC 시절 가입자는 같은 UID 로
|
||||
/// 들어오고, [FirebaseAccountLinker.linkedAccounts] 도 지금처럼 「연결됨」을 그린다.
|
||||
final class KakaoSignInProvider implements SocialAuthProvider {
|
||||
KakaoSignInProvider({
|
||||
Future<String> Function()? accessToken,
|
||||
Future<Map<String, dynamic>> Function(Map<String, dynamic> payload)?
|
||||
exchange,
|
||||
this.firebaseAuth,
|
||||
this.nativeAppKey = kakaoNativeAppKey,
|
||||
}) : _accessToken = accessToken ?? _sdkAccessToken,
|
||||
_exchange = exchange ?? _callServer;
|
||||
|
||||
final Future<String> Function() _accessToken;
|
||||
final Future<Map<String, dynamic>> Function(Map<String, dynamic>) _exchange;
|
||||
|
||||
/// 테스트 주입용. 기본은 [fb.FirebaseAuth.instance].
|
||||
final fb.FirebaseAuth? firebaseAuth;
|
||||
final String nativeAppKey;
|
||||
|
||||
static Future<void>? _init;
|
||||
|
||||
@override
|
||||
SocialProvider get provider => SocialProvider.kakao;
|
||||
|
||||
@override
|
||||
bool get isLive => true;
|
||||
|
||||
@override
|
||||
List<String> get missingConfig => [
|
||||
if (!FirebaseBoot.isLive) ...FirebaseBoot.missingLabels,
|
||||
if (nativeAppKey.isEmpty) '카카오 네이티브 앱 키',
|
||||
];
|
||||
|
||||
fb.FirebaseAuth get _auth => firebaseAuth ?? fb.FirebaseAuth.instance;
|
||||
|
||||
/// 카카오톡이 있으면 카카오톡, 없거나 실패하면 카카오계정(공식 가이드 순서).
|
||||
/// 사용자 취소(`CANCELED`)는 계정 로그인으로 넘기지 않고 그대로 던진다.
|
||||
static Future<String> _sdkAccessToken() async {
|
||||
await (_init ??= kakao.KakaoSdk.init(nativeAppKey: kakaoNativeAppKey));
|
||||
final api = kakao.UserApi.instance;
|
||||
if (await kakao.isKakaoTalkInstalled()) {
|
||||
try {
|
||||
return (await api.loginWithKakaoTalk()).accessToken;
|
||||
} on PlatformException catch (error) {
|
||||
if (error.code == 'CANCELED') rethrow;
|
||||
}
|
||||
}
|
||||
return (await api.loginWithKakaoAccount()).accessToken;
|
||||
}
|
||||
|
||||
static Future<Map<String, dynamic>> _callServer(
|
||||
Map<String, dynamic> payload,
|
||||
) async {
|
||||
final result = await FirebaseFunctions.instanceFor(
|
||||
region: Backend.region,
|
||||
).httpsCallable('fnAuthKakao').call<Object?>(payload);
|
||||
final data = result.data;
|
||||
return data is Map ? Map<String, dynamic>.from(data) : const {};
|
||||
}
|
||||
|
||||
@override
|
||||
Future<AuthOutcome> signIn() => _run(AuthFlow.signIn, () async {
|
||||
final data = await _exchange({'accessToken': await _accessToken()});
|
||||
final result = await _auth.signInWithCustomToken(data['token'] as String);
|
||||
return AuthSucceeded(_toAccount(result.user, provider));
|
||||
});
|
||||
|
||||
/// SNS 연동 — 로그인한 UID 에 카카오를 붙인다. 「동일 이메일만 연동」은 서버가 붙이기 전에 본다.
|
||||
Future<AuthOutcome> link(fb.User user) => _run(AuthFlow.link, () async {
|
||||
await _exchange({'accessToken': await _accessToken(), 'link': true});
|
||||
await user.reload();
|
||||
return AuthSucceeded(_toAccount(_auth.currentUser ?? user, provider));
|
||||
});
|
||||
|
||||
Future<AuthOutcome> _run(
|
||||
AuthFlow flow,
|
||||
Future<AuthOutcome> Function() body,
|
||||
) async {
|
||||
final missing = missingConfig;
|
||||
if (missing.isNotEmpty) return AuthNotConfigured(provider, missing);
|
||||
try {
|
||||
return await body();
|
||||
} on PlatformException catch (error) {
|
||||
if (error.code == 'CANCELED') return const AuthCancelled();
|
||||
debugPrint('[KakaoSignInProvider] sdk failed: ${error.code}');
|
||||
return AuthFailed('E-AUTH-03', appL10n.authSocialFailed);
|
||||
} on kakao.KakaoAuthException catch (error) {
|
||||
// 동의 화면에서 「취소」.
|
||||
if (error.error == kakao.AuthErrorCause.accessDenied) {
|
||||
return const AuthCancelled();
|
||||
}
|
||||
return AuthFailed('E-AUTH-03', appL10n.authSocialFailed);
|
||||
} on FirebaseFunctionsException catch (error) {
|
||||
final details = error.details;
|
||||
final code = details is Map && details['code'] is String
|
||||
? details['code'] as String
|
||||
: 'E-AUTH-03';
|
||||
return AuthFailed(code, switch (code) {
|
||||
_ when details is Map && details['reason'] == 'different-email' =>
|
||||
appL10n.authDifferentEmail,
|
||||
'E-AUTH-08' => appL10n.authCredentialInUse,
|
||||
'E-AUTH-09' => appL10n.authAlreadyLinked,
|
||||
_ =>
|
||||
flow == AuthFlow.link
|
||||
? appL10n.authLinkFailed
|
||||
: appL10n.authSocialFailed,
|
||||
});
|
||||
} on fb.FirebaseAuthException catch (error) {
|
||||
return AuthFailed(authCatalogCode(error), authMessage(error, flow: flow));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> signOut() async {
|
||||
// SDK 를 한 번도 띄우지 않았으면 지울 카카오 토큰도 없다.
|
||||
if (_init == null) return;
|
||||
try {
|
||||
await kakao.UserApi.instance.logout();
|
||||
} on Object catch (error) {
|
||||
// 토큰이 이미 만료·폐기됐어도 SDK 는 로컬 토큰을 지운다. 로그아웃을 막을 이유가 없다.
|
||||
debugPrint('[KakaoSignInProvider] logout: ${error.runtimeType}');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 사용자가 인가 웹 화면을 닫았다. Android 는 `canceled`, iOS 는 `cancelled` 철자다.
|
||||
bool isWebFlowCancelled(fb.FirebaseAuthException error) =>
|
||||
error.code == 'web-context-canceled' ||
|
||||
error.code == 'web-context-cancelled';
|
||||
|
||||
/// Android 에서 웹 인가 흐름이 결과 없이 버려졌으면 취소(`web-context-canceled`)로 끝낸다.
|
||||
///
|
||||
/// 콜백이 Custom Tab 밖(일반 Chrome)에서 열리면 Firebase 의 대기 Task 가 영영
|
||||
/// 끝나지 않아 로그인 버튼이 잠긴다. 앱이 포그라운드로 돌아온 뒤 [grace] 안에
|
||||
/// 결과가 없으면 사용자가 흐름을 버린 것으로 보고 기존 취소 경로([isWebFlowCancelled])로
|
||||
/// 넘긴다. 정상 완료는 돌아온 직후 토큰 교환 한 번이라 [grace] 안에 끝난다.
|
||||
/// iOS 는 SFSafariViewController 가 취소를 스스로 알려 주므로 그대로 둔다.
|
||||
///
|
||||
/// ponytail: 고정 대기 시간. 망이 아주 느려 [grace] 를 넘기면 취소로 보이지만
|
||||
/// Firebase 세션은 나중에 열리므로 authStateChanges 가 따라잡는다.
|
||||
Future<T> untilAbandoned<T>(
|
||||
Future<T> flow, {
|
||||
Duration grace = const Duration(seconds: 8),
|
||||
}) {
|
||||
if (kIsWeb || defaultTargetPlatform != TargetPlatform.android) return flow;
|
||||
final done = Completer<T>();
|
||||
Timer? timer;
|
||||
final listener = AppLifecycleListener(
|
||||
onStateChange: (state) {
|
||||
timer?.cancel();
|
||||
if (state != AppLifecycleState.resumed) return;
|
||||
timer = Timer(grace, () {
|
||||
if (done.isCompleted) return;
|
||||
done.completeError(
|
||||
fb.FirebaseAuthException(code: 'web-context-canceled'),
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
flow.then(
|
||||
(value) {
|
||||
if (!done.isCompleted) done.complete(value);
|
||||
},
|
||||
onError: (Object error, StackTrace stack) {
|
||||
if (!done.isCompleted) done.completeError(error, stack);
|
||||
},
|
||||
);
|
||||
return done.future.whenComplete(() {
|
||||
timer?.cancel();
|
||||
listener.dispose();
|
||||
});
|
||||
}
|
||||
|
||||
/// Apple Service ID와 callback URL은 비밀값이 아니지만 환경별 값이다.
|
||||
/// 저장소에 임시 상수를 박지 않고 빌드 시 `--dart-define`으로만 받는다.
|
||||
apple.WebAuthenticationOptions? appleWebAuthenticationOptionsFromEnvironment() {
|
||||
|
||||
Reference in New Issue
Block a user