1
|
|
|
package utils |
2
|
|
|
|
3
|
|
|
import ( |
4
|
|
|
"crypto/rand" |
5
|
|
|
"crypto/tls" |
6
|
|
|
"encoding/hex" |
7
|
|
|
"fmt" |
8
|
|
|
"github.com/joho/godotenv" |
9
|
|
|
gomail "gopkg.in/mail.v2" |
10
|
|
|
"log" |
11
|
|
|
"math/big" |
12
|
|
|
"os" |
13
|
|
|
"strconv" |
14
|
|
|
) |
15
|
|
|
|
16
|
|
|
// GenerateSecretCode generates a secret code |
17
|
|
|
func GenerateSecretCode(length int) string { |
18
|
|
|
// Generate a random string of letters and digits |
19
|
|
|
b := make([]byte, length) |
20
|
|
|
if _, err := rand.Read(b); err != nil { |
21
|
|
|
return "" |
22
|
|
|
} |
23
|
|
|
return hex.EncodeToString(b) |
24
|
|
|
} |
25
|
|
|
|
26
|
|
|
// GenerateRandomDigit GetRandomNumber returns a random number between min and max |
27
|
|
|
func GenerateRandomDigit(min, max int64) (string, error) { |
28
|
|
|
// Set max and min value |
29
|
|
|
randomNumber, err := rand.Int(rand.Reader, big.NewInt(max-min)) |
30
|
|
|
if err != nil { |
31
|
|
|
return "0", err |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
return strconv.FormatInt(randomNumber.Int64()+min, 10), nil |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
// GetSmtpConfig returns a gomail.Dialer and gomail.Message |
38
|
|
|
func getSMTPConfig() (*gomail.Dialer, *gomail.Message) { |
39
|
|
|
// Load the .env file |
40
|
|
|
err := godotenv.Load() |
41
|
|
|
if err != nil { |
42
|
|
|
log.Fatal("Error loading .env file") |
43
|
|
|
} |
44
|
|
|
password := os.Getenv("SMTP_PASSWORD") |
45
|
|
|
host := os.Getenv("SMTP_HOST") |
46
|
|
|
port, _ := strconv.Atoi(os.Getenv("SMTP_PORT")) |
47
|
|
|
from := os.Getenv("SMTP_USER") |
48
|
|
|
|
49
|
|
|
// Settings for SMTP server |
50
|
|
|
d := gomail.NewDialer(host, port, from, password) |
51
|
|
|
d.TLSConfig = &tls.Config{ |
52
|
|
|
InsecureSkipVerify: false, |
53
|
|
|
MinVersion: tls.VersionTLS12, |
54
|
|
|
MaxVersion: 0, |
55
|
|
|
ServerName: host, |
56
|
|
|
} |
57
|
|
|
m := gomail.NewMessage() |
58
|
|
|
m.SetHeader("From", from) |
59
|
|
|
return d, m |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
// SendEmail sends an email to the given address |
63
|
|
|
func SendEmail(email, subject, body string) error { |
64
|
|
|
// Send email |
65
|
|
|
|
66
|
|
|
d, m := getSMTPConfig() |
67
|
|
|
|
68
|
|
|
// Set E-Mail receivers |
69
|
|
|
m.SetHeader("To", email) |
70
|
|
|
|
71
|
|
|
// Set E-Mail subject |
72
|
|
|
m.SetHeader("Subject", subject) |
73
|
|
|
|
74
|
|
|
// Set E-Mail body. You can set plain text or html with text/html |
75
|
|
|
m.SetBody("text/plain", body) |
76
|
|
|
|
77
|
|
|
// Now send E-Mail |
78
|
|
|
if err := d.DialAndSend(m); err != nil { |
79
|
|
|
fmt.Println(err) |
80
|
|
|
panic(err) |
81
|
|
|
} |
82
|
|
|
return nil |
83
|
|
|
} |
84
|
|
|
|