Skip to content

Commit 6d7de1c

Browse files
authored
[#219] Sign in with Apple이 실패하는 현상을 해결한다 (#220)
* style: 인덴트 수정 * fix: 애플 관련 키 못찾는 현상 해결 * refactor: 어떤 키가 누락되었는지 더 로그를 자세히 띄우도록 개선
1 parent 306b1e3 commit 6d7de1c

2 files changed

Lines changed: 64 additions & 58 deletions

File tree

DevLog/Infra/Service/SocialLogin/AppleAuthenticationService.swift

Lines changed: 29 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -44,39 +44,39 @@ final class AppleAuthenticationService: AuthenticationService {
4444
logger.debug("Signing in with custom token")
4545
let result = try await Auth.auth().signIn(withCustomToken: customToken)
4646

47-
let changeRequest = result.user.createProfileChangeRequest()
48-
var displayName: String?
49-
50-
// 최초 사용자 가입 시 사용자 이름 설정
51-
if let fullName = credential.fullName {
52-
let formatter = PersonNameComponentsFormatter()
53-
formatter.style = .long
54-
let formattedName = formatter.string(from: fullName)
55-
if !formattedName.isEmpty {
56-
displayName = formattedName
47+
let changeRequest = result.user.createProfileChangeRequest()
48+
var displayName: String?
49+
50+
// 최초 사용자 가입 시 사용자 이름 설정
51+
if let fullName = credential.fullName {
52+
let formatter = PersonNameComponentsFormatter()
53+
formatter.style = .long
54+
let formattedName = formatter.string(from: fullName)
55+
if !formattedName.isEmpty {
56+
displayName = formattedName
57+
}
5758
}
58-
}
5959

60-
// 이미 가입된 사용자일 경우 Firestore에서 사용자 이름 가져오기
61-
if displayName == nil {
62-
let doc = try await store.document("users/\(result.user.uid)/userData/info").getDocument()
63-
displayName = doc.data()?["appleName"] as? String
64-
}
60+
// 이미 가입된 사용자일 경우 Firestore에서 사용자 이름 가져오기
61+
if displayName == nil {
62+
let doc = try await store.document("users/\(result.user.uid)/userData/info").getDocument()
63+
displayName = doc.data()?["appleName"] as? String
64+
}
6565

66-
// FirebaseAuth 사용자 프로필 업데이트
67-
changeRequest.displayName = displayName ?? ""
68-
changeRequest.photoURL = nil // Apple ID 프로필 사진 URL은 제공되지 않음
69-
try await changeRequest.commitChanges()
66+
// FirebaseAuth 사용자 프로필 업데이트
67+
changeRequest.displayName = displayName ?? ""
68+
changeRequest.photoURL = nil // Apple ID 프로필 사진 URL은 제공되지 않음
69+
try await changeRequest.commitChanges()
7070

71-
// FirebaseAuth 계정에 Apple ID 연결
72-
if !result.user.providerData.contains(where: { $0.providerID == providerID.rawValue }) {
73-
let appleCredential = OAuthProvider.credential(
74-
providerID: providerID,
75-
idToken: idTokenString,
76-
rawNonce: nonce
77-
)
78-
try await result.user.link(with: appleCredential)
79-
}
71+
// FirebaseAuth 계정에 Apple ID 연결
72+
if !result.user.providerData.contains(where: { $0.providerID == providerID.rawValue }) {
73+
let appleCredential = OAuthProvider.credential(
74+
providerID: providerID,
75+
idToken: idTokenString,
76+
rawNonce: nonce
77+
)
78+
try await result.user.link(with: appleCredential)
79+
}
8080

8181
let fcmToken = try await messaging.token()
8282

Firebase/functions/src/auth/apple.ts

Lines changed: 35 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,38 @@ interface AppleTokenPayload {
1919
auth_time?: number; // 인증 시간
2020
}
2121

22-
// Apple 설정 불러오기
23-
const teamId = process.env.APPLE_TEAM_ID;
24-
const clientId = process.env.APPLE_CLIENT_ID;
25-
const keyId = process.env.APPLE_KEY_ID;
26-
const privateKey = (process.env.APPLE_PRIVATE_KEY || "").replace(/\\n/g, "\n");
22+
function getAppleConfiguration() {
23+
const teamId = process.env.APPLE_TEAM_ID;
24+
const clientId = process.env.APPLE_CLIENT_ID;
25+
const keyId = process.env.APPLE_KEY_ID;
26+
const privateKey = (process.env.APPLE_PRIVATE_KEY || "").replace(/\\n/g, "\n");
27+
const configs = {
28+
APPLE_TEAM_ID: teamId,
29+
APPLE_CLIENT_ID: clientId,
30+
APPLE_KEY_ID: keyId,
31+
APPLE_PRIVATE_KEY: privateKey
32+
};
33+
const missingKeys = Object.entries(configs)
34+
.filter(([, value]) => !value)
35+
.map(([key]) => key);
36+
37+
if (0 < missingKeys.length) {
38+
console.error("Missing Apple configuration", {
39+
missingKeys
40+
});
41+
throw new HttpsError(
42+
'internal',
43+
`Missing Apple configuration for: ${missingKeys.join(", ")}`
44+
);
45+
}
46+
47+
return {
48+
teamId: teamId!,
49+
clientId: clientId!,
50+
keyId: keyId!,
51+
privateKey: privateKey!
52+
};
53+
}
2754

2855
export const requestAppleCustomToken = onCall({
2956
cors: true,
@@ -37,11 +64,6 @@ export const requestAppleCustomToken = onCall({
3764
throw new HttpsError('invalid-argument', 'ID token and authorization code are required');
3865
}
3966

40-
// Apple 설정 불러오기
41-
if (!teamId || !clientId || !keyId || !privateKey) {
42-
throw new HttpsError('internal', 'Missing Apple configuration');
43-
}
44-
4567
// // 1. Verify and decode the Apple ID token
4668
let decodedToken: AppleTokenPayload;
4769
try {
@@ -143,10 +165,6 @@ export const requestAppleRefreshToken = onCall({
143165
if (!authorizationCode || !uid) {
144166
throw new HttpsError("invalid-argument", "Authorization code and uid are required");
145167
}
146-
147-
if (!teamId || !clientId || !keyId || !privateKey) {
148-
throw new HttpsError("internal", "Missing Apple configuration");
149-
}
150168

151169
const refreshToken = await requestAppleRefreshTokenHelper(authorizationCode);
152170
console.log("appleRefreshToken:", refreshToken);
@@ -197,13 +215,7 @@ export const refreshAppleAccessToken = onCall({
197215
}
198216

199217
console.log("Successfully retrieved refresh token from Firestore");
200-
201-
if (!teamId || !clientId || !keyId || !privateKey) {
202-
throw new HttpsError(
203-
"internal",
204-
"Missing Apple configuration environment variables."
205-
);
206-
}
218+
const { teamId, clientId, keyId, privateKey } = getAppleConfiguration();
207219

208220
// Create client_secret JWT
209221
const clientSecret = jwt.sign({}, privateKey, {
@@ -265,15 +277,12 @@ export const revokeAppleAccessToken = onCall({
265277

266278
try {
267279
const { token } = request.data;
280+
const { teamId, clientId, keyId, privateKey } = getAppleConfiguration();
268281

269282
if (!token) {
270283
throw new HttpsError("invalid-argument", "Token is required");
271284
}
272285

273-
if (!teamId || !clientId || !keyId || !privateKey) {
274-
throw new HttpsError("internal", "Missing Apple configuration");
275-
}
276-
277286
// JWT 생성
278287
const clientSecret = jwt.sign({}, privateKey, {
279288
algorithm: "ES256",
@@ -323,10 +332,7 @@ export const revokeAppleAccessToken = onCall({
323332
});
324333

325334
export async function requestAppleRefreshTokenHelper(authorizationCode: string): Promise<string> {
326-
// Apple 설정 불러오기
327-
if (!teamId || !clientId || !keyId || !privateKey) {
328-
throw new HttpsError('internal', 'Missing Apple configuration');
329-
}
335+
const { teamId, clientId, keyId, privateKey } = getAppleConfiguration();
330336

331337
// JWT 생성
332338
const clientSecret = jwt.sign({}, privateKey, {

0 commit comments

Comments
 (0)