forked from xxl-job/xxl-job-executor-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
120 lines (92 loc) · 1.89 KB
/
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package xxl
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/url"
"sync"
"time"
)
type Auth interface {
Login() ([]*http.Cookie, error)
}
type AuthImpl struct {
Addr string
UserName string
Password string
mu sync.Mutex
closeChan chan struct{}
cookies []*http.Cookie
}
func NewAuth(userName, password, addr string, interval time.Duration) (Auth, func(), error) {
auth := &AuthImpl{
UserName: userName,
Password: password,
Addr: addr,
closeChan: make(chan struct{}),
}
auth.CronReplaceCookie(interval)
return auth, func() {
auth.closeChan <- struct{}{}
}, nil
}
const loginUrl = "/login"
var LoginErr = errors.New("login failed")
// Login 登录
func (a *AuthImpl) Login() ([]*http.Cookie, error) {
if len(a.cookies) == 0 {
a.mu.Lock()
defer a.mu.Unlock()
if len(a.cookies) > 0 {
return a.cookies, nil
}
cookies, err := a.login()
if err != nil {
return nil, err
}
a.cookies = cookies
}
return a.cookies, nil
}
func (a *AuthImpl) CronReplaceCookie(interval time.Duration) {
go func(t time.Duration) {
ticker := time.NewTicker(t)
ReplaceXxlJonCookieLoop:
for {
select {
case <-ticker.C:
cookies, err := a.login()
if err != nil {
continue
}
a.cookies = cookies
case <-a.closeChan:
break ReplaceXxlJonCookieLoop
}
}
}(interval)
}
func (a *AuthImpl) login() ([]*http.Cookie, error) {
values := url.Values{}
values.Add("userName", a.UserName)
values.Add("password", a.Password)
resp, err := http.PostForm(a.Addr+loginUrl, values)
if err != nil {
return nil, err
}
defer resp.Body.Close()
all, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
response := &res{}
if err = json.Unmarshal(all, response); err != nil {
return nil, err
}
if response.Code == FailureCode {
return nil, LoginErr
}
cookies := resp.Cookies()
return cookies, nil
}