-
Notifications
You must be signed in to change notification settings - Fork 4
/
content_test.go
2935 lines (2346 loc) · 77.4 KB
/
content_test.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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import ()
var helpContent = `Usage:
wheel new APP_PATH [options] # Creates new app
wheel generate SUBJECT NAME ATTRIBUTES # Adds new CRUD to an existing app.
# SUBJECT: scaffold/model/entity/handler.
# NAME: name of the model, entity or handler
# ATTRIBUTES: when not a handler, is a pair of column name
# and column type separated by ":" i.e. description:string
# Available types are:
# string/text/integer/decimal/datetime/bool/reference.
# When a handler "attributes" are functions inside handler.
Options:
-G, [--skip-git] # Skip .gitignore file
More:
-h, [--help] # Show this help message and quit
-v, [--version] # Show Wheel version number and quit`
var versionContent = `Wheel 1.0`
var gitIgnoreContent = `/log/*.log`
var mainContent = `package main
import (
"flag"
"net/http"
"test_repository_hub.com/test_account/test_project/commons/app/model"
"test_repository_hub.com/test_account/test_project/commons/log"
"test_repository_hub.com/test_account/test_project/config"
"test_repository_hub.com/test_account/test_project/db/schema"
"test_repository_hub.com/test_account/test_project/routes"
)
func main() {
var mode string
var port string
var host string
flag.StringVar(&mode, "mode", "server", "run mode (options: server/migrate)")
flag.StringVar(&host, "host", "localhost", "http server host")
flag.StringVar(&port, "port", "8081", "http server port")
flag.Parse()
log.Info.Println("starting app", config.App.AppName)
model.Connect()
if mode == "migrate" {
schema.Migrate()
} else if mode == "s" || mode == "server" {
log.Fatal.Println(http.ListenAndServe(host+":"+port, routes.Routes(host, port)))
} else {
log.Fatal.Println("invalid run mode, please, use \"--help\" for more details")
}
}`
var routesContentV1 = `package routes
import (
"github.com/gorilla/mux"
"net/http"
"test_repository_hub.com/test_account/test_project/app/handlers"
"test_repository_hub.com/test_account/test_project/commons/app/handler"
"test_repository_hub.com/test_account/test_project/commons/log"
)
func Routes(host string, port string) *mux.Router {
router := mux.NewRouter().StrictSlash(true)
// middlewares
log.Info.Println("setting up middlewares")
router.Use(loggingMiddleware)
router.Use(authorizeMiddleware)
log.Info.Println("setting up routes")
log.Info.Println("listening on " + host + ":" + port + ", CTRL+C to stop")
router.NotFoundHandler = http.HandlerFunc(handler.Error404)
router.HandleFunc("/", handler.ApiRoot).Methods("GET")
// sessions
router.HandleFunc("/sessions/sign_in", handlers.SessionSignIn).Methods("POST")
router.HandleFunc("/sessions/sign_out", handlers.SessionSignOut).Methods("DELETE")
router.HandleFunc("/sessions/sign_up", handlers.SessionSignUp).Methods("POST")
router.HandleFunc("/sessions/password", handlers.SessionPassword).Methods("POST")
router.HandleFunc("/sessions/password", handlers.SessionRecovery).Methods("PUT")
router.HandleFunc("/sessions/refresh", handlers.SessionRefresh).Methods("POST")
// user
router.HandleFunc("/myself", handlers.MyselfShow).Methods("GET")
router.HandleFunc("/myself", handlers.MyselfUpdate).Methods("PUT")
router.HandleFunc("/myself/password", handlers.MyselfUpdatePassword).Methods("PUT")
router.HandleFunc("/myself", handlers.MyselfDestroy).Methods("DELETE")
// admin
router.HandleFunc("/users", handlers.UserList).Methods("GET")
router.HandleFunc("/users/{id}", handlers.UserShow).Methods("GET")
router.HandleFunc("/users", handlers.UserCreate).Methods("POST")
router.HandleFunc("/users/{id}", handlers.UserUpdate).Methods("PUT")
router.HandleFunc("/users/{id}/password", handlers.UserUpdatePassword).Methods("PUT")
router.HandleFunc("/users/{id}", handlers.UserDestroy).Methods("DELETE")
return router
}`
var middlewareContent = `package routes
import (
"bytes"
"errors"
"io/ioutil"
"net/http"
"regexp"
"strings"
"test_repository_hub.com/test_account/test_project/app/handlers"
"test_repository_hub.com/test_account/test_project/app/user"
"test_repository_hub.com/test_account/test_project/commons/app/handler"
"test_repository_hub.com/test_account/test_project/commons/log"
"test_repository_hub.com/test_account/test_project/db/entities"
)
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Info.Println(r.Method + ": " + filterUrlValues(r.URL.Path, r.URL.Query()) + " for " + r.RemoteAddr)
if strings.Trim(r.Header.Get("Content-Type"), " \n") == "application/json" {
body, err := ioutil.ReadAll(r.Body)
if err == nil {
log.Info.Println("Body JSON:", filterJsonValues(string(body)))
// put the body content back
r.Body = ioutil.NopCloser(strings.NewReader(string(body)))
} else {
log.Error.Println("loggingMiddlware: ", err)
}
} else {
r.ParseMultipartForm(100 * 1024)
log.Info.Println("Form-data: " + filterFormValues(r.Form))
}
next.ServeHTTP(w, r)
})
}
func authorizeMiddleware(next http.Handler) http.Handler {
var userId uint
var err error
var userRole string
var signedInUser entities.User
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
userId = 0
err = nil
userRole = "public"
userId, err = checkToken(r.Header.Get("Authorization"))
if err == nil {
if signedInUser, err = checkSignedInUser(userId); err == nil {
userRole = "signed_in"
}
if userRole == "signed_in" && checkAdminUser(user.Current) {
userRole = "admin"
}
}
if GrantPermission(r.RequestURI, r.Method, userRole) {
next.ServeHTTP(w, r)
} else if userRole == "public" {
handler.Error401(w, r)
} else {
handler.Error403(w, r)
}
})
}
func checkAdminUser(signedInUser entities.User) bool {
if signedInUser.Admin {
log.Info.Println("admin access granted to user")
return true
} else {
log.Info.Println("admin access denied to user")
return false
}
}
func checkSignedInUser(userId uint) (entities.User, error) {
log.Info.Printf("checking user id: %d...\n", userId)
if userId == 0 {
log.Info.Println("user is not available")
return entities.User{}, errors.New("user is not available")
} else if signedInUser, err := user.Find(userId); err == nil {
user.SetCurrent(userId)
log.Info.Println("user was found")
return signedInUser, nil
} else {
log.Info.Println("user was not found")
return signedInUser, errors.New("user was not found")
}
}
func checkToken(token string) (uint, error) {
log.Info.Println("checking token...")
if token == "" {
log.Info.Println("token was not sent")
return 0, nil
} else {
return validateToken(token)
}
}
func validateToken(token string) (uint, error) {
log.Info.Println("validating token...")
userId, err := handlers.SessionCheck(token)
if err == nil {
log.Info.Println("token is valid")
return userId, nil
} else {
log.Info.Println("invalid token")
return 0, errors.New("invalid token")
}
}
func filterParamsValues(queries map[string][]string) map[string][]string {
var filter = regexp.MustCompile(` + "`" + `(?i)(password)|(token)` + "`" + `)
queries_filtered := make(map[string][]string)
for key := range queries {
if filter.MatchString(key) {
queries_filtered[key] = []string{"[FILTERED]"}
} else {
queries_filtered[key] = []string{}
for _, element := range queries[key] {
queries_filtered[key] = append(queries_filtered[key], element)
}
}
}
return queries_filtered
}
func filterUrlValues(path string, queries map[string][]string) string {
var firstParam = true
queries_filtered := filterParamsValues(queries)
for key := range queries_filtered {
if firstParam {
path = path + "?"
firstParam = false
} else {
path = path + "&"
}
path = path + key + "=" + strings.Join(queries_filtered[key], " ")
}
return path
}
func filterFormValues(queries map[string][]string) string {
var buffer bytes.Buffer
var index int
queries_filtered := filterParamsValues(queries)
index = 0
buffer.WriteString("{ ")
for key := range queries_filtered {
buffer.WriteString("\"")
buffer.WriteString(key)
buffer.WriteString("\": \"")
buffer.WriteString(strings.Join(queries_filtered[key], " "))
buffer.WriteString("\"")
if (index + 1) != len(queries_filtered) {
buffer.WriteString(", ")
}
index++
}
buffer.WriteString(" }")
return buffer.String()
}
func filterJsonValues(inputJson string) string {
type Point struct {
StartAt int
EndAt int
}
var filter = regexp.MustCompile(` + "`" + `(?i)(password)|(token)` + "`" + `)
var regexpWhiteSpace = regexp.MustCompile(` + "`" + `[\s\t\n]{1}` + "`" + `)
var stack []string
var key, currentChar string
var valueStartAt, valueEndAt, keyStartAt, keyEndAt int
var points []Point
substring := []rune(inputJson)
isCharBeforeEscape := false
isKey := false
isValue := false
for i := 0; i < len(inputJson); i++ {
currentChar = string(inputJson[i])
if regexpWhiteSpace.MatchString(currentChar) && (len(stack) == 0 || stack[len(stack)-1] != ` + "`" + `"` + "`" + ` || stack[len(stack)-1] == ` + "`" + `:` + "`" + `) {
currentChar = currentChar
} else if currentChar == "{" && (len(stack) == 0 || stack[len(stack)-1] == "{") {
stack = append(stack, "{")
} else if currentChar == ":" && (len(stack) == 0 || stack[len(stack)-1] == "{") {
stack = append(stack, ":")
} else if currentChar == "}" && (len(stack) > 0 && stack[len(stack)-1] == "{") {
stack = stack[:len(stack)-1]
} else if currentChar == ` + "`" + `"` + "`" + ` && (len(stack) > 0 && stack[len(stack)-1] == ":") && !isCharBeforeEscape {
stack = stack[:len(stack)-1]
stack = append(stack, ` + "`" + `"` + "`" + `)
isValue = true
isKey = false
valueStartAt = i + 1
} else if currentChar == ` + "`" + `"` + "`" + ` && (len(stack) > 0 && stack[len(stack)-1] == ` + "`" + `"` + "`" + `) && isValue && !isCharBeforeEscape {
stack = stack[:len(stack)-1]
isValue = false
isKey = false
valueEndAt = i
if filter.MatchString(key) {
points = append(points, Point{StartAt: valueStartAt, EndAt: valueEndAt})
}
} else if currentChar == ` + "`" + `"` + "`" + ` && (len(stack) > 0 && stack[len(stack)-1] == "{") && !isCharBeforeEscape {
isKey = true
isValue = false
stack = append(stack, ` + "`" + `"` + "`" + `)
keyStartAt = i + 1
} else if currentChar == ` + "`" + `"` + "`" + ` && (len(stack) > 0 && stack[len(stack)-1] == ` + "`" + `"` + "`" + `) && isKey && !isCharBeforeEscape {
isKey = false
isValue = false
stack = stack[:len(stack)-1]
keyEndAt = i
key = string(substring[keyStartAt:keyEndAt])
}
if currentChar == ` + "`" + `\` + "`" + ` && (len(stack) > 0 && stack[len(stack)-1] == ` + "`" + `"` + "`" + `) {
isCharBeforeEscape = true
} else if isCharBeforeEscape {
isCharBeforeEscape = false
}
}
if len(points) > 0 {
for i := len(points) - 1; i >= 0; i-- {
inputJson = string(substring[0:points[i].StartAt]) + "[FILTERED]" + string(substring[points[i].EndAt:len(inputJson)])
substring = []rune(inputJson)
}
}
return inputJson
}`
var authorizeContentV1 = `package routes
import (
"regexp"
)
type Permission struct {
UrlRegexp *regexp.Regexp
Methods []string
UserRoles []string
}
var Permissions []Permission
func GrantPermission(url string, method string, userRole string) bool {
for _, permission := range Permissions {
if permission.UrlRegexp.MatchString(url) && checkItem(method, permission.Methods) && checkItem(userRole, permission.UserRoles) {
return true
}
}
return false
}
func checkItem(currrent string, availables []string) bool {
for _, item := range availables {
if item == currrent {
return true
}
}
return false
}
func init() {
Permissions = append(Permissions,
Permission{
UrlRegexp: regexp.MustCompile(` + "`" + `\A\/{0,1}\z` + "`" + `),
Methods: []string{"GET"},
UserRoles: []string{"public", "signed_in", "admin"},
})
Permissions = append(Permissions,
Permission{
UrlRegexp: regexp.MustCompile(` + "`" + `\A\/sessions\/(sign_in|sign_up|password)(\/){0,1}.*\z` + "`" + `),
Methods: []string{"GET", "POST", "DELETE"},
UserRoles: []string{"public"},
})
Permissions = append(Permissions,
Permission{
UrlRegexp: regexp.MustCompile(` + "`" + `\A\/sessions\/sign_out(\/){0,1}.*\z` + "`" + `),
Methods: []string{"DELETE"},
UserRoles: []string{"admin", "signed_in"},
})
Permissions = append(Permissions,
Permission{
UrlRegexp: regexp.MustCompile(` + "`" + `\A\/sessions\/refresh(\/){0,1}.*\z` + "`" + `),
Methods: []string{"POST"},
UserRoles: []string{"admin", "signed_in"},
})
Permissions = append(Permissions,
Permission{
UrlRegexp: regexp.MustCompile(` + "`" + `\A\/users(\/){0,1}.*\z` + "`" + `),
Methods: []string{"GET", "POST", "DELETE", "PUT"},
UserRoles: []string{"admin"},
})
Permissions = append(Permissions,
Permission{
UrlRegexp: regexp.MustCompile(` + "`" + `\A\/myself(\/){0,1}.*\z` + "`" + `),
Methods: []string{"GET", "POST", "DELETE", "PUT"},
UserRoles: []string{"admin", "signed_in"},
})
}`
var localePtBrContent = `# encoding: UTF-8
welcome: 'Bem vindo(a)'
password_recovery_instructions: 'Instruções de Recuperação de Senha'`
var localeEnContent = `# encoding: UTF-8
welcome: 'Welcome'
password_recovery_instructions: 'Password Recovery Instructions'`
var configAppContent = `app_name: "test_project"
app_repository: "test_repository_hub.com/test_account/test_project"
frontend_base_url: "https://example.com"
secret_key: "0B7f3892773a0be1E4C6c992f9D4BcdB96Bf2277665133d8CdE18FfED0ECcF7d4a5e7114d4c5fDD3430ad9d87A1C705aACfBCBBD928B38248aBd48Ff8bDdA5E0"
reset_password_expiration_seconds: 172800
token_expiration_seconds: 7200
pagination:
default: 20
maximum: 50
locales:
- "en"
- "pt-BR"`
var configConfigContent = `package config
import (
"gopkg.in/yaml.v2"
"io/ioutil"
"test_repository_hub.com/test_account/test_project/commons/log"
)
type Pagination struct {
Default int ` + "`" + `yaml:"default"` + "`" + `
Maximum int ` + "`" + `yaml:"maximum"` + "`" + `
}
type AppConfig struct {
AppName string ` + "`" + `yaml:"app_name"` + "`" + `
AppRepository string ` + "`" + `yaml:"app_repository"` + "`" + `
SecretKey string ` + "`" + `yaml:"secret_key"` + "`" + `
ResetPasswordExpirationSeconds int ` + "`" + `yaml:"reset_password_expiration_seconds"` + "`" + `
ResetPasswordUrl string ` + "`" + `yaml:"reset_password_url"` + "`" + `
TokenExpirationSeconds int ` + "`" + `yaml:"token_expiration_seconds"` + "`" + `
Pagination Pagination ` + "`" + `yaml:"pagination"` + "`" + `
Locales []string ` + "`" + `yaml:"locales"` + "`" + `
}
var App AppConfig
func readAppConfigFile() []byte {
data, err := ioutil.ReadFile("./config/app.yml")
if err != nil {
log.Error.Fatal(err)
}
return data
}
func init() {
err := yaml.Unmarshal(readAppConfigFile(), &App)
if err != nil {
log.Error.Fatalf("error: %v", err)
}
}`
var configDatabaseContent = `host: localhost
port: 5432
user: root
dbname: test_project
password: Secret123!
sslmode: disable
pool: 10`
var configEmailContent = `user: 'no-reply0@example.com'
name: 'No Reply'
password: 'Secret123!'
address: 'smtp.example.com'
port: 25`
var mailerContent = `package mailer
import (
"crypto/tls"
"fmt"
"github.com/adilsonchacon/blog/commons/log"
"gopkg.in/yaml.v2"
"io/ioutil"
"net"
"net/mail"
"net/smtp"
"regexp"
"strconv"
"strings"
)
type Config struct {
User string
Name string
Password string
Address string
Port int
}
var (
from mail.Address
to []mail.Address
cc []mail.Address
bcc []mail.Address
validEmail = regexp.MustCompile(` + "`" + `\A[^@]+@([^@\.]+\.)+[^@\.]+\z` + "`" + `)
)
func SetFrom(name string, tEmail string) {
if validEmail.MatchString(tEmail) {
from = mail.Address{name, tEmail}
} else {
log.Error.Println("email is invalid")
}
}
func AddTo(name string, tEmail string) {
if validEmail.MatchString(tEmail) {
to = append(to, mail.Address{name, tEmail})
} else {
log.Error.Println("email is invalid")
}
}
func AddCc(name string, tEmail string) {
if validEmail.MatchString(tEmail) {
cc = append(cc, mail.Address{name, tEmail})
} else {
log.Error.Println("email is invalid")
}
}
func AddBcc(name string, tEmail string) {
if validEmail.MatchString(tEmail) {
bcc = append(bcc, mail.Address{name, tEmail})
} else {
log.Error.Println("email is invalid")
}
}
func ResetReceipts() {
SetFrom("", "")
to = to[:0]
cc = cc[:0]
bcc = bcc[:0]
}
func Send(subject string, body string, html bool) {
receipts := Receipts()
headers := make(map[string]string)
config, err := loadConfigFile()
if err != nil {
log.Error.Println("mailer.Send", err)
return
}
if from.String() == "<@>" {
from = mail.Address{config.Name, config.User}
}
// Setup header
headers["From"] = from.String()
if len(to) > 0 {
headers["To"] = stringfy("to")
}
if len(cc) > 0 {
headers["Cc"] = stringfy("cc")
}
if len(bcc) > 0 {
headers["Bcc"] = stringfy("bcc")
}
if html {
headers["MIME-version"] = "1.0;\nContent-Type: text/html; charset=\"UTF-8\";"
}
headers["Subject"] = subject
// Setup message
message := ""
for k, v := range headers {
message += fmt.Sprintf("%s: %s\r\n", k, v)
}
message += "\r\n" + body
// Connect to the SMTP Server
servername := config.Address + ":" + strconv.Itoa(config.Port)
host, _, _ := net.SplitHostPort(servername)
auth := smtp.PlainAuth("", config.User, config.Password, host)
err = checkHost(host)
if err != nil {
log.Error.Println("mailer.Send", err)
return
}
// TLS config
tlsconfig := &tls.Config{
InsecureSkipVerify: true,
ServerName: host,
}
// Here is the key, you need to call tls.Dial instead of smtp.Dial
// for smtp servers running on 465 that require an ssl connection
// from the very beginning (no starttls)
conn, err := tls.Dial("tcp", servername, tlsconfig)
if err != nil {
log.Error.Println("mailer.Send", err)
return
}
client, err := smtp.NewClient(conn, host)
if err != nil {
log.Error.Println("mailer.Send", err)
return
}
// Auth
if err = client.Auth(auth); err != nil {
log.Error.Println("mailer.Send", err)
return
}
// To
if err = client.Mail(from.Address); err != nil {
log.Error.Println("mailer.Send", err)
return
}
// To, Cc and Bcc
for i := 0; i < len(receipts); i++ {
if err = client.Rcpt(receipts[0]); err != nil {
log.Error.Println("mailer.Send", err)
return
}
}
// Data
socket, err := client.Data()
if err != nil {
log.Error.Println("mailer.Send", err)
return
}
_, err = socket.Write([]byte(message))
if err != nil {
log.Error.Println("mailer.Send", err)
return
}
err = socket.Close()
if err != nil {
log.Error.Println("mailer.Send", err)
return
}
client.Quit()
}
func stringfy(tType string) string {
var isTo = regexp.MustCompile(` + "`" + `(?i)\Ato\z` + "`" + `)
var isCc = regexp.MustCompile(` + "`" + `(?i)\Acc\z` + "`" + `)
var isBcc = regexp.MustCompile(` + "`" + `(?i)\Abcc\z` + "`" + `)
var isFrom = regexp.MustCompile(` + "`" + `(?i)\Afrom\z` + "`" + `)
var auxEmail []mail.Address
var auxString []string
if isTo.MatchString(tType) {
auxEmail = to
} else if isCc.MatchString(tType) {
auxEmail = cc
} else if isBcc.MatchString(tType) {
auxEmail = bcc
} else if isFrom.MatchString(tType) {
auxEmail = append(auxEmail, from)
} else {
log.Error.Println("Invalid param for stringfy, available params are to, cc, bcc and from")
}
for i := 0; i < len(auxEmail); i++ {
auxString = append(auxString, auxEmail[i].Address)
}
return strings.Join(auxString, "; ")
}
func Receipts() []string {
var receipts []string
for i := 0; i < len(to); i++ {
receipts = append(receipts, to[0].Address)
}
for i := 0; i < len(cc); i++ {
receipts = append(receipts, cc[0].Address)
}
for i := 0; i < len(bcc); i++ {
receipts = append(receipts, bcc[0].Address)
}
return receipts
}
func loadConfigFile() (Config, error) {
config := Config{}
content, err := readConfigFile()
if err != nil {
return config, err
}
err = yaml.Unmarshal(content, &config)
if err != nil {
return config, err
}
return config, nil
}
func readConfigFile() ([]byte, error) {
data, err := ioutil.ReadFile("./config/email.yml")
if err != nil {
return nil, err
}
return data, nil
}
func checkHost(host string) error {
var err error
ip := net.ParseIP(host)
if ip == nil {
_, err = net.LookupHost(host)
if err != nil {
return err
}
} else {
_, err = net.LookupAddr(host)
if err != nil {
return err
}
}
return nil
}`
var commonsLogContent = `package log
import (
"fmt"
"io"
"log"
"os"
)
var writer = setWriter()
var (
Debug = log.New(writer, fmt.Sprintf("\033[94m[DEBUG]\033[39m "), log.LstdFlags)
Info = log.New(writer, fmt.Sprintf("\033[36m[INFO]\033[39m "), log.LstdFlags)
Warn = log.New(writer, fmt.Sprintf("\033[93m[WARN]\033[39m "), log.LstdFlags)
Error = log.New(writer, fmt.Sprintf("\033[91m[ERROR]\033[39m "), log.LstdFlags)
Fatal = log.New(writer, fmt.Sprintf("\033[90m[FATAL]\033[39m "), log.LstdFlags)
)
func setWriter() io.Writer {
os.MkdirAll("./log", 0755)
fileHandler, err := os.OpenFile("./log/app.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
return io.MultiWriter(os.Stdout, fileHandler)
}`
var commonsLocaleContent = `package locale
import (
"gopkg.in/yaml.v2"
"io/ioutil"
"test_repository_hub.com/test_account/test_project/commons/log"
)
type Keys struct {
Welcome string ` + "`" + `yaml:"welcome"` + "`" + `
PasswordRecoveryInstructions string ` + "`" + `yaml:"password_recovery_instructions"` + "`" + `
}
var I18n Keys
func Load(locale string) {
err := yaml.Unmarshal(readLocaleFile(locale), &I18n)
if err != nil {
log.Error.Fatal(err)
}
}
func readLocaleFile(locale string) []byte {
data, err := ioutil.ReadFile("./config/locales/" + locale + ".yml")
if err != nil {
log.Error.Fatal(err)
}
return data
}`
var commonsCryptoContent = `package crypto
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"golang.org/x/crypto/bcrypt"
"math/rand"
"test_repository_hub.com/test_account/test_project/commons/log"
"time"
)
func SetPassword(password string) string {
var err error
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
log.Error.Println(err)
}
return string(hash)
}
func CheckPassword(password string, hashedPassword string) bool {
var err error
err = bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
return err == nil
}
func RandString(size int) string {
var letters = []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
rand.Seed(time.Now().UnixNano())
b := make([]rune, size)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
func EncryptText(clearText string, key string) string {
mac := hmac.New(sha256.New, []byte(key))
mac.Write([]byte(clearText))
return hex.EncodeToString(mac.Sum(nil))
}`
var commonsConversorContent = `package conversor
import (
"regexp"
"strconv"
"strings"
"time"
)
func StringToInterface(contentType string, contentValue string) (interface{}, error) {
var regexpBooleanType = regexp.MustCompile(` + "`" + `bool` + "`" + `)
var regexpIntType = regexp.MustCompile(` + "`" + `int` + "`" + `)
var regexpFloatType = regexp.MustCompile(` + "`" + `float|double|decimal` + "`" + `)
var regexpDateTimeType = regexp.MustCompile(` + "`" + `time|date` + "`" + `)
var returnInterface interface{}
var err error
if regexpIntType.MatchString(contentType) {
returnInterface, err = StringToInt(contentValue)
} else if regexpFloatType.MatchString(contentType) {
returnInterface, err = StringToFloat(contentValue)
} else if regexpDateTimeType.MatchString(contentType) {
returnInterface, err = time.Parse(time.RFC3339, contentValue)
} else if regexpBooleanType.MatchString(contentType) {
returnInterface, err = StringToBoolean(contentValue)
} else {
returnInterface = contentValue
err = nil
}
return returnInterface, err
}
func StringToInt(valueContent string) (interface{}, error) {
return strconv.ParseInt(valueContent, 10, 64)
}
func StringToFloat(valueContent string) (interface{}, error) {
return strconv.ParseFloat(valueContent, 64)
}
func StringToBoolean(valueContent string) (interface{}, error) {
var checkFalse = regexp.MustCompile(` + "`" + `\A(0|f|false|no)\z` + "`" + `)
valueContent = strings.TrimSpace(valueContent)
if valueContent != "" {
if checkFalse.MatchString(valueContent) {
return false, nil
} else {
return true, nil
}
} else {
return false, nil
}
}`
var commonsAppViewContent = `package view
import ()
type DefaultMessage struct {
Message SystemMessage ` + "`" + `json:"system_message"` + "`" + `
}
type SystemMessage struct {
Type string ` + "`" + `json:"type"` + "`" + `
Content string ` + "`" + `json:"content"` + "`" + `
}
type ErrorMessage struct {
Message SystemMessage ` + "`" + `json:"system_message"` + "`" + `
Errors []string ` + "`" + `json:"errors"` + "`" + `
}
type MainPagination struct {
CurrentPage int ` + "`" + `json:"current_page"` + "`" + `
TotalPages int ` + "`" + `json:"total_pages"` + "`" + `
TotalEntries int ` + "`" + `json:"total_entries"` + "`" + `
}
func SetSystemMessage(mType string, content string) SystemMessage {
return SystemMessage{Type: mType, Content: content}
}
func SetDefaultMessage(mType string, content string) DefaultMessage {
return DefaultMessage{Message: SetSystemMessage(mType, content)}