Skip to content

[#130] Firebase로 dueDate가 하루 남은 Todo에 대해서 해당 계정으로 푸시 알람을 보내고 저장하는 기능을 구현한다#137

Merged
opficdev merged 8 commits intodevelopfrom
feat/#130-Todo-PushNotification
Feb 26, 2026
Merged

[#130] Firebase로 dueDate가 하루 남은 Todo에 대해서 해당 계정으로 푸시 알람을 보내고 저장하는 기능을 구현한다#137
opficdev merged 8 commits intodevelopfrom
feat/#130-Todo-PushNotification

Conversation

@opficdev
Copy link
Owner

@opficdev opficdev self-assigned this Feb 26, 2026
@gemini-code-assist
Copy link

Summary of Changes

Hello @opficdev, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

이 Pull Request는 Firebase를 활용하여 마감일이 하루 남은 할 일에 대한 푸시 알림 기능을 전면적으로 개선합니다. 기존의 개별 할 일 변경 기반 스케줄링 방식에서 사용자별 타임존을 고려한 주기적인 배치 스케줄링 방식으로 전환하여, 모든 사용자에게 정확한 현지 시간에 맞춰 알림이 전송되도록 합니다. 또한, 중복 알림 방지, 알림 기록의 안정성 강화, 그리고 사용자 데이터 저장 로직의 개선을 통해 전반적인 알림 시스템의 신뢰성과 사용자 경험을 향상시킵니다.

Highlights

  • 할 일 알림 스케줄링 방식 변경: 개별 할 일 문서 변경 시 트리거되던 방식에서 5분마다 실행되는 배치 작업으로 전환하여 모든 사용자에게 마감일이 하루 남은 할 일을 일괄적으로 확인하고 알림을 예약하도록 변경되었습니다.
  • 사용자별 타임존 지원: 사용자의 현재 타임존 정보를 저장하고, 이를 기반으로 알림 발송 시간을 계산하여 각 사용자의 현지 시간에 맞춰 알림이 전송되도록 개선되었습니다.
  • 중복 알림 방지 및 알림 기록 강화: 동일한 할 일에 대해 중복 알림이 발송되는 것을 방지하는 로직이 추가되었으며, 푸시 알림 발송 전에 Firestore에 알림 기록을 먼저 저장하도록 하여 안정성을 높였습니다.
  • 사용자 데이터 저장 로직 개선: 사용자 로그인 시 타임존 정보를 저장하고, 푸시 알림 설정의 초기값을 기존 설정이 없을 경우에만 적용하도록 하여 데이터 일관성을 확보했습니다.
  • 푸시 알림 발송 로직 견고화: 푸시 알림 발송 실패 시에도 Firestore에 알림 기록은 유지되도록 예외 처리가 강화되었습니다.
Changelog
  • DevLog/App/Delegate/AppDelegate.swift
    • FirebaseAuth 및 FirebaseFirestore 모듈을 임포트했습니다.
    • 앱이 활성화될 때 현재 로그인된 사용자의 타임존을 Firestore에 저장하는 updateUserTimeZone() 함수를 추가하고 호출했습니다.
  • DevLog/Infra/Service/UserService.swift
    • 사용자 데이터 초기화 로직을 개선했습니다.
    • 사용자 설정 문서가 존재하지 않을 경우에만 푸시 알림 관련 초기 설정을 적용하도록 변경했습니다.
    • Firestore 데이터 쓰기 작업을 async let을 사용하여 병렬로 처리하도록 최적화했습니다.
    • 사용자 로그인 시 timeZone 정보를 settings 컬렉션에 저장하도록 추가했습니다.
  • Firebase/functions/src/fcm/notification.ts
    • Cloud Tasks의 재시도 횟수와 초당 처리율 제한을 조정했습니다.
    • 푸시 알림 페이로드에 todoId, todoKind, dueDateKey 필드를 추가하고 유효성 검사를 강화했습니다.
    • 사용자 설정에서 푸시 알림 허용 여부를 확인하고, 비활성화된 경우 알림 발송을 중단하도록 했습니다.
    • 동일한 할 일에 대한 중복 알림 발송을 방지하는 로직을 추가했습니다.
    • 푸시 알림 발송 전에 Firestore에 알림 기록을 먼저 저장하도록 변경했습니다.
    • FCM 토큰이 없는 경우에도 Firestore 기록은 유지되도록 경고 메시지를 수정했습니다.
    • FCM 메시지에 todoID와 todoKind를 포함하는 data 페이로드를 추가했습니다.
    • 푸시 알림 발송 실패 시 오류를 로깅하고 재시도하지 않도록 예외 처리 로직을 수정했습니다.
  • Firebase/functions/src/fcm/schedule.ts
    • 할 일 알림 스케줄링 방식을 onDocumentWritten에서 onSchedule (5분마다 실행)로 변경했습니다.
    • 모든 사용자를 순회하며 각 사용자의 설정된 알림 시간과 타임존을 기반으로 마감일이 하루 남은 할 일을 조회하도록 로직을 전면 개편했습니다.
    • 타임존 변환, 날짜 계산, 시간대별 알림 창 확인 등 복잡한 날짜/시간 처리 로직을 위한 여러 헬퍼 함수를 추가했습니다.
    • 조회된 할 일에 대해 sendPushNotification Cloud Task를 예약하도록 구현했습니다.
    • 오류 직렬화 및 상세 로깅을 통해 오류 처리 기능을 강화했습니다.
Activity
  • 이 Pull Request는 이슈 #130에서 논의된 Firebase를 이용한 할 일 마감일 푸시 알림 기능을 구현했습니다.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

이 Pull Request는 Firebase를 사용하여 마감일이 하루 남은 Todo에 대한 푸시 알림을 보내고 저장하는 기능을 구현합니다. 특히 schedule.ts의 리팩토링을 통해 타임존을 고려한 알림 스케줄링을 가능하게 하여 사용자 경험을 향상시켰습니다. 하지만 Firebase Cloud Functions 구현에는 중요한 보안 및 확장성 문제가 존재합니다. 알림 디스패처는 Firestore 경로 주입에 취약하며, 스케줄러는 전체 사용자 컬렉션을 스캔하는 비효율적인 폴링 메커니즘을 사용하여 애플리케이션 확장 시 서비스 거부(DoS) 위험을 초래합니다. 전반적으로 이 PR은 Todo 알림 시스템의 핵심 기능을 추가하고 기존 로직을 크게 개선했지만, 이러한 보안 및 성능 문제를 해결하는 것이 중요합니다.

Comment on lines 78 to 85
let settingsDocument = try await settingsRef.getDocument()
if !settingsDocument.exists {
try await settingsRef.setData([
"allowPushNotification": true,
"pushNotificationHour": 9,
"pushNotificationMinute": 0
], merge: true)
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

settingsTimeZoneUpdatesettingsReftimeZone을 병합(merge)하여 설정하는 async let으로 실행됩니다. 이후 settingsDocument.exists를 확인하여 문서가 존재하지 않을 경우 allowPushNotification, pushNotificationHour, pushNotificationMinute를 설정합니다. 이 과정에서 settingsTimeZoneUpdate가 먼저 문서를 생성하고, 그 사이에 settingsRef.getDocument()가 호출되면 settingsDocument.existstrue가 되어 기본 푸시 알림 설정이 누락될 수 있는 경쟁 조건(race condition)이 발생합니다. 신규 사용자의 경우 푸시 알림 기본 설정이 적용되지 않을 수 있는 심각한 버그로 이어질 수 있습니다. settingsRef에 대한 초기 쓰기 작업을 하나의 setData 호출로 통합하여 모든 기본 설정이 함께 적용되도록 하는 것이 안전합니다.

Suggested change
let settingsDocument = try await settingsRef.getDocument()
if !settingsDocument.exists {
try await settingsRef.setData([
"allowPushNotification": true,
"pushNotificationHour": 9,
"pushNotificationMinute": 0
], merge: true)
}
let settingsDocument = try await settingsRef.getDocument()
if !settingsDocument.exists {
try await settingsRef.setData([
"allowPushNotification": true,
"pushNotificationHour": 9,
"pushNotificationMinute": 0,
"timeZone": TimeZone.autoupdatingCurrent.identifier
], merge: true)
} else {
// 문서가 이미 존재하면 timeZone만 업데이트
try await settingsRef.setData(["timeZone": TimeZone.autoupdatingCurrent.identifier], merge: true)
}

Comment on lines 32 to 34
var userField: [String: Any] = [
"statusMsg": "",
"lastLogin": FieldValue.serverTimestamp()
"currentProvider": response.providerID
]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

이전 코드에서는 userField 초기화 시 lastLogin 필드를 FieldValue.serverTimestamp()로 설정하여 사용자의 마지막 로그인 시간을 기록했습니다. 현재 변경 사항에서는 이 필드가 완전히 제거되어 더 이상 업데이트되지 않습니다. lastLogin 필드가 중요한 사용자 추적 데이터였다면, 이 변경은 데이터 추적의 회귀로 이어질 수 있습니다. updatedAt 필드와는 다른 목적으로 사용될 수 있으므로, lastLogin 필드의 업데이트를 다시 추가하는 것을 고려해 주세요.

Suggested change
var userField: [String: Any] = [
"statusMsg": "",
"lastLogin": FieldValue.serverTimestamp()
"currentProvider": response.providerID
]
var userField: [String: Any] = [
"currentProvider": response.providerID,
"lastLogin": FieldValue.serverTimestamp()
]

Comment on lines +34 to +41
const settingsDoc = await admin.firestore().doc(`users/${userId}/userData/settings`).get();
const allowPushNotification = settingsDoc.data()?.allowPushNotification ?? true;
if (!allowPushNotification) {
return;
}

const notificationDocId = `${todoId}_${dueDateKey}`;
const notificationDocRef = admin.firestore().doc(`users/${userId}/notifications/${notificationDocId}`);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-medium medium

The sendPushNotification function uses userId and todoId from the task payload to construct Firestore document paths without sanitization. If an attacker can trigger this function with arbitrary data (e.g., via a misconfigured Cloud Task or a leaked service account key), they could potentially read from or write to arbitrary Firestore collections by using path traversal characters (like /) in the userId or todoId fields. This is a classic path injection vulnerability in the context of Firestore document paths.

const queue = getFunctions().taskQueue(`locations/${LOCATION}/functions/sendPushNotification`);
let usersSnapshot: FirebaseFirestore.QuerySnapshot<FirebaseFirestore.DocumentData>;
try {
usersSnapshot = await admin.firestore().collection("users").get();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-medium medium

The scheduleTodoReminder function performs a full scan of the users collection every 5 minutes. This approach does not scale and will lead to function timeouts, high memory usage, and significant Firestore costs as the number of users grows. An attacker could exploit this by creating a large number of accounts, effectively disabling the notification system for all users and causing a Denial of Service (DoS). A more scalable approach would be to use Cloud Tasks to schedule individual notifications when a todo is created or updated, or to use a more targeted query to find users who need notifications.

Comment on lines +92 to +94
} catch {
print("Failed to update timeZone: \(error)")
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

에러 발생 시 print 문을 사용하는 것은 프로덕션 환경에서 적절한 로깅 방식이 아닙니다. 에러를 추적하고 디버깅하기 위해 전용 로깅 시스템(예: Crashlytics, Firebase Analytics의 커스텀 이벤트 등)을 사용하는 것이 좋습니다.

Suggested change
} catch {
print("Failed to update timeZone: \(error)")
}
print("Failed to update timeZone: \(error)") // TODO: 프로덕션 환경에 맞는 로깅 시스템으로 교체

}

const notificationData = {
title: "Todo 알림",

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

이전 코드에서는 notificationDatatitle 필드가 req.data.title에서 동적으로 가져왔습니다. 하지만 현재 변경 사항에서는 "Todo 알림"으로 하드코딩되어 있습니다. 만약 알림 제목이 항상 "Todo 알림"으로 고정되어야 한다면 괜찮지만, 다양한 종류의 알림에 따라 제목을 다르게 설정할 필요가 있다면 req.data.title을 다시 사용하는 것이 좋습니다.

Suggested change
title: "Todo 알림",
title: title, // req.data.title 사용

@opficdev opficdev merged commit aef3d86 into develop Feb 26, 2026
1 check passed
@opficdev opficdev deleted the feat/#130-Todo-PushNotification branch February 26, 2026 08:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Firebase로 dueDate가 곧 끝나가는 Todo에 대해서 해당 계정으로 푸시 알람을 보내는 기능을 구현한다

1 participant