-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathglobal.groovy
108 lines (81 loc) · 1.98 KB
/
global.groovy
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
globalHeaders (
Accept: JSON_TYPE,
"Content-Type": JSON_TYPE
)
env test {
baseUrl 'http://localhost:8080/'
}
env pro {
baseUrl 'http://localhost:8081/'
}
// tools functions
import java.security.MessageDigest
def md5(String s) {
MessageDigest.getInstance("MD5").digest(s.bytes).encodeHex().toString()
}
def String getToken(currentEnv, username, password) {
def loginUrl
if (currentEnv == "test") {
loginUrl = "http://localhost:8080/v1/user/login"
} else if (currentEnv == "pro") {
loginUrl = "http://localhost:8081/v1/user/login"
}
def loginResult = Unirest.post(loginUrl).headers([
Accept: JSON_TYPE,
"Content-Type": JSON_TYPE,
sign: getSign([username: username, password: password])
]).body("{username: '${username}', password: '${password}'}").asJson().body.object
return loginResult["token"]
}
SECRET_KEY = "123456"
def getSign(args) {
def sortedArgs = new TreeMap(args)
def entries = sortedArgs.collect({ k, v ->
"${-> k}=${-> v}"
})
md5("${String.join(';', entries)}$SECRET_KEY")
}
// global fixtures
fixture sign {
setUp {
if (body instanceof Map) {
String sign = getSign(body)
headers["sign"] = sign
}
}
}
fixture token {
setUp {
if (! headers["token"]) {
synchronized(global) {
if (! headers["token"]) {
headers["token"] = getToken(currentEnv, "samchi", "123456")
}
}
}
}
}
globalFixtures << [ "token", "sign" ]
// mock interceptor
mockInterceptor checkToken {
def path = req.pathInfo()
// 登录和注册无需检查token
if (path == "/v1/user/login" || path == "/v1/user/register") {
return
}
def token = req.headers("token")
if (! token) {
halt(200, [ code: 400, msg: "invalid token" ])
}
}
mockInterceptor checkSign {
def path = req.pathInfo()
// 上传文件无需检查sign
if (path == "/v1/user/upload") {
return
}
def sign = req.headers("sign")
if (! sign) {
halt(200, [ code: 400, msg: "invalid sign" ])
}
}