-
Notifications
You must be signed in to change notification settings - Fork 1
/
login_auth.go
97 lines (82 loc) · 2.1 KB
/
login_auth.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
// Copyright 2020-2024 NGR Softlab
package emailer
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net/smtp"
"time"
)
// loginAuth struct for login auth
type loginAuth struct {
username, password string
}
// LoginAuth auth with login and password
func LoginAuth(username, password string) smtp.Auth {
return &loginAuth{username, password}
}
// Start login auth start
func (a *loginAuth) Start(_ *smtp.ServerInfo) (string, []byte, error) {
return "LOGIN", []byte{}, nil
}
// Next loginAuth
func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
if more {
switch string(fromServer) {
case "Username:":
return []byte(a.username), nil
case "Password:":
return []byte(a.password), nil
default:
return nil, errors.New("unknown fromServer")
}
}
return nil, nil
}
////////////////////////////////////////////////////
// TestLoginAuth - test smtp server login auth
func TestLoginAuth(
host string, port int,
tlsOn bool, tlsConfig *tls.Config,
user, password string,
connTimeout time.Duration) (connError error, authError error) {
c, connError := smtp.Dial(fmt.Sprintf("%s:%v", host, port))
if connError != nil {
return connError, nil
}
defer func() {
if errClose := c.Close(); errClose != nil {
logger.Errorf("smtp conn close error: %s", errClose.Error())
}
}()
if tlsOn {
if connError = c.StartTLS(tlsConfig); connError != nil {
logger.Errorf("start tsl error: %s", connError.Error())
return connError, nil
}
}
ctx, cancel := context.WithTimeout(
context.Background(),
connTimeout)
go func(ctx context.Context) {
defer cancel()
if authError = c.Auth(LoginAuth(user, password)); authError != nil {
logger.Errorf("auth error: %s", authError.Error())
}
}(ctx)
select {
case <-ctx.Done():
switch ctx.Err() {
case context.DeadlineExceeded:
logger.Error("smtp auth conn deadline")
authError = errors.New("auth conn deadline is over")
case context.Canceled:
logger.Info("smtp auth conn cancel by timeout")
}
}
if authError != nil {
logger.Errorf("smtp auth conn test error: %s", authError.Error())
}
return connError, authError
}