2fas-server/internal/common/push/client.go

82 lines
1.8 KiB
Go
Raw Permalink Normal View History

2022-12-31 10:22:38 +01:00
package push
import (
"context"
"encoding/json"
2023-05-29 20:03:01 +02:00
"io/ioutil"
"time"
2023-01-31 20:27:04 +01:00
firebase "firebase.google.com/go/v4"
"firebase.google.com/go/v4/messaging"
2023-01-30 19:59:42 +01:00
"github.com/twofas/2fas-server/internal/api/mobile/domain"
"github.com/twofas/2fas-server/internal/common/logging"
2022-12-31 10:22:38 +01:00
"google.golang.org/api/option"
)
type Pusher interface {
Send(ctx context.Context, message *messaging.Message) error
}
type FcmPushClient struct {
FcmMessaging *messaging.Client
}
func NewFcmPushClient(config *domain.FcmPushConfig) *FcmPushClient {
fileContent, err := ioutil.ReadAll(config.FcmApiServiceAccountFile)
if err != nil {
logging.Fatal(err)
}
opt := option.WithCredentialsJSON(fileContent)
app, err := firebase.NewApp(context.Background(), nil, opt)
if err != nil {
logging.WithField("error", err.Error()).Fatal("Error initializing FCM App")
}
client, err := app.Messaging(context.Background())
return &FcmPushClient{
FcmMessaging: client,
}
}
func (p *FcmPushClient) Send(ctx context.Context, message *messaging.Message) error {
data, _ := json.Marshal(message)
logging.WithFields(logging.Fields{
"notification": string(data),
}).Debug("Sending push notifications")
contextWithTimeout, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
response, err := p.FcmMessaging.Send(contextWithTimeout, message)
if err != nil {
return err
}
2023-05-29 20:03:01 +02:00
logging.Infof("FCM notification has been sent: %s", response)
2022-12-31 10:22:38 +01:00
return nil
}
type FakePushClient struct {
}
func NewFakePushClient() *FakePushClient {
return &FakePushClient{}
}
func (p *FakePushClient) Send(ctx context.Context, message *messaging.Message) error {
data, _ := json.Marshal(message)
logging.WithFields(logging.Fields{
"notification": string(data),
}).Debug("Sending fake push notifications")
return nil
}