-
Notifications
You must be signed in to change notification settings - Fork 208
Expand file tree
/
Copy pathinboxes.go
More file actions
477 lines (423 loc) · 17.8 KB
/
Copy pathinboxes.go
File metadata and controls
477 lines (423 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
477
package main
import (
"encoding/json"
"net/mail"
"regexp"
"strconv"
"strings"
"time"
"github.com/abhinavxd/libredesk/internal/envelope"
"github.com/abhinavxd/libredesk/internal/httputil"
"github.com/abhinavxd/libredesk/internal/inbox"
"github.com/abhinavxd/libredesk/internal/inbox/channel/email/oauth"
"github.com/abhinavxd/libredesk/internal/inbox/channel/livechat"
"github.com/abhinavxd/libredesk/internal/inbox/channel/telegram"
imodels "github.com/abhinavxd/libredesk/internal/inbox/models"
"github.com/valyala/fasthttp"
"github.com/zerodha/fastglue"
)
// handleGetInboxes returns all inboxes
func handleGetInboxes(r *fastglue.Request) error {
var app = r.Context.(*App)
inboxes, err := app.inbox.GetAll()
if err != nil {
return sendErrorEnvelope(r, err)
}
for i := range inboxes {
if err := inboxes[i].ClearPasswords(); err != nil {
app.lo.Error("error clearing inbox passwords from response", "error", err)
return envelope.NewError(envelope.GeneralError, app.i18n.T("globals.messages.somethingWentWrong"), nil)
}
}
return r.SendEnvelope(inboxes)
}
// handleGetInbox returns an inbox by ID
func handleGetInbox(r *fastglue.Request) error {
var (
app = r.Context.(*App)
id, _ = strconv.Atoi(r.RequestCtx.UserValue("id").(string))
)
inbox, err := app.inbox.GetDBRecord(id)
if err != nil {
return sendErrorEnvelope(r, err)
}
if err := inbox.ClearPasswords(); err != nil {
app.lo.Error("error clearing inbox passwords from response", "error", err)
return envelope.NewError(envelope.GeneralError, app.i18n.T("globals.messages.somethingWentWrong"), nil)
}
return r.SendEnvelope(inbox)
}
// handleCreateInbox creates a new inbox
func handleCreateInbox(r *fastglue.Request) error {
var (
app = r.Context.(*App)
inbox = imodels.Inbox{}
)
if err := r.Decode(&inbox, "json"); err != nil {
return r.SendErrorEnvelope(fasthttp.StatusBadRequest, app.i18n.T("errors.parsingRequest"), err.Error(), envelope.InputError)
}
// Trim whitespace from inbox fields and config.
if err := trimInboxFields(&inbox); err != nil {
return r.SendErrorEnvelope(fasthttp.StatusBadRequest, app.i18n.T("errors.parsingRequest"), err.Error(), envelope.InputError)
}
if err := validateInbox(app, inbox); err != nil {
return sendErrorEnvelope(r, err)
}
createdInbox, err := app.inbox.Create(inbox)
if err != nil {
return sendErrorEnvelope(r, err)
}
if err := reloadInbox(app, createdInbox.ID); err != nil {
app.lo.Error("error reloading inbox", "id", createdInbox.ID, "error", err)
return r.SendErrorEnvelope(fasthttp.StatusInternalServerError, app.i18n.T("globals.messages.somethingWentWrong"), nil, envelope.GeneralError)
}
// Clear passwords before returning.
if err := createdInbox.ClearPasswords(); err != nil {
app.lo.Error("error clearing inbox passwords from response", "error", err)
return envelope.NewError(envelope.GeneralError, app.i18n.T("globals.messages.somethingWentWrong"), nil)
}
return r.SendEnvelope(createdInbox)
}
// handleUpdateInbox updates an inbox
func handleUpdateInbox(r *fastglue.Request) error {
var (
app = r.Context.(*App)
inbox = imodels.Inbox{}
)
id, err := strconv.Atoi(r.RequestCtx.UserValue("id").(string))
if err != nil || id == 0 {
return r.SendErrorEnvelope(fasthttp.StatusBadRequest,
app.i18n.T("globals.messages.somethingWentWrong"), nil, envelope.InputError)
}
if err := r.Decode(&inbox, "json"); err != nil {
return r.SendErrorEnvelope(fasthttp.StatusBadRequest, app.i18n.T("errors.parsingRequest"), err.Error(), envelope.InputError)
}
// Trim whitespace from inbox fields and config.
if err := trimInboxFields(&inbox); err != nil {
return r.SendErrorEnvelope(fasthttp.StatusBadRequest, app.i18n.T("errors.parsingRequest"), err.Error(), envelope.InputError)
}
if err := validateInbox(app, inbox); err != nil {
return sendErrorEnvelope(r, err)
}
updatedInbox, err := app.inbox.Update(id, inbox)
if err != nil {
return sendErrorEnvelope(r, err)
}
if err := reloadInbox(app, id); err != nil {
app.lo.Error("error reloading inbox", "id", id, "error", err)
return r.SendErrorEnvelope(fasthttp.StatusInternalServerError, app.i18n.T("globals.messages.somethingWentWrong"), nil, envelope.GeneralError)
}
// Clear passwords before returning.
if err := updatedInbox.ClearPasswords(); err != nil {
app.lo.Error("error clearing inbox passwords from response", "error", err)
return envelope.NewError(envelope.GeneralError, app.i18n.T("globals.messages.somethingWentWrong"), nil)
}
return r.SendEnvelope(updatedInbox)
}
// handleToggleInbox toggles an inbox
func handleToggleInbox(r *fastglue.Request) error {
var (
app = r.Context.(*App)
)
id, err := strconv.Atoi(r.RequestCtx.UserValue("id").(string))
if err != nil || id == 0 {
return r.SendErrorEnvelope(fasthttp.StatusBadRequest,
app.i18n.T("globals.messages.somethingWentWrong"), nil, envelope.InputError)
}
toggledInbox, err := app.inbox.Toggle(id)
if err != nil {
return err
}
if err := reloadInbox(app, id); err != nil {
app.lo.Error("error reloading inbox", "id", id, "error", err)
return r.SendErrorEnvelope(fasthttp.StatusInternalServerError, app.i18n.T("globals.messages.somethingWentWrong"), nil, envelope.GeneralError)
}
// Clear passwords before returning
if err := toggledInbox.ClearPasswords(); err != nil {
app.lo.Error("error clearing inbox passwords from response", "error", err)
return envelope.NewError(envelope.GeneralError, app.i18n.T("globals.messages.somethingWentWrong"), nil)
}
return r.SendEnvelope(toggledInbox)
}
// handleDeleteInbox deletes an inbox
func handleDeleteInbox(r *fastglue.Request) error {
var (
app = r.Context.(*App)
id, _ = strconv.Atoi(r.RequestCtx.UserValue("id").(string))
)
err := app.inbox.SoftDelete(id)
if err != nil {
return sendErrorEnvelope(r, err)
}
if err := reloadInbox(app, id); err != nil {
app.lo.Error("error reloading inbox", "id", id, "error", err)
return r.SendErrorEnvelope(fasthttp.StatusInternalServerError, app.i18n.T("globals.messages.somethingWentWrong"), nil, envelope.GeneralError)
}
return r.SendEnvelope(true)
}
// validateInbox validates the inbox
func validateInbox(app *App, inbox imodels.Inbox) error {
// Validate from address only for email channels.
if inbox.Channel == "email" {
if _, err := mail.ParseAddress(inbox.From); err != nil {
return envelope.NewError(envelope.InputError, app.i18n.Ts("validation.invalidFromAddress"), nil)
}
var cfg imodels.Config
if len(inbox.Config) > 0 {
if err := json.Unmarshal(inbox.Config, &cfg); err == nil && cfg.ReplyTo != "" {
if _, err := mail.ParseAddress(cfg.ReplyTo); err != nil {
return envelope.NewError(envelope.InputError, app.i18n.T("validation.invalidEmail"), nil)
}
}
}
}
if len(inbox.Config) == 0 {
return envelope.NewError(envelope.InputError, app.i18n.Ts("globals.messages.empty", "name", "config"), nil)
}
if inbox.Name == "" {
return envelope.NewError(envelope.InputError, app.i18n.Ts("globals.messages.empty", "name", "name"), nil)
}
if inbox.Channel == "" {
return envelope.NewError(envelope.InputError, app.i18n.Ts("globals.messages.empty", "name", "channel"), nil)
}
// Validate livechat-specific configuration
if inbox.Channel == livechat.ChannelLiveChat {
var config livechat.Config
if err := json.Unmarshal(inbox.Config, &config); err == nil {
// ShowOfficeHoursAfterAssignment cannot be enabled if ShowOfficeHoursInChat is disabled
if config.ShowOfficeHoursAfterAssignment && !config.ShowOfficeHoursInChat {
return envelope.NewError(envelope.InputError, "`show_office_hours_after_assignment` cannot be enabled when `show_office_hours_in_chat` is disabled", nil)
}
// Validate continuity settings - required when linked email inbox is set.
if inbox.LinkedEmailInboxID.Valid && inbox.LinkedEmailInboxID.Int > 0 {
if config.Continuity.OfflineThreshold == "" {
return envelope.NewError(envelope.InputError, app.i18n.Ts("globals.messages.empty", "name", "offline_threshold"), nil)
}
if config.Continuity.MinEmailInterval == "" {
return envelope.NewError(envelope.InputError, app.i18n.Ts("globals.messages.empty", "name", "min_email_interval"), nil)
}
if config.Continuity.MaxMessagesPerEmail == 0 {
return envelope.NewError(envelope.InputError, app.i18n.Ts("globals.messages.empty", "name", "max_messages_per_email"), nil)
}
}
if config.Continuity.OfflineThreshold != "" {
d, err := time.ParseDuration(config.Continuity.OfflineThreshold)
if err != nil {
return envelope.NewError(envelope.InputError, app.i18n.Ts("validation.invalidDuration", "name", "offline_threshold"), nil)
}
if d < time.Minute {
return envelope.NewError(envelope.InputError, app.i18n.Ts("validation.minDuration", "name", "offline_threshold", "min", "1m"), nil)
}
}
if config.Continuity.MinEmailInterval != "" {
d, err := time.ParseDuration(config.Continuity.MinEmailInterval)
if err != nil {
return envelope.NewError(envelope.InputError, app.i18n.Ts("validation.invalidDuration", "name", "min_email_interval"), nil)
}
if d < time.Minute {
return envelope.NewError(envelope.InputError, app.i18n.Ts("validation.minDuration", "name", "min_email_interval", "min", "1m"), nil)
}
}
if config.Continuity.MaxMessagesPerEmail != 0 {
if config.Continuity.MaxMessagesPerEmail < 1 || config.Continuity.MaxMessagesPerEmail > 100 {
return envelope.NewError(envelope.InputError, app.i18n.Ts("validation.minmaxNumber", "min", "1", "max", "100"), nil)
}
}
// Validate colors.
hexColorRegex := regexp.MustCompile(`^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$`)
if config.Colors.Primary == "" {
return envelope.NewError(envelope.InputError, app.i18n.Ts("globals.messages.empty", "name", "primary color"), nil)
}
if !hexColorRegex.MatchString(config.Colors.Primary) {
return envelope.NewError(envelope.InputError, app.i18n.T("validation.invalidColor"), nil)
}
// Validate launcher position.
if config.Launcher.Position != "left" && config.Launcher.Position != "right" {
return envelope.NewError(envelope.InputError, app.i18n.T("validation.invalidValue"), nil)
}
// Validate launcher spacing: clamp to a sane range so a fat-fingered value doesn't push the launcher off-screen.
if config.Launcher.Spacing.Side < 0 || config.Launcher.Spacing.Side > 200 ||
config.Launcher.Spacing.Bottom < 0 || config.Launcher.Spacing.Bottom > 200 {
return envelope.NewError(envelope.InputError, app.i18n.T("validation.invalidValue"), nil)
}
// Validate home apps.
for _, ha := range config.HomeApps {
if ha.URL != "" && !httputil.IsValidHTTPURL(ha.URL) {
return envelope.NewError(envelope.InputError, app.i18n.T("validation.invalidUrl"), nil)
}
if ha.Type == livechat.HomeAppAnnouncement && ha.ImageURL != "" && !httputil.IsValidHTTPURL(ha.ImageURL) {
return envelope.NewError(envelope.InputError, app.i18n.T("validation.invalidUrl"), nil)
}
}
// Validate home screen background image URL.
if config.HomeScreen.Background.ImageURL != "" && !httputil.IsValidHTTPURL(config.HomeScreen.Background.ImageURL) {
return envelope.NewError(envelope.InputError, app.i18n.T("validation.invalidUrl"), nil)
}
// Validate URLs if set.
for _, u := range []string{config.LogoURL, config.Launcher.LogoURL, config.WebsiteURL} {
if u != "" && !httputil.IsValidHTTPURL(u) {
return envelope.NewError(envelope.InputError, app.i18n.T("validation.invalidUrl"), nil)
}
}
// Validate trusted domains.
// Valid formats: example.com, *.example.com, sub.example.com, example.com:8080
for _, domain := range config.TrustedDomains {
d := strings.TrimSpace(domain)
if d == "" {
continue
}
if strings.Contains(d, "://") || strings.Contains(d, "/") || strings.Contains(d, " ") {
return envelope.NewError(envelope.InputError, app.i18n.Ts("validation.invalidDomain", "domain", d), nil)
}
// Wildcard must be at the start followed by a dot.
if strings.Contains(d, "*") && !strings.HasPrefix(d, "*.") {
return envelope.NewError(envelope.InputError, app.i18n.Ts("validation.invalidDomain", "domain", d), nil)
}
}
// Validate blocked IPs entries.
for _, entry := range config.BlockedIPs {
if !httputil.ValidateIPOrCIDR(entry) {
return envelope.NewError(envelope.InputError, app.i18n.Ts("validation.invalidIPOrCIDR", "entry", entry), nil)
}
}
}
// Validate linked email inbox if specified
if inbox.LinkedEmailInboxID.Valid {
linkedInbox, err := app.inbox.GetDBRecord(int(inbox.LinkedEmailInboxID.Int))
if err != nil {
return envelope.NewError(envelope.InputError, app.i18n.T("globals.messages.somethingWentWrong"), nil)
}
// Ensure linked inbox is an email channel
if linkedInbox.Channel != "email" {
return envelope.NewError(envelope.InputError, app.i18n.T("globals.messages.somethingWentWrong"), nil)
}
// Ensure linked inbox is enabled
if !linkedInbox.Enabled {
return envelope.NewError(envelope.InputError, app.i18n.T("globals.messages.somethingWentWrong"), nil)
}
}
}
// Validate email channel config.
if inbox.Channel == "email" {
if err := validateEmailConfig(app, inbox.Config); err != nil {
return err
}
}
// Validate telegram channel config.
if inbox.Channel == telegram.ChannelTelegram {
if err := validateTelegramConfig(app, inbox.Config); err != nil {
return err
}
}
return nil
}
// validateEmailConfig validates the email inbox configuration.
func validateEmailConfig(app *App, configJSON json.RawMessage) error {
var cfg imodels.Config
if err := json.Unmarshal(configJSON, &cfg); err != nil {
return envelope.NewError(envelope.InputError, app.i18n.T("globals.messages.somethingWentWrong"), nil)
}
// Validate auth_type.
if cfg.AuthType != "" && cfg.AuthType != imodels.AuthTypePassword && cfg.AuthType != imodels.AuthTypeOAuth2 {
return envelope.NewError(envelope.InputError, app.i18n.T("globals.messages.somethingWentWrong"), nil)
}
// Validate OAuth config if auth_type is oauth2.
if cfg.AuthType == imodels.AuthTypeOAuth2 {
if cfg.OAuth == nil {
return envelope.NewError(envelope.InputError, app.i18n.Ts("globals.messages.empty", "name", "oauth"), nil)
}
if cfg.OAuth.Provider != string(oauth.ProviderGoogle) && cfg.OAuth.Provider != string(oauth.ProviderMicrosoft) {
return envelope.NewError(envelope.InputError, app.i18n.T("globals.messages.somethingWentWrong"), nil)
}
if cfg.OAuth.ClientID == "" {
return envelope.NewError(envelope.InputError, app.i18n.Ts("globals.messages.empty", "name", "oauth.client_id"), nil)
}
}
// Validate SMTP configs.
for i, smtp := range cfg.SMTP {
if smtp.Host == "" {
return envelope.NewError(envelope.InputError, app.i18n.Ts("globals.messages.empty", "name", "smtp.host"), nil)
}
if smtp.Port <= 0 {
return envelope.NewError(envelope.InputError, app.i18n.T("validation.invalidPortValue"), nil)
}
// Validate auth_protocol for password auth.
if cfg.AuthType != imodels.AuthTypeOAuth2 {
validAuthProtocols := map[string]bool{"": true, "none": true, "plain": true, "login": true, "cram": true}
if !validAuthProtocols[cfg.SMTP[i].AuthProtocol] {
return envelope.NewError(envelope.InputError, app.i18n.T("globals.messages.somethingWentWrong"), nil)
}
}
}
// Validate IMAP configs.
for _, imap := range cfg.IMAP {
if imap.Host == "" {
return envelope.NewError(envelope.InputError, app.i18n.Ts("globals.messages.empty", "name", "imap.host"), nil)
}
if imap.Port <= 0 {
return envelope.NewError(envelope.InputError, app.i18n.T("globals.messages.somethingWentWrong"), nil)
}
if imap.Mailbox == "" {
return envelope.NewError(envelope.InputError, app.i18n.Ts("globals.messages.empty", "name", "imap.mailbox"), nil)
}
// Validate tls_type.
validTLSTypes := map[string]bool{"none": true, "starttls": true, "tls": true}
if !validTLSTypes[imap.TLSType] {
return envelope.NewError(envelope.InputError, app.i18n.T("globals.messages.somethingWentWrong"), nil)
}
}
return nil
}
// trimInboxFields trims whitespace from inbox fields and its email config if applicable.
func trimInboxFields(inb *imodels.Inbox) error {
inb.Name = strings.TrimSpace(inb.Name)
inb.From = strings.TrimSpace(inb.From)
// Trim email config fields if this is an email channel.
if inb.Channel == inbox.ChannelEmail && len(inb.Config) > 0 {
var cfg imodels.Config
if err := json.Unmarshal(inb.Config, &cfg); err != nil {
return err
}
trimEmailConfig(&cfg)
trimmedConfig, err := json.Marshal(cfg)
if err != nil {
return err
}
inb.Config = trimmedConfig
}
return nil
}
// trimEmailConfig trims whitespace from email configuration fields.
// Passwords and secrets are intentionally NOT trimmed.
func trimEmailConfig(cfg *imodels.Config) {
cfg.ReplyTo = strings.TrimSpace(cfg.ReplyTo)
// Trim IMAP configs.
for i := range cfg.IMAP {
cfg.IMAP[i].Host = strings.TrimSpace(cfg.IMAP[i].Host)
cfg.IMAP[i].Username = strings.TrimSpace(cfg.IMAP[i].Username)
cfg.IMAP[i].Mailbox = strings.TrimSpace(cfg.IMAP[i].Mailbox)
}
// Trim SMTP configs.
for i := range cfg.SMTP {
cfg.SMTP[i].Host = strings.TrimSpace(cfg.SMTP[i].Host)
cfg.SMTP[i].Username = strings.TrimSpace(cfg.SMTP[i].Username)
cfg.SMTP[i].HelloHostname = strings.TrimSpace(cfg.SMTP[i].HelloHostname)
}
// Trim OAuth config.
if cfg.OAuth != nil {
cfg.OAuth.Provider = strings.TrimSpace(cfg.OAuth.Provider)
cfg.OAuth.ClientID = strings.TrimSpace(cfg.OAuth.ClientID)
cfg.OAuth.TenantID = strings.TrimSpace(cfg.OAuth.TenantID)
}
}
// validateTelegramConfig validates the Telegram inbox configuration.
func validateTelegramConfig(app *App, configJSON json.RawMessage) error {
var cfg telegram.Config
if err := json.Unmarshal(configJSON, &cfg); err != nil {
return envelope.NewError(envelope.InputError, app.i18n.T("globals.messages.somethingWentWrong"), nil)
}
if cfg.BotToken == "" {
return envelope.NewError(envelope.InputError, app.i18n.Ts("globals.messages.empty", "name", "bot_token"), nil)
}
return nil
}