-
Notifications
You must be signed in to change notification settings - Fork 28
/
client.go
106 lines (92 loc) · 2.58 KB
/
client.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
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
package sms
import (
"errors"
"github.com/authgear/authgear-server/pkg/lib/config"
"github.com/authgear/authgear-server/pkg/util/log"
)
var ErrNoAvailableClient = errors.New("no available SMS client")
var ErrAmbiguousClient = errors.New("ambiguous SMS client")
type SendOptions struct {
Sender string
To string
Body string
}
type RawClient interface {
Send(from string, to string, body string) error
}
type Logger struct{ *log.Logger }
func NewLogger(lf *log.Factory) Logger { return Logger{lf.New("sms-client")} }
type Client struct {
Logger Logger
DevMode config.DevMode
MessagingConfig *config.MessagingConfig
FeatureTestModeSMSSuppressed config.FeatureTestModeSMSSuppressed
TestModeSMSConfig *config.TestModeSMSConfig
TwilioClient *TwilioClient
NexmoClient *NexmoClient
CustomClient *CustomClient
}
func (c *Client) Send(opts SendOptions) error {
if c.FeatureTestModeSMSSuppressed {
c.testModeSend(opts)
return nil
}
if c.TestModeSMSConfig.Enabled {
if r, ok := c.TestModeSMSConfig.MatchTarget(opts.To); ok && r.Suppressed {
c.testModeSend(opts)
return nil
}
}
if c.DevMode {
c.Logger.
WithField("recipient", opts.To).
WithField("sender", opts.Sender).
WithField("body", opts.Body).
Warn("skip sending SMS in development mode")
return nil
}
var client RawClient
switch c.MessagingConfig.SMSProvider {
case config.SMSProviderNexmo:
if c.NexmoClient == nil {
return ErrNoAvailableClient
}
client = c.NexmoClient
case config.SMSProviderTwilio:
if c.TwilioClient == nil {
return ErrNoAvailableClient
}
client = c.TwilioClient
case config.SMSProviderCustom:
if c.CustomClient == nil {
return ErrNoAvailableClient
}
client = c.CustomClient
default:
var availableClients []RawClient = []RawClient{}
if c.NexmoClient != nil {
availableClients = append(availableClients, c.NexmoClient)
}
if c.TwilioClient != nil {
availableClients = append(availableClients, c.TwilioClient)
}
if c.CustomClient != nil {
availableClients = append(availableClients, c.CustomClient)
}
if len(availableClients) == 0 {
return ErrNoAvailableClient
}
if len(availableClients) > 1 {
return ErrAmbiguousClient
}
client = availableClients[0]
}
return client.Send(opts.Sender, opts.To, opts.Body)
}
func (c *Client) testModeSend(opts SendOptions) {
c.Logger.
WithField("recipient", opts.To).
WithField("sender", opts.Sender).
WithField("body", opts.Body).
Warn("sending SMS is suppressed in test mode")
}