forked from NdoleStudio/httpsms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser_service.go
More file actions
476 lines (385 loc) · 17.8 KB
/
user_service.go
File metadata and controls
476 lines (385 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
package services
import (
"context"
"fmt"
"time"
"firebase.google.com/go/auth"
"github.com/NdoleStudio/httpsms/pkg/events"
"github.com/NdoleStudio/httpsms/pkg/emails"
"github.com/NdoleStudio/lemonsqueezy-go"
"github.com/NdoleStudio/httpsms/pkg/repositories"
"github.com/google/uuid"
"github.com/palantir/stacktrace"
"github.com/NdoleStudio/httpsms/pkg/entities"
"github.com/NdoleStudio/httpsms/pkg/telemetry"
)
// UserService is handles user requests
type UserService struct {
service
logger telemetry.Logger
tracer telemetry.Tracer
emailFactory emails.UserEmailFactory
mailer emails.Mailer
repository repositories.UserRepository
dispatcher *EventDispatcher
authClient *auth.Client
lemonsqueezyClient *lemonsqueezy.Client
}
// NewUserService creates a new UserService
func NewUserService(
logger telemetry.Logger,
tracer telemetry.Tracer,
repository repositories.UserRepository,
mailer emails.Mailer,
emailFactory emails.UserEmailFactory,
lemonsqueezyClient *lemonsqueezy.Client,
dispatcher *EventDispatcher,
authClient *auth.Client,
) (s *UserService) {
return &UserService{
logger: logger.WithService(fmt.Sprintf("%T", s)),
tracer: tracer,
mailer: mailer,
emailFactory: emailFactory,
repository: repository,
dispatcher: dispatcher,
authClient: authClient,
lemonsqueezyClient: lemonsqueezyClient,
}
}
// Get fetches or creates an entities.User
func (service *UserService) Get(ctx context.Context, source string, authUser entities.AuthContext) (*entities.User, error) {
ctx, span := service.tracer.Start(ctx)
defer span.End()
user, isNew, err := service.repository.LoadOrStore(ctx, authUser)
if err != nil {
msg := fmt.Sprintf("could not get [%T] with from [%+#v]", user, authUser)
return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
if isNew {
service.dispatchUserCreatedEvent(ctx, source, user)
}
return user, nil
}
func (service *UserService) dispatchUserCreatedEvent(ctx context.Context, source string, user *entities.User) {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
event, err := service.createEvent(events.UserAccountCreated, source, &events.UserAccountCreatedPayload{
UserID: user.ID,
Timestamp: time.Now().UTC(),
})
if err != nil {
msg := fmt.Sprintf("cannot create event [%s] for user [%s]", events.UserAccountCreated, user.ID)
ctxLogger.Error(stacktrace.Propagate(err, msg))
return
}
if err = service.dispatcher.Dispatch(ctx, event); err != nil {
msg := fmt.Sprintf("cannot dispatch [%s] event for user [%s]", event.Type(), user.ID)
ctxLogger.Error(stacktrace.Propagate(err, msg))
return
}
}
// GetByID fetches an entities.User
func (service *UserService) GetByID(ctx context.Context, userID entities.UserID) (*entities.User, error) {
ctx, span, _ := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
user, err := service.repository.Load(ctx, userID)
if err != nil {
msg := fmt.Sprintf("could not get [%T] with ID [%s]", user, userID)
return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
return user, nil
}
// UserUpdateParams are parameters for updating an entities.User
type UserUpdateParams struct {
Timezone *time.Location
ActivePhoneID *uuid.UUID
}
// Update an entities.User
func (service *UserService) Update(ctx context.Context, source string, authUser entities.AuthContext, params UserUpdateParams) (*entities.User, error) {
ctx, span := service.tracer.Start(ctx)
defer span.End()
ctxLogger := service.tracer.CtxLogger(service.logger, span)
user, isNew, err := service.repository.LoadOrStore(ctx, authUser)
if err != nil {
msg := fmt.Sprintf("could not get [%T] with from [%+#v]", user, authUser)
return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
if isNew {
service.dispatchUserCreatedEvent(ctx, source, user)
}
user.Timezone = params.Timezone.String()
user.ActivePhoneID = params.ActivePhoneID
if err = service.repository.Update(ctx, user); err != nil {
msg := fmt.Sprintf("cannot save user with id [%s]", user.ID)
return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
ctxLogger.Info(fmt.Sprintf("user saved with id [%s] in the userRepository", user.ID))
return user, nil
}
// UserNotificationUpdateParams are parameters for updating the notifications of a user
type UserNotificationUpdateParams struct {
MessageStatusEnabled bool
WebhookEnabled bool
HeartbeatEnabled bool
NewsletterEnabled bool
}
// UpdateNotificationSettings for an entities.User
func (service *UserService) UpdateNotificationSettings(ctx context.Context, userID entities.UserID, params *UserNotificationUpdateParams) (*entities.User, error) {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
user, err := service.repository.Load(ctx, userID)
if err != nil {
msg := fmt.Sprintf("could not load [%T] with ID [%s]", user, userID)
return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
user.NotificationWebhookEnabled = params.WebhookEnabled
user.NotificationHeartbeatEnabled = params.HeartbeatEnabled
user.NotificationMessageStatusEnabled = params.MessageStatusEnabled
user.NotificationNewsletterEnabled = params.NewsletterEnabled
if err = service.repository.Update(ctx, user); err != nil {
msg := fmt.Sprintf("cannot save user with id [%s] in [%T]", user.ID, service.repository)
return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
ctxLogger.Info(fmt.Sprintf("updated notification settings for [%T] with ID [%s] in the [%T]", user, user.ID, service.repository))
return user, nil
}
// RotateAPIKey for an entities.User
func (service *UserService) RotateAPIKey(ctx context.Context, source string, userID entities.UserID) (*entities.User, error) {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
user, err := service.repository.RotateAPIKey(ctx, userID)
if err != nil {
msg := fmt.Sprintf("could not rotate API key for [%T] with ID [%s]", user, userID)
return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
ctxLogger.Info(fmt.Sprintf("rotated the api key for [%T] with ID [%s] in the [%T]", user, user.ID, service.repository))
event, err := service.createEvent(events.UserAPIKeyRotated, source, &events.UserAPIKeyRotatedPayload{
UserID: user.ID,
Email: user.Email,
Timestamp: time.Now().UTC(),
Timezone: user.Timezone,
})
if err != nil {
msg := fmt.Sprintf("cannot create event [%s] for user [%s]", events.UserAPIKeyRotated, user.ID)
ctxLogger.Error(stacktrace.Propagate(err, msg))
return user, nil
}
if err = service.dispatcher.Dispatch(ctx, event); err != nil {
msg := fmt.Sprintf("cannot dispatch [%s] event for user [%s]", event.Type(), user.ID)
ctxLogger.Error(stacktrace.Propagate(err, msg))
return user, nil
}
return user, nil
}
// Delete an entities.User
func (service *UserService) Delete(ctx context.Context, source string, userID entities.UserID) error {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
user, err := service.repository.Load(ctx, userID)
if err != nil {
msg := fmt.Sprintf("cannot load user with ID [%s] from the [%T]", userID, service.repository)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
if !user.IsOnFreePlan() && user.SubscriptionRenewsAt != nil && user.SubscriptionRenewsAt.After(time.Now()) {
msg := fmt.Sprintf("cannot delete user with ID [%s] because they are have an active [%s] subscription which renews at [%s]", userID, user.SubscriptionName, user.SubscriptionRenewsAt)
return service.tracer.WrapErrorSpan(span, stacktrace.NewError(msg))
}
if err = service.repository.Delete(ctx, user); err != nil {
msg := fmt.Sprintf("could not delete user with ID [%s] from the [%T]", userID, service.repository)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
ctxLogger.Info(fmt.Sprintf("sucessfully deleted user with ID [%s] in the [%T]", userID, service.repository))
event, err := service.createEvent(events.UserAccountDeleted, source, &events.UserAccountDeletedPayload{
UserID: userID,
UserEmail: user.Email,
Timestamp: time.Now().UTC(),
})
if err != nil {
msg := fmt.Sprintf("cannot create event [%s] for user [%s]", events.UserAccountDeleted, userID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
if err = service.dispatcher.Dispatch(ctx, event); err != nil {
msg := fmt.Sprintf("cannot dispatch [%s] event for user [%s]", event.Type(), userID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
return nil
}
// SendAPIKeyRotatedEmail sends an email to an entities.User when the API key is rotated
func (service *UserService) SendAPIKeyRotatedEmail(ctx context.Context, payload *events.UserAPIKeyRotatedPayload) error {
ctx, span := service.tracer.Start(ctx)
defer span.End()
ctxLogger := service.tracer.CtxLogger(service.logger, span)
email, err := service.emailFactory.APIKeyRotated(payload.Email, payload.Timestamp, payload.Timezone)
if err != nil {
msg := fmt.Sprintf("cannot create api key rotated email for user [%s]", payload.UserID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
if err = service.mailer.Send(ctx, email); err != nil {
msg := fmt.Sprintf("canot create api key rotated email to user [%s]", payload.UserID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
ctxLogger.Info(fmt.Sprintf("api key rotated email sent successfully to [%s] with user ID [%s]", payload.Email, payload.UserID))
return nil
}
// UserSendPhoneDeadEmailParams are parameters for notifying a user when a phone is dead
type UserSendPhoneDeadEmailParams struct {
UserID entities.UserID
PhoneID uuid.UUID
Owner string
LastHeartbeatTimestamp time.Time
}
// SendPhoneDeadEmail sends an email to an entities.User when a phone is dead
func (service *UserService) SendPhoneDeadEmail(ctx context.Context, params *UserSendPhoneDeadEmailParams) error {
ctx, span := service.tracer.Start(ctx)
defer span.End()
ctxLogger := service.tracer.CtxLogger(service.logger, span)
user, err := service.repository.Load(ctx, params.UserID)
if err != nil {
msg := fmt.Sprintf("could not get [%T] with ID [%s]", user, params.UserID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
if !user.NotificationHeartbeatEnabled {
ctxLogger.Info(fmt.Sprintf("[%s] email notifications disabled for user [%s] with owner [%s]", events.EventTypePhoneHeartbeatOffline, params.UserID, params.Owner))
return nil
}
email, err := service.emailFactory.PhoneDead(user, params.LastHeartbeatTimestamp, params.Owner)
if err != nil {
msg := fmt.Sprintf("cannot create phone dead email for user [%s]", params.UserID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
if err = service.mailer.Send(ctx, email); err != nil {
msg := fmt.Sprintf("canot send phone dead notification to user [%s]", params.UserID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
ctxLogger.Info(fmt.Sprintf("phone dead notification sent successfully to [%s] about [%s]", user.Email, params.Owner))
return nil
}
// StartSubscription starts a subscription for an entities.User
func (service *UserService) StartSubscription(ctx context.Context, params *events.UserSubscriptionCreatedPayload) error {
ctx, span := service.tracer.Start(ctx)
defer span.End()
user, err := service.repository.Load(ctx, params.UserID)
if err != nil {
msg := fmt.Sprintf("could not get [%T] with with ID [%s]", user, params.UserID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
user.SubscriptionID = ¶ms.SubscriptionID
user.SubscriptionName = params.SubscriptionName
user.SubscriptionRenewsAt = ¶ms.SubscriptionRenewsAt
user.SubscriptionStatus = ¶ms.SubscriptionStatus
user.SubscriptionEndsAt = nil
if err = service.repository.Update(ctx, user); err != nil {
msg := fmt.Sprintf("could not update [%T] with with ID [%s] after update", user, params.UserID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
return nil
}
// InitiateSubscriptionCancel initiates the cancelling of a subscription on lemonsqueezy
func (service *UserService) InitiateSubscriptionCancel(ctx context.Context, userID entities.UserID) error {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
user, err := service.repository.Load(ctx, userID)
if err != nil {
msg := fmt.Sprintf("could not get [%T] with with ID [%s]", user, userID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
if _, _, err = service.lemonsqueezyClient.Subscriptions.Cancel(ctx, *user.SubscriptionID); err != nil {
msg := fmt.Sprintf("could not cancel subscription [%s] for [%T] with with ID [%s]", *user.SubscriptionID, user, user.ID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
ctxLogger.Info(fmt.Sprintf("cancelled subscription [%s] for user [%s]", *user.SubscriptionID, user.ID))
return nil
}
// GetSubscriptionUpdateURL initiates the cancelling of a subscription on lemonsqueezy
func (service *UserService) GetSubscriptionUpdateURL(ctx context.Context, userID entities.UserID) (url string, err error) {
ctx, span := service.tracer.Start(ctx)
defer span.End()
user, err := service.repository.Load(ctx, userID)
if err != nil {
msg := fmt.Sprintf("could not get [%T] with with ID [%s]", user, userID)
return "", service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
subscription, _, err := service.lemonsqueezyClient.Subscriptions.Get(ctx, *user.SubscriptionID)
if err != nil {
msg := fmt.Sprintf("could not get subscription [%s] for [%T] with with ID [%s]", *user.SubscriptionID, user, user.ID)
return url, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
return subscription.Data.Attributes.Urls.CustomerPortal, nil
}
// CancelSubscription starts a subscription for an entities.User
func (service *UserService) CancelSubscription(ctx context.Context, params *events.UserSubscriptionCancelledPayload) error {
ctx, span := service.tracer.Start(ctx)
defer span.End()
user, err := service.repository.Load(ctx, params.UserID)
if err != nil {
msg := fmt.Sprintf("could not get [%T] with with ID [%s]", user, params.UserID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
user.SubscriptionID = ¶ms.SubscriptionID
user.SubscriptionName = params.SubscriptionName
user.SubscriptionRenewsAt = nil
user.SubscriptionStatus = ¶ms.SubscriptionStatus
user.SubscriptionEndsAt = ¶ms.SubscriptionEndsAt
if err = service.repository.Update(ctx, user); err != nil {
msg := fmt.Sprintf("could not update [%T] with with ID [%s] after update", user, params.UserID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
return nil
}
// ExpireSubscription finishes a subscription for an entities.User
func (service *UserService) ExpireSubscription(ctx context.Context, params *events.UserSubscriptionExpiredPayload) error {
ctx, span := service.tracer.Start(ctx)
defer span.End()
user, err := service.repository.Load(ctx, params.UserID)
if err != nil {
msg := fmt.Sprintf("could not get [%T] with with ID [%s]", user, params.UserID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
user.SubscriptionID = nil
user.SubscriptionName = entities.SubscriptionNameFree
user.SubscriptionRenewsAt = nil
user.SubscriptionStatus = nil
user.SubscriptionEndsAt = nil
if err = service.repository.Update(ctx, user); err != nil {
msg := fmt.Sprintf("could not update [%T] with with ID [%s] after expired subscription update", user, params.UserID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
return nil
}
// UpdateSubscription updates a subscription for an entities.User
func (service *UserService) UpdateSubscription(ctx context.Context, params *events.UserSubscriptionUpdatedPayload) error {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
user, err := service.repository.Load(ctx, params.UserID)
if err != nil {
msg := fmt.Sprintf("could not get [%T] with with ID [%s]", user, params.UserID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
if params.SubscriptionStatus != "active" {
msg := fmt.Sprintf("subscription status is [%s] for [%T] with with ID [%s]", params.SubscriptionStatus, user, params.UserID)
ctxLogger.Info(msg)
return nil
}
user.SubscriptionID = ¶ms.SubscriptionID
user.SubscriptionName = params.SubscriptionName
user.SubscriptionEndsAt = params.SubscriptionEndsAt
user.SubscriptionRenewsAt = ¶ms.SubscriptionRenewsAt
user.SubscriptionStatus = ¶ms.SubscriptionStatus
if err = service.repository.Update(ctx, user); err != nil {
msg := fmt.Sprintf("could not update [%T] with with ID [%s] after subscription update", user, params.UserID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
return nil
}
// DeleteAuthUser deletes an entities.AuthContext from firebase
func (service *UserService) DeleteAuthUser(ctx context.Context, userID entities.UserID) error {
ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
if err := service.authClient.DeleteUser(ctx, userID.String()); err != nil {
msg := fmt.Sprintf("could not delete [entities.AuthContext] from firebase with ID [%s]", userID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
ctxLogger.Info(fmt.Sprintf("deleted [entities.AuthContext] from firebase for user with ID [%s]", userID))
return nil
}