generated from streamingriver/template
-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
tokens.go
126 lines (111 loc) · 2.09 KB
/
tokens.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
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net"
"net/http"
"strings"
"sync"
"time"
)
func NewTokens(url string, other ...interface{}) *Tokens {
t := &Tokens{
fetchFrom: url,
mu: &sync.RWMutex{},
workerMu: &sync.RWMutex{},
maps: &T{make(map[string]bool), make(map[string]string), make(map[string]string)},
work: false,
}
return t
}
type Tokens struct {
fetchFrom string
mu *sync.RWMutex
workerMu *sync.RWMutex
maps *T
work bool
}
type T struct {
ADDR map[string]bool `json:"addr"`
IP map[string]string `json:"ip"`
CH map[string]string `json:"ch"`
}
// Check if user match conditions and can watch
func (t Tokens) Check(token, channel string, req *http.Request) bool {
t.mu.RLock()
defer t.mu.RUnlock()
host := req.Header.Get("X-Real-IP")
if strings.Contains(req.Header.Get("X-Real-IP"), ":") {
var err error
host, _, err = net.SplitHostPort(req.Header.Get("X-Real-IP"))
if err != nil {
log.Printf("%v", err)
return false
}
}
ip, ok := t.maps.IP[token]
if !ok {
return false
}
if ip != host {
return false
}
ch, ok := t.maps.CH[token]
if !ok {
return false
}
if ch != channel {
return false
}
return true
}
// Worker periodicaly fetches tokens from api
func (t *Tokens) Worker() {
t.workerMu.Lock()
defer t.workerMu.Unlock()
t.work = true
go t.updateTokens()
}
func (t *Tokens) StopWorker() {
t.workerMu.Lock()
defer t.workerMu.Unlock()
t.work = false
}
func (t *Tokens) updateTokens() {
for {
t.workerMu.RLock()
if !t.work {
t.workerMu.RUnlock()
break
}
t.workerMu.RUnlock()
t.tokens()
time.Sleep(2 * time.Second)
}
}
func (t *Tokens) tokens() {
body := t.remoteGet(t.fetchFrom)
if body == nil {
return
}
t.mu.Lock()
err := json.Unmarshal(body, t.maps)
t.mu.Unlock()
if err != nil {
log.Printf("updateTokens error: %v", err)
return
}
}
func (t *Tokens) remoteGet(url string) []byte {
response, err := http.Get(url)
if err != nil {
return nil
}
defer response.Body.Close()
b, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil
}
return b
}