-
Notifications
You must be signed in to change notification settings - Fork 0
/
task_send_verify_email.go
78 lines (66 loc) · 2.42 KB
/
task_send_verify_email.go
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
package worker
import (
"context"
"encoding/json"
"fmt"
"github.com/hibiken/asynq"
"github.com/rs/zerolog/log"
db "github.com/stuartfranke/golang-backend-master-class/db/sqlc"
"github.com/stuartfranke/golang-backend-master-class/util"
)
const TaskSendVerifyEmail = "task:send_verify_email"
type PayloadSendVerifyEmail struct {
Username string `json:"username"`
}
func (distributor *RedisTaskDistributor) DistributeTaskSendVerifyEmail(
ctx context.Context,
payload *PayloadSendVerifyEmail,
opts ...asynq.Option,
) error {
jsonPayload, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("failed to marshal task payload: %w", err)
}
task := asynq.NewTask(TaskSendVerifyEmail, jsonPayload, opts...)
info, err := distributor.client.EnqueueContext(ctx, task)
if err != nil {
return fmt.Errorf("failed to enqueue task: %w", err)
}
log.Info().Str("type", task.Type()).Bytes("payload", task.Payload()).
Str("queue", info.Queue).Int("max_retry", info.MaxRetry).Msg("enqueued task")
return nil
}
func (processor *RedisTaskProcessor) ProcessTaskSendVerifyEmail(ctx context.Context, task *asynq.Task) error {
var payload PayloadSendVerifyEmail
if err := json.Unmarshal(task.Payload(), &payload); err != nil {
return fmt.Errorf("failed to unmarshal payload: %w", asynq.SkipRetry)
}
user, err := processor.store.GetUser(ctx, payload.Username)
if err != nil {
return fmt.Errorf("failed to get user: %w", err)
}
verifyEmail, err := processor.store.CreateVerifyEmail(ctx, db.CreateVerifyEmailParams{
Username: user.Username,
Email: user.Email,
SecretCode: util.RandomString(32),
})
if err != nil {
return fmt.Errorf("failed to create verify email: %w", err)
}
subject := "Welcome to Simple Bank"
// TODO: replace this URL with an environment variable that points to a front-end page
verifyUrl := fmt.Sprintf("http://localhost:8082/v1/verify_email?email_id=%d&secret_code=%s",
verifyEmail.ID, verifyEmail.SecretCode)
content := fmt.Sprintf(`Hello %s,<br/>
Thank you for registering with us!<br/>
Please <a href="%s">click here</a> to verify your email address.<br/>
`, user.FullName, verifyUrl)
to := []string{user.Email}
err = processor.mailer.SendEmail(subject, content, to, nil, nil, nil)
if err != nil {
return fmt.Errorf("failed to send verify email: %w", err)
}
log.Info().Str("type", task.Type()).Bytes("payload", task.Payload()).
Str("email", user.Email).Msg("processed task")
return nil
}