/
base_email.go
567 lines (486 loc) · 22.8 KB
/
base_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
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
package email
// Copyright (C) Philip Schlump, 2016-2018, 2023.
// MIT Licensed. See LICENSE.mit file.
// BSD Licensed. See LICENSE.bsd file.
// EMail interface to sendgrid, aws_ses.
import (
"context"
"fmt"
"net/http"
"os"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/pschlump/HashStrings"
"github.com/pschlump/ReadConfig"
"github.com/pschlump/dbgo"
"github.com/pschlump/filelib"
"github.com/pschlump/gintools/data"
"github.com/pschlump/gintools/metrics"
"github.com/pschlump/gintools/run_template"
"github.com/pschlump/scany/pgxscan"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// "github.com/pschlump/gintools/jwt_auth"
type EmailSender interface {
SendEmailViaVendor(rowID, fromName, fromAddress, subject, toName, toAddress, textBody, htmlBody string) (err error)
SendEmail(template_name string, param ...interface{}) (err error)
SendEmailMapdata(template_name string, mdata map[string]interface{}) (err error)
LogError(rowID, msg string, err error)
LogSuccess(rowID string)
SetupHandlerApi(router *gin.Engine, urlPath, key string)
ResetLogFile(newFp *os.File)
}
type EmailSenderImplementation interface {
SendEmailViaVendor(rowID, fromName, fromAddress, subject, toName, toAddress, textBody, htmlBody string) (err error, result string)
}
type GenericEmailSender struct {
SenderName string
TheSender EmailSenderImplementation
// Configuration data
gCfg *data.BaseConfigType
// Debug flags like prevent send of email for testing
DbFlag map[string]bool
// Log file to write logging to
emailLogFilePtr *os.File
// Logging and Metrics
md *metrics.MetricsData
logger *zap.Logger
// Database Context and Connection
//
// Will be used by the LogError, LogSuccess fuctions to track email.
conn *pgxpool.Pool
ctx context.Context
// Timed Sender Data
nTicks int
ch chan string
timeout chan string
}
// func NewEmailSender(senderType string, gcfg *data.BaseConfigType, db map[string]bool, f *os.File, conn *pgxpool.Pool, ctx context.Context, lgr *zap.Logger, xmd *metrics.MetricsData) (rv GenericEmailSender) {
func NewEmailSender(senderType string, gcfg *data.BaseConfigType, db map[string]bool, f *os.File, conn *pgxpool.Pool, ctx context.Context, lgr *zap.Logger, xmd *metrics.MetricsData) (rv EmailSender) {
if xmd != nil {
validKeys := []metrics.MetricsTypeInfo{
{
Key: "email_sender_successful_emails",
Desc: "Count of Successful Emails Sent",
},
{
Key: "email_sender_failed_emails",
Desc: "Count of Failed Emails Sent",
},
{
Key: "email_sender_redirect_email_to_address",
Desc: "Count of Failed Emails Sent",
},
{
Key: "email_sender_sql_error",
Desc: "Count of sql errors",
},
{
Key: "email_sender_timed_check_for_email",
Desc: "Count of sql errors",
},
}
xmd.AddMetricsKeys(validKeys)
}
var xv GenericEmailSender
xv.SenderName = senderType
xv.nTicks = 0
xv.ch = make(chan string, 1)
xv.timeout = make(chan string, 2)
xv.emailLogFilePtr = f
xv.gCfg = gcfg
xv.DbFlag = db
xv.conn = conn
xv.ctx = ctx
xv.logger = lgr
xv.md = xmd
switch senderType {
case "sendgrid":
xv.TheSender = NewEmailSenderSendgrid(f)
case "aws_ses":
xv.TheSender = NewEmailSenderAwsSes(f)
default:
fmt.Fprintf(xv.emailLogFilePtr, "Fatal Configuration Error: Invalid email sender type >%s<-, should be one of [ \"sendgrid\", \"aws_ses\" ]\n", senderType)
os.Exit(1)
}
if gcfg.EmailTickerSeconds >= 1 {
xv.initializeTimedSender()
}
return &xv
}
func (em *GenericEmailSender) ResetLogFile(newFp *os.File) {
em.emailLogFilePtr = newFp
}
// -------------------------------------------------------------------------------------------------------------------------
/*
CREATE TABLE if not exists q_qr_email_log (
email_email_id uuid DEFAULT uuid_generate_v4() not null primary key
, updated timestamp
, created timestamp default current_timestamp not null
, user_id uuid
, state text
, error_msg text
, email_data text
);
*/
func (em GenericEmailSender) LogError(rowID, msg string, err error) {
stmt := `
update q_qr_email_log
set state = 'Error',
error_msg = $2
where email_log_id = $1
`
_, e0 := em.SqlRunStmt(stmt, "..", rowID, fmt.Sprintf("%s: %s", msg, err))
if e0 != nil {
dbgo.Fprintf(os.Stderr, "%(red)%(LF)Error on update of q_qr_email_log ->%s<- %s error:%s\n", stmt, XData(rowID), e0)
dbgo.Fprintf(em.emailLogFilePtr, "%(LF)Error on update of q_qr_email_log ->%s<- %s error:%s\n", stmt, XData(rowID), e0)
}
}
func (em GenericEmailSender) LogSuccess(rowID string) {
stmt := `
update q_qr_email_log
set state = 'Sent-Success'
where email_log_id = $1
`
_, err := em.SqlRunStmt(stmt, "..", rowID)
if err != nil {
dbgo.Fprintf(os.Stderr, "%(green)%(LF)Error on update of q_qr_email_log ->%s<- %s error:%s\n", stmt, XData(rowID), err)
dbgo.Fprintf(em.emailLogFilePtr, "%(LF)Error on update of q_qr_email_log ->%s<- %s error:%s\n", stmt, XData(rowID), err)
}
}
// SendEmailViaVendor will use the underlying implemenation to send the email.
func (em *GenericEmailSender) SendEmailViaVendor(rowID, fromName, fromAddress, subject, toName, toAddress, textBody, htmlBody string) (err error) {
err, result := em.TheSender.SendEmailViaVendor(rowID, fromName, fromAddress, subject, toName, toAddress, textBody, htmlBody)
if err != nil {
em.md.AddCounter("email_sender_failed_emails", 1)
em.LogError(rowID, "Failed to send email", err)
fmt.Fprintf(em.emailLogFilePtr, "#Email# Send Error: %s\n", err)
return
}
fmt.Fprintf(em.emailLogFilePtr, "#Email# Send Success, %v\n", result)
em.md.AddCounter("email_sender_successful_emails", 1)
dbgo.Fprintf(em.emailLogFilePtr, "Success: result= ->%s<-\n", dbgo.SVarI(result))
em.LogSuccess(rowID)
return err
}
// SendEmail combines a base template name with globacl configuration on where to find the templates
// and turns that into all the parts of an email, then calls SendEmailViaVendor to send the email.
func (em *GenericEmailSender) SendEmail(template_name string, param ...interface{}) (err error) {
mdata := make(map[string]interface{})
for ii := 0; ii < len(param); ii += 2 {
var val interface{}
if ii+1 < len(param) {
val = param[ii+1]
} else {
val = ""
}
key := fmt.Sprintf("%s", param[ii])
mdata[key] = val
}
return em.SendEmailMapdata(template_name, mdata)
}
func (em *GenericEmailSender) SendEmailMapdata(template_name string, mdata map[string]interface{}) (err error) {
dbgo.Printf("%(LF) %(cyan) ---- AT TOP mdata=%s\n", dbgo.SVarI(mdata))
dbgo.Fprintf(em.emailLogFilePtr, "%(LF) --- AT TOP --- mdata=%s\n", dbgo.SVarI(mdata))
tfn := fmt.Sprintf("%s/%s.tmpl", em.gCfg.EmailTmplDir, template_name)
CurDir, _ := os.Getwd()
dbgo.Printf("%(LF) %(cyan) ---- template file = ->%s<- in dir ->%s<-\n", tfn, CurDir)
if !ReadConfig.Exists(tfn) {
fmt.Fprintf(os.Stderr, "#Email# Missing template file [%s]\n", tfn)
fmt.Fprintf(em.emailLogFilePtr, "#Email# Missing template file [%s]\n", tfn)
return fmt.Errorf("Missing template file [%s]\n", tfn)
}
dbgo.Printf("%(LF)\n")
mdata["tfn"] = tfn
mdata["from_name"] = em.gCfg.EmailFromName
mdata["from_address"] = em.gCfg.EmailFromAddress
dbgo.Printf("%(LF) %(yellow) mdata=%s\n", dbgo.SVarI(mdata))
dbgo.Fprintf(em.emailLogFilePtr, "%(LF) mdata=%s\n", dbgo.SVarI(mdata))
// run_template.RunTemplate(TemplateFn string, name_of string, g_data map[string]interface{}) string {
fromName := run_template.RunTemplate(tfn, "from_name", mdata)
fromAddress := run_template.RunTemplate(tfn, "from_address", mdata)
subject := run_template.RunTemplate(tfn, "subject", mdata)
toName := run_template.RunTemplate(tfn, "to_name", mdata)
toAddress := run_template.RunTemplate(tfn, "to_address", mdata)
textBody := run_template.RunTemplate(tfn, "text_body", mdata)
htmlBody := run_template.RunTemplate(tfn, "html_body", mdata)
UserID, ok := mdata["UserID"]
if !ok {
UserID = ""
}
dbgo.Printf("%(LF)\n")
if em.gCfg.RedirectEmailSendTo != "" {
if em.logger != nil {
fields := []zapcore.Field{
zap.String("message", "Redirecting Email"),
zap.String("originalAddress", toAddress),
zap.String("sentTo", em.gCfg.RedirectEmailSendTo),
}
em.logger.Info("email_sender_redirect_email_to_address", fields...)
} else {
dbgo.Fprintf(os.Stderr, "Redirecting ->%s<- to ->%s<-\n", toAddress, em.gCfg.RedirectEmailSendTo)
}
dbgo.Fprintf(em.emailLogFilePtr, "Redirecting ->%s<- to ->%s<-\n", toAddress, em.gCfg.RedirectEmailSendTo)
toAddress = em.gCfg.RedirectEmailSendTo
}
dbgo.Printf("%(LF)\n")
mdata["FromName"] = fromName
mdata["FromAddress"] = fromAddress
mdata["ToName"] = toName
mdata["ToAddress"] = toAddress
mdata["Subject"] = subject
mdata["TextBody"] = textBody
mdata["HtmlBody"] = htmlBody
mdata["randomval"] = GenUUID() // <a href="{{.server}}api/v1/auth/email-confirm?email_verify_token={{.token}}&redirect_to={{.server}}&__ran__={{.randomval}}"> {{.server}}confirm-email.html </a><br>
dbgo.Printf("%(LF)\n")
if em.logger != nil {
fields := []zapcore.Field{}
fields = append(fields, zap.String("message", "email-template-fields"))
for k, v := range mdata {
fields = append(fields, zap.String(k, fmt.Sprintf("%s", v)))
}
em.logger.Info("email_sender_redirect_email_to_address", fields...)
} else {
dbgo.Fprintf(em.emailLogFilePtr, "%(yellow)EmailData\n")
}
fmt.Fprintf(em.emailLogFilePtr, "#EmailData#%s\n", dbgo.SVar(mdata))
dbgo.Printf("%(LF)%(green) -- just before -- -- token -- ->%s<-\n", mdata["token"])
// Used in test scripts to get the email token from the email log. Do not change syntax. ./test/tgo_register_and_login.sh
dbgo.Fprintf(em.emailLogFilePtr, "\nAT: Email Data %(LF)\n\n#EmailToken#: %s\n\n", mdata["token"])
dbgo.Printf("%(LF) %(yellow) mdata=%s\n", dbgo.SVarI(mdata))
dbgo.Fprintf(em.emailLogFilePtr, "%(LF) mdata=%s\n", dbgo.SVarI(mdata))
dbgo.Fprintf(em.emailLogFilePtr, "#textBody#= ---[[[%s]]]---\n", textBody)
dbgo.Fprintf(em.emailLogFilePtr, "#htmlBody#= ---[[[->%s]]]---\n", htmlBody)
/*
-- -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE TABLE if not exists q_qr_email_log (
email_email_id uuid DEFAULT uuid_generate_v4() not null primary key
, updated timestamp
, created timestamp default current_timestamp not null
, user_id uuid
, state text
, error_msg text
, email_data text
);
*/
rowID := GenUUID()
var stmt string
if UserID == "" {
stmt = `insert into q_qr_email_log ( email_log_id, state, email_data ) values ( $1, $2, $3 )`
_, err = em.SqlRunStmt(stmt, "...", rowID, "planned", dbgo.SVar(mdata))
} else { // has UserID
stmt = `insert into q_qr_email_log ( email_log_id, user_id, state, email_data ) values ( $1, $2, $3, $4 )`
_, err = em.SqlRunStmt(stmt, "...", rowID, UserID, "planned", dbgo.SVar(mdata))
}
if err != nil {
dbgo.Fprintf(os.Stderr, "%(red)%(LF)Error on insert of q_qr_email_log ->%s<- %s error:%s\n", stmt, XData(rowID, UserID, dbgo.SVar(mdata), "planned"), err)
dbgo.Fprintf(em.emailLogFilePtr, "%(LF)Error on insert of q_qr_email_log ->%s<- %s error:%s\n", stmt, XData(rowID, UserID, dbgo.SVar(mdata), "planned"), err)
}
dbgo.Printf("%(LF) DbFlag=%s\n", dbgo.SVarI(em.DbFlag))
if em.DbFlag["__email_no_send__:"+toAddress] {
dbgo.Printf("%(LF) address %s in __email_no_send__\n", toAddress)
dbgo.Fprintf(os.Stderr, "%(LF) address %s in __email_no_send__\n", toAddress)
dbgo.Fprintf(em.emailLogFilePtr, "%(LF) address %s in __email_no_send__\n", toAddress)
stmt := `
update q_qr_email_log
set state = 'Dev-Skip'
where email_log_id = $1
`
_, err := em.SqlRunStmt(stmt, "..", rowID, fmt.Sprintf("%s", err))
if err != nil {
dbgo.Fprintf(os.Stderr, "%(red)%(LF)Error on update of q_qr_email_log ->%s<- %s error:%s\n", stmt, XData(rowID), err)
dbgo.Fprintf(em.emailLogFilePtr, "%(LF)Error on update of q_qr_email_log ->%s<- %s error:%s\n", stmt, XData(rowID), err)
}
} else if at, err := filelib.InPatternArray(toAddress, em.gCfg.NoEmailSendListRe); at >= 0 || err != nil {
if err != nil {
dbgo.Printf("%(LF)%(red) Invalid data in set of patterns for redirecting email %s, %s\n", em.gCfg.NoEmailSendListRe, err)
dbgo.Fprintf(os.Stderr, "%(LF)Invalid data in set of patterns for redirecting email %s, %s\n", em.gCfg.NoEmailSendListRe, err)
dbgo.Fprintf(em.emailLogFilePtr, "%(LF)Invalid data in set of patterns for redirecting email %s, %s\n", em.gCfg.NoEmailSendListRe, err)
} else {
dbgo.Printf("%(LF) address %s redirected to %s\n", toAddress, em.gCfg.RedirectEmailSendTo)
dbgo.Fprintf(os.Stderr, "%(LF) address %s redirected to %s\n", toAddress, em.gCfg.RedirectEmailSendTo)
dbgo.Fprintf(em.emailLogFilePtr, "%(LF) address %s redirected to %s\n", toAddress, em.gCfg.RedirectEmailSendTo)
toAddress = em.gCfg.RedirectEmailSendTo
stmt := `
update q_qr_email_log
set state = 'Dev-Skip'
where email_log_id = $1
`
_, err := em.SqlRunStmt(stmt, "..", rowID, fmt.Sprintf("%s", err))
if err != nil {
dbgo.Fprintf(os.Stderr, "%(red)%(LF)Error on update of q_qr_email_log ->%s<- %s error:%s\n", stmt, XData(rowID), err)
dbgo.Fprintf(em.emailLogFilePtr, "%(LF)Error on update of q_qr_email_log ->%s<- %s error:%s\n", stmt, XData(rowID), err)
}
dbgo.Printf("\n%(green)Just before actual send of email to:%s, %(LF)\n", toAddress)
err = em.SendEmailViaVendor(rowID, fromName, fromAddress, subject, toName, toAddress, textBody, htmlBody)
if err != nil {
dbgo.Printf("%(LF)%(red) Failed to send email: %s\n", err)
dbgo.Fprintf(os.Stderr, "%(LF)Failed to send email: %s\n", err)
dbgo.Fprintf(em.emailLogFilePtr, "%(LF)Failed to send email: %s\n", err)
}
}
} else {
dbgo.Printf("\n%(green)Just before actual send of email to:%s, %(LF)\n", toAddress)
dbgo.Fprintf(em.emailLogFilePtr, "\n%(green)Just before actual send of email to:%s, %(LF)\n", toAddress)
err = em.SendEmailViaVendor(rowID, fromName, fromAddress, subject, toName, toAddress, textBody, htmlBody)
if err != nil {
dbgo.Printf("%(LF)%(red) Failed to send email: %s\n", err)
dbgo.Fprintf(os.Stderr, "%(LF)Failed to send email: %s\n", err)
dbgo.Fprintf(em.emailLogFilePtr, "%(LF)Failed to send email: %s\n", err)
}
// logging occures in the SendEmailViaValidator ...
}
if err != nil {
if em.logger != nil {
fields := []zapcore.Field{
zap.String("message", "Email Error"),
zap.String("fromName", fromName),
zap.String("fromAddress", fromAddress),
zap.String("subject", subject),
zap.String("toName", toName),
zap.String("toAddress", toAddress),
zap.String("textBody", textBody),
zap.String("htmlBody", htmlBody),
}
em.logger.Error("email-did-not-send", fields...)
} else {
fmt.Fprintf(os.Stderr, "\n%s+============================================================================================================\n", dbgo.ColorRed)
fmt.Fprintf(os.Stderr, "| Error -- did not send\n")
fmt.Fprintf(os.Stderr, "| Skip of Send of Email.\n| From Name:%s\n| From Address:%s\n| Subject:%s\n| To:%s\n| To Address:%s\n| Text Body:--->%s<---\n HTML Body --->%s<---\n", fromName, fromAddress, subject, toName, toAddress, textBody, htmlBody)
fmt.Fprintf(os.Stderr, "+============================================================================================================\n%s\n", dbgo.ColorReset)
}
fmt.Fprintf(em.emailLogFilePtr, "\n%s+============================================================================================================\n", "")
fmt.Fprintf(em.emailLogFilePtr, "| Skip of Send of Email.\n| From Name:%s\n| From Address:%s\n| Subject:%s\n| To:%s\n| To Address:%s\n| Text Body:--->%s<---\n HTML Body --->%s<---\n", fromName, fromAddress, subject, toName, toAddress, textBody, htmlBody)
fmt.Fprintf(em.emailLogFilePtr, "+============================================================================================================\n%s\n", "")
} else if em.DbFlag["__email_no_send__:"+toAddress] || em.DbFlag["dump-email"] {
if em.logger != nil {
fields := []zapcore.Field{
zap.String("message", "Email Success"),
zap.Bool("mapped_addres_to_not_send_to", em.DbFlag["__email_no_send__:"+toAddress]),
zap.Bool("dump_email_flag_set", em.DbFlag["dump-email"]),
zap.String("fromName", fromName),
zap.String("fromAddress", fromAddress),
zap.String("subject", subject),
zap.String("toName", toName),
zap.String("toAddress", toAddress),
zap.String("textBody", textBody),
zap.String("htmlBody", htmlBody),
}
em.logger.Info("email-ignored-due-to-address-sent", fields...)
} else {
fmt.Fprintf(os.Stderr, "\n%s+============================================================================================================\n", dbgo.ColorCyan)
fmt.Fprintf(os.Stderr, "| DbFlag Set 'dump-email' or '__email_no_send__:%s'\n", toAddress)
fmt.Fprintf(os.Stderr, "| Skip of Send of Email.\n| From Name:%s\n| From Address:%s\n| Subject:%s\n| To:%s\n| To Address:%s\n| Text Body:--->%s<---\n HTML Body --->%s<---\n", fromName, fromAddress, subject, toName, toAddress, textBody, htmlBody)
fmt.Fprintf(os.Stderr, "+============================================================================================================\n%s\n", dbgo.ColorReset)
}
fmt.Fprintf(em.emailLogFilePtr, "\n%s+============================================================================================================\n", "")
fmt.Fprintf(em.emailLogFilePtr, "| Skip of Send of Email.\n| From Name:%s\n| From Address:%s\n| Subject:%s\n| To:%s\n| To Address:%s\n| Text Body:--->%s<---\n HTML Body --->%s<---\n", fromName, fromAddress, subject, toName, toAddress, textBody, htmlBody)
fmt.Fprintf(em.emailLogFilePtr, "+============================================================================================================\n%s\n", "")
} else {
if em.logger != nil {
fields := []zapcore.Field{
zap.String("message", "Email Success"),
zap.String("fromName", fromName),
zap.String("fromAddress", fromAddress),
zap.String("subject", subject),
zap.String("toName", toName),
zap.String("toAddress", toAddress),
zap.String("textBody", textBody),
zap.String("htmlBody", htmlBody),
}
em.logger.Info("email-sent", fields...)
} else {
fmt.Fprintf(os.Stderr, "\n%s+============================================================================================================\n", dbgo.ColorGreen)
fmt.Fprintf(os.Stderr, "| Send of Email.\n| From Name:%s\n| From Address:%s\n| Subject:%s\n| To:%s\n| To Address:%s\n| Text Body:--->%s<---\n HTML Body --->%s<---\n", fromName, fromAddress, subject, toName, toAddress, textBody, htmlBody)
fmt.Fprintf(os.Stderr, "+============================================================================================================\n%s\n", dbgo.ColorReset)
}
}
return
}
// SqlRunStmt will run a single statemt and return the data as an array of maps
func (em GenericEmailSender) SqlRunStmt(stmt string, encPat string, data ...interface{}) (rv []map[string]interface{}, err error) {
if em.conn == nil {
dbgo.Fprintf(em.emailLogFilePtr, "Connection is nil -- no database connected -- :%(LF)\n")
return
}
fmt.Fprintf(os.Stderr, "Database Stmt ->%s<- data ->%s<-\n", stmt, dbgo.SVar(data))
fmt.Fprintf(em.emailLogFilePtr, "Database Stmt ->%s<- data ->%s<-\n", stmt, dbgo.SVar(data))
err = pgxscan.Select(em.ctx, em.conn, &rv, stmt, data...)
if err != nil {
em.md.AddCounter("email_sender_sql_error", 1)
if em.logger != nil {
fields := []zapcore.Field{
zap.String("message", "Email SQL Error"),
zap.Error(err),
zap.String("stmt", stmt),
zap.String("bind_vars", fmt.Sprintf("%s", data)),
zap.String("location", dbgo.LF(-2)),
}
em.logger.Info("email-sql-error", fields...)
}
fmt.Fprintf(em.emailLogFilePtr, "Sql error: %s stmt: ->%s<- params: %s", err, stmt, XData(data))
return nil, fmt.Errorf("Sql error: %s stmt: ->%s<- params: %s", err, stmt, XData(data))
}
return nil, nil
}
// SetupHandlerApi will create a handler at the specified URL path to "kick" the timed sender
func (em *GenericEmailSender) SetupHandlerApi(router *gin.Engine, urlPath, AuthKey string) {
router.POST(urlPath, func(c *gin.Context) {
type ApiSendTestEmail struct {
AuthKey string `json:"auth_key" form:"auth_key" binding:"required"`
}
dbgo.Fprintf(os.Stderr, "%(cyan)In handler, Kicker for Email, %s, at %(LF)\n", urlPath)
var pp ApiSendTestEmail
if err := BindFormOrJSON(c, &pp); err != nil {
return
}
pw := os.Getenv("TEST_SEND_EMAIL_PASSWORD")
if pw == "" {
dbgo.DbFprintf("db.SendTestEmailHandler", os.Stderr, "%(red)email.SendTestEmailHandler -- Requires TEST_SEND_EMAIL_PASSWORD to be set %(LF)\n")
c.JSON(http.StatusUnauthorized, gin.H{
"status": "error",
"msg": "Must be have correct HMAC key/password.",
"location": dbgo.LF(),
})
return
}
// To Generate the HMAC auth key, See: ../gen-email-key or $tools/tools/gen-email-key
// dbgo.Fprintf(os.Stderr, "%(cyan)AT:%(LF) -- %(red)checking auth of key%(cyan) -- ->%s<- || ->%s<- hash to ->%s<- should match ->%s<-\n", pw, pp.AuthKey, HashStrings.HashStrings(pw+pp.AuthKey), "2572640f43d8b184d14c2b7f0d255a752fd4c3d674dba969046d5c611d47b8d5")
if HashStrings.HashStrings(pw+pp.AuthKey) != "2572640f43d8b184d14c2b7f0d255a752fd4c3d674dba969046d5c611d47b8d5" {
dbgo.DbFprintf("db.SendTestEmailHandler", os.Stderr, "%(red)email.SendTestEmailHandler -- Requires AuthKey to be valid %(LF) --\nSee ~/.secret/setup.sh or run generation tool ../gen-email-key/gen-email-key.go\n ->%s<-\n ->%s<-\n", pp.AuthKey, "2572640f43d8b184d14c2b7f0d255a752fd4c3d674dba969046d5c611d47b8d5")
c.JSON(http.StatusUnauthorized, gin.H{
"status": "error",
"msg": "Must be have correct HMAC key to access set the SendTestEmailHandler interface.",
"location": dbgo.LF(),
})
return
}
em.ch <- "kick"
c.JSON(http.StatusOK /*200*/, gin.H{"status": "success"})
})
/*
router.POST("/api/v1/status", func(c *gin.Context) {
c.JSON(http.StatusOK / * 200 * /, gin.H{
"status": "success",
"msg": "Hello Silly World!",
})
})
*/
}
func BindFormOrJSON(c *gin.Context, bindTo interface{}) (err error) {
if err = c.ShouldBind(bindTo); err != nil {
dbgo.Printf("%(red)In BindFormOrJSON at:%(LF) err=%s\n", err)
// dbgo.Fprintf(logFilePtr, "%(red)In BindFormOrJSON at:%(LF) err=%s\n", err)
c.JSON(http.StatusNotAcceptable, gin.H{ // 406
"status": "error",
"msg": fmt.Sprintf("Error: %s", err),
})
return
}
dbgo.Printf("%(cyan)Parameters: %s at %s\n", dbgo.SVarI(bindTo), dbgo.LF(2))
// dbgo.Fprintf(logFilePtr, "%(cyan)Parameters: %s at %s\n", dbgo.SVarI(bindTo), dbgo.LF(2))
return
}
/* vim: set noai ts=4 sw=4: */