-
Notifications
You must be signed in to change notification settings - Fork 13
/
subscriptionnotification.go
251 lines (213 loc) · 7.61 KB
/
subscriptionnotification.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
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
package notify
import (
"encoding/json"
"fmt"
"strings"
sasl "github.com/emersion/go-sasl"
smtp "github.com/emersion/go-smtp"
coreapi "github.com/Axway/agent-sdk/pkg/api"
"github.com/Axway/agent-sdk/pkg/apic"
corecfg "github.com/Axway/agent-sdk/pkg/config"
emailtemplate "github.com/Axway/agent-sdk/pkg/notify/template"
utilerrors "github.com/Axway/agent-sdk/pkg/util/errors"
"github.com/Axway/agent-sdk/pkg/util/log"
)
//TODO
/*
1. Search for comment "DEPRECATED to be removed on major release"
2. Remove deprecated code left from APIGOV-19751
*/
//SubscriptionNotification - the struct that is sent to the notification and used to fill in email templates
type SubscriptionNotification struct {
CatalogItemID string `json:"catalogItemId"`
CatalogItemURL string `json:"catalogItemUrl"`
CatalogItemName string `json:"catalogItemName"`
Action apic.SubscriptionState `json:"action"`
Email string `json:"email,omitempty"`
Message string `json:"message,omitempty"`
Key string `json:"key,omitempty"`
ClientID string `json:"clientID,omitempty"`
ClientSecret string `json:"clientSecret,omitempty"`
AuthTemplate string `json:"authtemplate,omitempty"`
IsAPIKey bool `json:"isAPIKey,omitempty"`
KeyName string
KeyLocation string
apiClient coreapi.Client
}
//NewSubscriptionNotification - creates a new subscription notification object
func NewSubscriptionNotification(recipient, message string, state apic.SubscriptionState) *SubscriptionNotification {
subscriptionNotification := &SubscriptionNotification{
Email: recipient,
Action: state,
Message: message,
apiClient: coreapi.NewClient(corecfg.NewTLSConfig(), ""),
}
return subscriptionNotification
}
// consts
const (
Apikeys = "apikeys"
Oauth = "oauth"
)
// SetCatalogItemInfo - Set the catalogitem info
func (s *SubscriptionNotification) SetCatalogItemInfo(catalogID, catalogName, catalogItemURL string) {
s.CatalogItemID = catalogID
s.CatalogItemName = catalogName
s.CatalogItemURL = catalogItemURL
}
// SetAPIKeyInfo - Set the key and header
func (s *SubscriptionNotification) SetAPIKeyInfo(key, keyName string) {
s.Key = key
s.KeyName = keyName
}
// SetAPIKeyInfoAndLocation - Set the key, name, and location
func (s *SubscriptionNotification) SetAPIKeyInfoAndLocation(key, keyName, keyLocation string) {
s.Key = key
s.KeyName = keyName
s.KeyLocation = keyLocation
}
// SetOauthInfo - Set the id and secret info
func (s *SubscriptionNotification) SetOauthInfo(clientID, clientSecret string) {
s.ClientID = clientID
s.ClientSecret = clientSecret
}
// SetAuthorizationTemplate - Set the authtemplate in the config central.subscriptions.notifications.smtp.subscribe.body {authtemplate}
func (s *SubscriptionNotification) SetAuthorizationTemplate(authType string) {
if authType == "" {
log.Debug("Subscription notification configuration for authorization type is not set")
return
}
template := templateActionMap[s.Action]
if template == nil {
log.Error(ErrSubscriptionNoTemplateForAction.FormatError(s.Action))
return
}
//DEPRECATED to be removed on major release - setting s.AuthTemplate will no longer be needed after "${tag} is invalid"
switch authType {
case Apikeys:
s.AuthTemplate = template.APIKey
s.IsAPIKey = true
case Oauth:
s.AuthTemplate = template.Oauth
s.IsAPIKey = false
default:
log.Error(ErrSubscriptionBadAuthtype.FormatError(authType))
return
}
log.Debugf("Subscription notification configuration for '{authtemplate}' is set to %s", authType)
}
// NotifySubscriber - send a notification to any configured notification type
func (s *SubscriptionNotification) NotifySubscriber(recipient string) error {
var notificationSent bool
for _, notificationType := range globalCfg.GetNotificationTypes() {
log.Debugf("Attempt to notify using %s", notificationType)
switch notificationType {
case corecfg.NotifyWebhook:
err := s.notifyViaWebhook()
if err != nil {
return utilerrors.Wrap(ErrSubscriptionNotification, err.Error()).FormatError("webhook")
}
notificationSent = true
log.Debugf("Webhook notification sent to %s.", recipient)
case corecfg.NotifySMTP:
log.Info("Sending subscription email to subscriber.")
err := s.notifyViaSMTP()
if err != nil {
return utilerrors.Wrap(ErrSubscriptionNotification, err.Error()).FormatError("smtp")
}
notificationSent = true
log.Debugf("Email notification sent to %s.", recipient)
}
}
if !notificationSent {
return ErrSubscriptionNoNotifications
}
return nil
}
func (s *SubscriptionNotification) notifyViaWebhook() error {
buffer, err := json.Marshal(&s)
if err != nil {
return utilerrors.Wrap(ErrSubscriptionData, err.Error())
}
request := coreapi.Request{
Method: coreapi.POST,
URL: globalCfg.GetWebhookURL(),
Headers: globalCfg.GetWebhookHeaders(),
Body: buffer,
}
_, err = s.apiClient.Send(request)
if err != nil {
return err
}
return nil
}
func (s *SubscriptionNotification) notifyViaSMTP() error {
template := templateActionMap[s.Action]
if template == nil {
return fmt.Errorf("no template found for action %s", s.Action)
}
if template.Subject == "" && template.Body == "" {
return fmt.Errorf("template subject and body not found for action %s", s.Action)
}
// determine the auth type to use
var auth sasl.Client
log.Debugf("SMTP authorization type %s", globalCfg.GetSMTPAuthType())
switch globalCfg.GetSMTPAuthType() {
case (corecfg.LoginAuth):
auth = sasl.NewLoginClient(globalCfg.GetSMTPUsername(), globalCfg.GetSMTPPassword())
case (corecfg.PlainAuth):
auth = sasl.NewPlainClient(globalCfg.GetSMTPIdentity(), globalCfg.GetSMTPUsername(), globalCfg.GetSMTPPassword())
case (corecfg.AnonymousAuth):
auth = sasl.NewAnonymousClient(globalCfg.GetSMTPFromAddress())
}
msg, err := s.BuildSMTPMessage(template)
if err != nil {
return err
}
err = smtp.SendMail(globalCfg.GetSMTPURL(), auth, globalCfg.GetSMTPFromAddress(), []string{s.Email}, msg)
if err != nil {
log.Error(utilerrors.Wrap(ErrSubscriptionSendEmail, err.Error()))
return err
}
return nil
}
// BuildSMTPMessage -
func (s *SubscriptionNotification) BuildSMTPMessage(template *corecfg.EmailTemplate) (*strings.Reader, error) {
mime := mimeMap{
"MIME-version": "1.0",
"Content-Type": "text/html",
"charset": "UTF-8",
}
fromAddress := fmt.Sprintf("From: %s", globalCfg.GetSMTPFromAddress())
toAddress := fmt.Sprintf("To: %s", s.Email)
subject := fmt.Sprintf("Subject: %s", template.Subject)
log.Debugf("Sending email %s, %s, %s", fromAddress, toAddress, subject)
emailNotificationTemplate := emailtemplate.EmailNotificationTemplate{
CatalogItemID: s.CatalogItemID,
CatalogItemURL: s.CatalogItemURL,
CatalogItemName: s.CatalogItemName,
Email: s.Email,
Message: s.Message,
Key: s.Key,
KeyHeaderName: s.KeyName,
KeyName: s.KeyName,
KeyLocation: s.KeyLocation,
ClientID: s.ClientID,
ClientSecret: s.ClientSecret,
AuthTemplate: s.AuthTemplate,
IsAPIKey: s.IsAPIKey,
}
// Shouldn't have to check error from ValidateSubscriptionConfigOnNotification since startup passed the subscription validation check
emailBody, err := emailtemplate.ValidateSubscriptionConfigOnNotification(template.Body, s.AuthTemplate, emailNotificationTemplate)
if err != nil {
return nil, err
}
msgArray := []string{
fromAddress,
toAddress,
subject,
mime.String(),
emailBody,
}
return strings.NewReader(strings.Join(msgArray, "\n")), nil
}