Skip to content

Commit e847680

Browse files
authored
Merge pull request #29 from GRACENOBLE/19-feat-integrate-firebase-cloud-messaging-for-push-notifications
feat(fcm): integrate Firebase Cloud Messaging for push notifications
2 parents 58f52df + a6e49b1 commit e847680

42 files changed

Lines changed: 2758 additions & 53 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/mobile-ci.yml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,9 @@ jobs:
3232
- name: Make gradlew executable
3333
run: chmod +x gradlew
3434

35+
- name: Write google-services.json
36+
run: echo '${{ secrets.GOOGLE_SERVICES_JSON }}' > app/google-services.json
37+
3538
- name: Lint
3639
run: ./gradlew lint
3740

‎backend/docs/_index.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,4 @@ The `docs` agent reads this index first to locate the right file before diving i
1818
| WebSocket (Hub, client, GET /ws, auth, wiring) | [websocket.md](websocket.md) | `internal/infrastructure/ws/`, `internal/transport/handlers/ws_handler.go`, `internal/transport/handlers/routes.go`, `internal/server/server.go`, `cmd/api/main.go` |
1919
| Background job queue (Asynq, task definitions, worker, Asynqmon UI) | [queue.md](queue.md) | `internal/usecase/enqueuer.go`, `internal/infrastructure/queue/tasks.go`, `internal/infrastructure/queue/client.go`, `internal/infrastructure/queue/worker.go`, `internal/infrastructure/queue/handlers.go`, `internal/transport/handlers/routes.go`, `cmd/api/main.go` |
2020
| Redis Streams event fan-out (producer, consumer, consumer groups) | [streams.md](streams.md) | `internal/infrastructure/streams/events.go`, `internal/infrastructure/streams/producer.go`, `internal/infrastructure/streams/consumer.go` |
21+
| Firebase Cloud Messaging — token storage, send API, FCM endpoints | [fcm.md](fcm.md) | `internal/domain/fcm_token.go`, `internal/usecase/notification.go`, `internal/infrastructure/database/postgres/fcm_token_repository.go`, `internal/transport/handlers/fcm_handler.go`, `pkg/firebase/app.go`, `pkg/firebase/messaging.go` |

‎backend/docs/auth.md‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@ sources:
55
- internal/usecase/auth_usecase.go
66
- internal/transport/middleware/auth.go
77
- internal/transport/handlers/auth_handler.go
8+
- internal/transport/handlers/handler.go
9+
- internal/transport/handlers/routes.go
10+
- internal/server/server.go
811
- pkg/firebase/admin.go
912
- internal/bootstrap/bootstrap.go
1013
---
@@ -94,17 +97,17 @@ func (h *Handler) MeHandler(c *gin.Context)
9497
- Returns `200 OK` with the token struct serialised as JSON.
9598
- Returns `401 Unauthorized` with `{"error": "unauthorized"}` if the context value is missing or of the wrong type (should not happen when `FirebaseAuth` is applied to the group).
9699
97-
The handler is registered on the `/api/v1` group in `RegisterRoutes`:
100+
The handler is registered on the `/api/v1` group in `RegisterRoutes`. The verifier is stored on the `Handler` struct (via `NewHandler`) and guarded inline:
98101
```go
99102
api := r.Group("/api/v1")
100-
if verifier != nil {
101-
api.Use(middleware.FirebaseAuth(verifier))
103+
if h.verifier != nil {
104+
api.Use(middleware.FirebaseAuth(h.verifier))
102105
}
103106
api.GET("/me", h.MeHandler)
104107
```
105108

106109
## Disabling auth in development
107110

108-
When `FIREBASE_PROJECT_ID` is not set `bootstrap.Run` skips Firebase initialisation and `app.Firebase` is `nil`. `server.NewServer` passes `app.Firebase` directly to `RegisterRoutes` as the `verifier` argument. When `verifier` is `nil` the `if verifier != nil` guard in `RegisterRoutes` skips `api.Use(middleware.FirebaseAuth(...))`, so `/api/v1/me` is reachable without a token.
111+
When `FIREBASE_PROJECT_ID` is not set `bootstrap.Run` skips Firebase initialisation and `app.Firebase` is `nil`. `server.NewServer` passes `app.Firebase` to `NewHandler` where it is stored as `h.verifier`. When `h.verifier` is `nil` the guard in `RegisterRoutes` skips `api.Use(middleware.FirebaseAuth(...))`, so `/api/v1/me` is reachable without a token.
109112

110113
To enable auth locally set both `FIREBASE_PROJECT_ID` and `FIREBASE_SERVICE_ACCOUNT_JSON` in `backend/.env`.

‎backend/docs/fcm.md‎

Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
---
2+
topic: fcm
3+
last_verified: 2026-06-16
4+
sources:
5+
- internal/domain/fcm_token.go
6+
- internal/usecase/notification.go
7+
- internal/infrastructure/database/postgres/fcm_token_repository.go
8+
- internal/infrastructure/database/postgres/fcm_token_repository_test.go
9+
- internal/transport/handlers/fcm_handler.go
10+
- internal/transport/handlers/fcm_handler_test.go
11+
- internal/transport/handlers/routes.go
12+
- internal/transport/handlers/handler.go
13+
- internal/server/server.go
14+
- internal/bootstrap/bootstrap.go
15+
- pkg/firebase/app.go
16+
- pkg/firebase/admin.go
17+
- pkg/firebase/messaging.go
18+
- internal/infrastructure/database/migrations/20260615220942_add_fcm_tokens.sql
19+
---
20+
21+
# Firebase Cloud Messaging (FCM)
22+
23+
FCM sends push notifications to Android, iOS, and web clients. The backend stores per-user device tokens and sends notifications via the Firebase Admin SDK using the FCM HTTP v1 API.
24+
25+
## Domain entity
26+
27+
`internal/domain/fcm_token.go`:
28+
```go
29+
type FCMToken struct {
30+
ID string
31+
UserID string
32+
Token string
33+
Platform string // "android" | "ios" | "web"
34+
CreatedAt time.Time
35+
}
36+
```
37+
38+
## Usecase interfaces
39+
40+
Both interfaces live in `internal/usecase/notification.go`.
41+
42+
```go
43+
// NotificationSender sends FCM push notifications via the Admin SDK.
44+
type NotificationSender interface {
45+
SendToToken(ctx context.Context, token, title, body string, data map[string]string) error
46+
SendMulticast(ctx context.Context, tokens []string, title, body string, data map[string]string) error
47+
}
48+
49+
// FCMTokenRepository persists device registration tokens per user.
50+
type FCMTokenRepository interface {
51+
SaveToken(ctx context.Context, userID, token, platform string) error
52+
GetTokensByUserID(ctx context.Context, userID string) ([]domain.FCMToken, error)
53+
DeleteToken(ctx context.Context, token string) error
54+
}
55+
```
56+
57+
`NotificationSender` is the narrow port used by any use case that needs to push a notification. `FCMTokenRepository` is the persistence port used by the HTTP handlers.
58+
59+
## pkg/firebase — shared app initialisation
60+
61+
`pkg/firebase/app.go` creates the single Firebase Admin SDK app instance:
62+
63+
```go
64+
func NewApp(ctx context.Context, projectID, credentialsJSON string) (*firebasesdk.App, error)
65+
```
66+
67+
The same `*firebasesdk.App` is passed to both `NewAuthClient` and `NewMessagingClient` so the SDK initialises only once per process. Calling `firebasesdk.NewApp` twice with default settings returns an error, hence the shared app pattern.
68+
69+
`pkg/firebase/admin.go` — `NewAuthClient(ctx, app)` now accepts the pre-created app instead of creating its own.
70+
71+
`pkg/firebase/messaging.go` — `NewMessagingClient(ctx, app)` wraps `*messaging.Client`:
72+
73+
```go
74+
func NewMessagingClient(ctx context.Context, app *firebasesdk.App) (usecase.NotificationSender, error)
75+
```
76+
77+
`SendMulticast` uses `client.SendEachForMulticast` and returns an error if any individual message fails.
78+
79+
## bootstrap.App
80+
81+
`internal/bootstrap/bootstrap.go` — `App` now carries `FCMSender usecase.NotificationSender`. Both Firebase clients share the same SDK app:
82+
83+
```go
84+
if cfg.FirebaseProjectID != "" {
85+
fbApp, _ := firebase.NewApp(ctx, cfg.FirebaseProjectID, cfg.FirebaseServiceAccountJSON)
86+
authClient, _ := firebase.NewAuthClient(ctx, fbApp)
87+
msgClient, _ := firebase.NewMessagingClient(ctx, fbApp)
88+
app.Firebase = authClient
89+
app.FCMSender = msgClient
90+
}
91+
```
92+
93+
When `FIREBASE_PROJECT_ID` is not set both fields are `nil` and FCM routes are not registered.
94+
95+
## Database — fcm_tokens table
96+
97+
Migration `20260615220942_add_fcm_tokens.sql`:
98+
```sql
99+
CREATE TABLE IF NOT EXISTS fcm_tokens (
100+
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
101+
user_id TEXT NOT NULL,
102+
token TEXT NOT NULL UNIQUE,
103+
platform TEXT NOT NULL,
104+
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
105+
);
106+
CREATE INDEX IF NOT EXISTS idx_fcm_tokens_user_id ON fcm_tokens(user_id);
107+
```
108+
109+
`SaveToken` uses an upsert (`ON CONFLICT (token) DO UPDATE`) so a physical device re-registering or switching accounts is handled atomically without a duplicate token.
110+
111+
## HTTP endpoints
112+
113+
Both routes are registered inside the `/api/v1` group and inherit the `FirebaseAuth` middleware when `h.verifier != nil`. They are only registered when `h.fcmTokenRepo != nil`:
114+
115+
```go
116+
if h.fcmTokenRepo != nil {
117+
api.POST("/fcm/register", h.RegisterFCMToken)
118+
api.DELETE("/fcm/unregister", h.UnregisterFCMToken)
119+
}
120+
```
121+
122+
### POST /api/v1/fcm/register
123+
124+
Request body:
125+
```json
126+
{ "token": "<fcm-registration-token>", "platform": "android|ios|web" }
127+
```
128+
129+
Reads `UID` from `*usecase.FirebaseToken` in the Gin context (set by `FirebaseAuth` middleware), then calls `SaveToken`. Returns `200 {"message": "token registered"}`.
130+
131+
### DELETE /api/v1/fcm/unregister
132+
133+
Request body:
134+
```json
135+
{ "token": "<fcm-registration-token>" }
136+
```
137+
138+
Calls `DeleteToken`. Returns `200 {"message": "token unregistered"}`. Designed to be called on logout.
139+
140+
## Wiring in server.go
141+
142+
```go
143+
fcmTokenRepo := postgres.NewFCMTokenRepository(app.DB)
144+
h := handlers.NewHandler(..., app.FCMSender, fcmTokenRepo)
145+
```
146+
147+
`NewFCMTokenRepository` always returns a valid repository backed by `app.DB`; the FCM routes are gated by `h.fcmTokenRepo != nil` on the router side, but since `NewFCMTokenRepository` is always called, the routes are always registered when the server starts. The `FirebaseAuth` middleware is the actual auth gate.
148+
149+
## Sending notifications from other use cases
150+
151+
Inject `usecase.NotificationSender` into any use case that needs to push a notification:
152+
153+
```go
154+
// Example: notify all user devices after a background job completes
155+
tokens, _ := fcmTokenRepo.GetTokensByUserID(ctx, userID)
156+
fcmTokens := make([]string, len(tokens))
157+
for i, t := range tokens { fcmTokens[i] = t.Token }
158+
_ = fcmSender.SendMulticast(ctx, fcmTokens, "Job done", "Your report is ready", nil)
159+
```
160+
161+
## Testing
162+
163+
**Handler unit tests** (`internal/transport/handlers/fcm_handler_test.go`): `mockFCMTokenRepo` implements `usecase.FCMTokenRepository`; no database or Firebase SDK involved.
164+
165+
**Repository integration tests** (`internal/infrastructure/database/postgres/fcm_token_repository_test.go`): use Testcontainers (real PostgreSQL). Each test calls `setupFCMTokensTable` to create the table and registers a cleanup to drop it. Shares the `testDB` global and `TestMain` from `health_repository_test.go` — do not add another `TestMain` to this package.
166+
167+
## Environment variables
168+
169+
| Variable | Required | Description |
170+
|---|---|---|
171+
| `FIREBASE_PROJECT_ID` | No | Firebase project ID (e.g. `my-app-12345`). Omit to disable Firebase entirely. |
172+
| `FIREBASE_SERVICE_ACCOUNT_JSON` | No | Raw service account JSON string. Omit to use Application Default Credentials. |
173+
174+
Both are already documented in `backend/.env.example`.

0 commit comments

Comments
 (0)