/
auth.go
62 lines (50 loc) · 1.01 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
package engin
import (
"net/http"
"strings"
"sync"
"time"
"github.com/astaxie/beego/logs"
)
type AuthItem struct {
Address string
Login time.Time
}
type AuthCtrl struct {
sync.RWMutex
Cache map[string]AuthItem
}
var authctrl AuthCtrl
func init() {
authctrl.Cache = make(map[string]AuthItem, 100)
go func() {
for {
now := time.Now()
authctrl.Lock()
for _, v := range authctrl.Cache {
if now.Sub(v.Login) > time.Hour {
logs.Info("auth ctrl address %s lease timeout", v.Address)
delete(authctrl.Cache, v.Address)
}
}
authctrl.Unlock()
time.Sleep(time.Minute)
}
}()
}
func AuthLogin(r *http.Request) {
address := strings.Split(r.RemoteAddr, ":")[0]
authctrl.Lock()
defer authctrl.Unlock()
authctrl.Cache[address] = AuthItem{Address: address, Login: time.Now()}
}
func AuthCache(r *http.Request) bool {
address := strings.Split(r.RemoteAddr, ":")[0]
authctrl.RLock()
defer authctrl.RUnlock()
_, ok := authctrl.Cache[address]
if ok {
return true
}
return false
}