-
Notifications
You must be signed in to change notification settings - Fork 36
/
web.go
289 lines (263 loc) · 7.94 KB
/
web.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
)
type UserInfo struct {
Password string
Token string
}
type TokenInfo struct {
User string
Expired time.Time
}
type deviceInfo struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
IP string `json:"ip,omitempty"`
IPv6 string `json:"ipv6,omitempty"`
NatType string `json:"natType,omitempty"`
Bandwidth string `json:"bandwidth,omitempty"`
LanIP string `json:"lanip,omitempty"`
MAC string `json:"mac,omitempty"`
OS string `json:"os,omitempty"`
IsActive int `json:"isActive,omitempty"`
Version string `json:"version,omitempty"`
Remark string `json:"remark,omitempty"`
Removed int `json:"removed,omitempty"`
Activetime string `json:"activetime,omitempty"`
Addtime string `json:"addtime,omitempty"`
IsUpdate bool `json:"isUpdate,omitempty"`
}
type deviceList struct {
Nodes []deviceInfo `json:"nodes" binding:"required"`
LatestVer string `json:"latestVer,omitempty"`
}
var JWTSecret string
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// just token not jwt
auth, ok := c.Request.Header["Authorization"]
if !ok {
c.String(http.StatusUnauthorized, "")
c.Abort()
return
}
token, err := jwt.ParseWithClaims(auth[0], &OpenP2PClaim{}, func(token *jwt.Token) (interface{}, error) {
// Don't forget to validate the alg is what you expect:
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return []byte(JWTSecret), nil
})
if err != nil {
gLog.Println(LvERROR, "Parse token error:", err)
c.String(http.StatusUnauthorized, "")
c.Abort()
return
}
claims, ok := token.Claims.(*OpenP2PClaim)
if ok && token.Valid {
fmt.Println(claims)
if claims.StandardClaims.ExpiresAt < time.Now().Unix() {
c.String(http.StatusUnauthorized, "")
c.Abort()
return
}
}
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
c.Next()
}
}
func runWeb() {
router := gin.Default()
router.GET("/api/v1/devices", listDevices, AuthMiddleware())
router.GET("/api/v1/device/:name/restart", restartDevice, AuthMiddleware())
user := router.Group("/api/v1/user")
user.POST("/login", webLogin)
device := router.Group("/api/v1/device")
device.Use(AuthMiddleware())
device.GET("/:name/apps", listApps)
device.POST("/:name/app", editApp)
device.POST("/:name/switchapp", switchApp)
router.RunTLS(":10008", "api.crt", "api.key")
// router.Run(":10008")
}
func webLogin(c *gin.Context) {
data, _ := c.GetRawData()
req := ProfileInfo{}
err := json.Unmarshal(data, &req)
if err != nil {
log.Println("wrong loginReq")
return
}
gLog.Println(LvINFO, "wechatLogin:", req.User)
if req.User != gUser || req.Password != gPassword {
c.String(http.StatusBadRequest, "登录失败")
log.Println("authorize error:")
return
}
// new token
claim := OpenP2PClaim{
User: req.User,
InstallToken: fmt.Sprintf("%d", gToken),
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().AddDate(0, 0, 1).Unix(),
// ExpiresAt: time.Now().Add(time.Second * 60).Unix(), // test
Issuer: "openp2p.cn",
IssuedAt: time.Now().Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString([]byte(JWTSecret))
if err != nil {
fmt.Println(tokenString, JWTSecret, err)
return
}
log.Println("authorize ok:")
c.JSON(http.StatusOK, gin.H{
"token": tokenString,
"nodeToken": fmt.Sprintf("%d", gToken),
"error": 0,
})
}
func listDevices(c *gin.Context) {
gWSSessionMgr.allSessionsMtx.RLock()
defer gWSSessionMgr.allSessionsMtx.RUnlock()
// TODO: no query latestVer each request.
var latestVer string
nodes := deviceList{}
nodes.LatestVer = latestVer
// list online devices
for _, sess := range gWSSessionMgr.allSessions {
data := deviceInfo{}
data.Name = sess.node
data.NatType = fmt.Sprintf("%d", sess.natType)
data.Bandwidth = fmt.Sprintf("%d", sess.shareBandWidth)
data.IP = sess.IPv4
data.IPv6 = sess.IPv6
data.LanIP = sess.lanIP
data.MAC = sess.mac
data.OS = sess.os
data.Version = sess.version
data.Activetime = sess.activeTime.Local().String()
data.IsActive = 1
data.IsUpdate = true
data.ID = fmt.Sprintf("%d", nodeNameToID(data.Name))
nodes.Nodes = append(nodes.Nodes, data)
}
// TODO: list offline devices in mysql
log.Println("get devices:", nodes)
c.JSON(http.StatusOK, nodes)
}
func listApps(c *gin.Context) {
nodeName := c.Param("name")
uuid := nodeNameToID(nodeName)
gLog.Println(LvINFO, nodeName, " update")
gWSSessionMgr.allSessionsMtx.Lock()
sess, ok := gWSSessionMgr.allSessions[uuid]
gWSSessionMgr.allSessionsMtx.Unlock()
if !ok {
gLog.Printf(LvERROR, "listTunnel %d error: peer offline", uuid)
c.JSON(http.StatusOK, gin.H{"error": 1, "detail": "device offline"})
return
}
sess.write(MsgPush, MsgPushReportApps, nil)
// TODO verify token
// wait for the channel at most 5 seconds
select {
case msg := <-sess.rspCh:
c.String(http.StatusOK, "%s", msg)
case <-time.After(ClientAPITimeout):
// Timed out after 5 seconds!
log.Printf("listTunnel %d timeout.", uuid)
c.JSON(http.StatusNotFound, gin.H{"error": 9, "detail": "timeout"})
}
}
func editApp(c *gin.Context) {
nodeName := c.Param("name")
uuid := nodeNameToID(nodeName)
gWSSessionMgr.allSessionsMtx.Lock()
sess, ok := gWSSessionMgr.allSessions[uuid]
gWSSessionMgr.allSessionsMtx.Unlock()
if !ok {
gLog.Printf(LvERROR, "editApp %d error: peer offline", uuid)
c.JSON(http.StatusOK, gin.H{"error": 1, "detail": "device offline"})
return
}
app := AppInfo{}
buf, _ := c.GetRawData()
err := json.Unmarshal(buf, &app)
if err != nil {
gLog.Printf(LvERROR, "wrong AppInfo:%s", err)
c.String(http.StatusNotAcceptable, "")
return
}
gLog.Println(LvINFO, "edit app:", app)
sess.write(MsgPush, MsgPushEditApp, app)
c.String(http.StatusOK, "")
}
func switchApp(c *gin.Context) {
nodeName := c.Param("name")
uuid := nodeNameToID(nodeName)
gWSSessionMgr.allSessionsMtx.Lock()
sess, ok := gWSSessionMgr.allSessions[uuid]
gWSSessionMgr.allSessionsMtx.Unlock()
if !ok {
gLog.Printf(LvERROR, "switchApp %d error: peer offline", uuid)
c.JSON(http.StatusOK, gin.H{"error": 1, "detail": "device offline"})
return
}
app := AppInfo{}
buf, _ := c.GetRawData()
err := json.Unmarshal(buf, &app)
if err != nil {
gLog.Printf(LvERROR, "wrong AppInfo:%s", err)
c.String(http.StatusNotAcceptable, "")
return
}
gLog.Println(LvINFO, "switchApp app:", app)
sess.write(MsgPush, MsgPushSwitchApp, app)
c.String(http.StatusOK, "")
}
func init() {
}
type OpenP2PClaim struct {
User string `json:"user,omitempty"`
InstallToken string `json:"installToken,omitempty"`
jwt.StandardClaims
}
func restartDevice(c *gin.Context) {
nodeName := c.Param("name")
uuid := nodeNameToID(nodeName)
gLog.Println(LvINFO, nodeName, " restart")
gWSSessionMgr.allSessionsMtx.Lock()
sess, ok := gWSSessionMgr.allSessions[uuid]
gWSSessionMgr.allSessionsMtx.Unlock()
if !ok {
gLog.Printf(LvERROR, "push to %s error: peer offline", nodeName)
c.JSON(http.StatusOK, gin.H{"error": 1, "detail": "device offline"})
return
}
sess.write(MsgPush, MsgPushRestart, nil)
c.JSON(http.StatusOK, gin.H{"error": 0})
}