/
handler.go
executable file
·374 lines (311 loc) · 9.13 KB
/
handler.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
/*
Copyright 2016 Medcl (m AT medcl.net)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package api
import (
"encoding/json"
log "github.com/cihub/seelog"
"github.com/jmoiron/jsonq"
"infini.sh/framework/core/api/router"
"infini.sh/framework/core/errors"
"infini.sh/framework/core/util"
"io/ioutil"
"net/http"
"strings"
)
// Method is object of http method
type Method string
const (
// GET is http get method
GET Method = "GET"
// POST is http post method
POST Method = "POST"
// PUT is http put method
PUT Method = "PUT"
// DELETE is http delete method
DELETE Method = "DELETE"
// HEAD is http head method
HEAD Method = "HEAD"
OPTIONS Method = "OPTIONS"
)
// String return http method as string
func (method Method) String() string {
switch method {
case GET:
return "GET"
case POST:
return "POST"
case PUT:
return "PUT"
case DELETE:
return "DELETE"
case HEAD:
return "HEAD"
}
return "N/A"
}
// Handler is the object of http handler
type Handler struct {
wroteHeader bool
//w http.ResponseWriter
//req *http.Request
//
formParsed bool
}
// WriteHeader write status code to http header
func (handler Handler) WriteHeader(w http.ResponseWriter, code int) {
if apiConfig.TLSConfig.TLSEnabled {
w.Header().Add("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
}
w.WriteHeader(code)
handler.wroteHeader = true
}
// Get http parameter or return default value
func (handler Handler) Get(req *http.Request, key string, defaultValue string) string {
if !handler.formParsed {
req.ParseForm()
}
if len(req.Form) > 0 {
return req.Form.Get(key)
}
return defaultValue
}
// GetHeader return specify http header or return default value if not set
func (handler Handler) GetHeader(req *http.Request, key string, defaultValue string) string {
v := req.Header.Get(key)
if strings.TrimSpace(v) == "" {
return defaultValue
}
return v
}
// EncodeJSON encode the object to json string
func (handler Handler) EncodeJSON(v interface{}) (b []byte, err error) {
//if(w.Get("pretty","false")=="true"){
b, err = json.MarshalIndent(v, "", " ")
//}else{
// b, err = json.Marshal(v)
//}
if err != nil {
return nil, err
}
return b, nil
}
// WriteJSONHeader will write standard json header
func (handler Handler) WriteJSONHeader(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
handler.wroteHeader = true
}
// Result is a general json result
type Result struct {
Total int `json:"total"`
Result interface{} `json:"result"`
}
// WriteJSONListResult output result list to json format
func (handler Handler) WriteJSONListResult(w http.ResponseWriter, total int, v interface{}, statusCode int) error {
result := Result{}
result.Total = total
result.Result = v
return handler.WriteJSON(w, result, statusCode)
}
// WriteJSON output signal result with json format
func (handler Handler) WriteJSON(w http.ResponseWriter, v interface{}, statusCode int) error {
if !handler.wroteHeader {
handler.WriteJSONHeader(w)
w.WriteHeader(statusCode)
}
b, err := handler.EncodeJSON(v)
if err != nil {
return err
}
_, err = w.Write(b)
if err != nil {
return err
}
return nil
}
func (handler Handler) WriteAckJSON(w http.ResponseWriter, ack bool) error {
if !handler.wroteHeader {
handler.WriteJSONHeader(w)
w.WriteHeader(200)
}
v := map[string]bool{}
v["ok"] = ack
b, err := handler.EncodeJSON(v)
if err != nil {
return err
}
_, err = w.Write(b)
if err != nil {
return err
}
return nil
}
// GetParameter return query parameter with argument name
func (handler Handler) GetParameter(r *http.Request, key string) string {
return r.URL.Query().Get(key)
}
// GetParameterOrDefault return query parameter or return default value
func (handler Handler) GetParameterOrDefault(r *http.Request, key string, defaultValue string) string {
v := r.URL.Query().Get(key)
if len(v) > 0 {
return v
}
return defaultValue
}
// GetIntOrDefault return parameter or default, data type is int
func (handler Handler) GetIntOrDefault(r *http.Request, key string, defaultValue int) int {
v := handler.GetParameter(r, key)
s, ok := util.ToInt(v)
if ok != nil {
return defaultValue
}
return s
}
// GetJSON return json input
func (handler Handler) GetJSON(r *http.Request) (*jsonq.JsonQuery, error) {
content, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err != nil {
return nil, err
}
if len(content) == 0 {
return nil, errors.NewWithCode(err, errors.JSONIsEmpty, r.URL.String())
}
data := map[string]interface{}{}
dec := json.NewDecoder(strings.NewReader(string(content)))
dec.Decode(&data)
jq := jsonq.NewQuery(data)
return jq, nil
}
func (handler Handler) DecodeJSON(r *http.Request, o interface{}) error {
content, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err != nil {
return err
}
if len(content) == 0 {
return errors.NewWithCode(err, errors.JSONIsEmpty, r.URL.String())
}
return json.Unmarshal(content, o)
}
// GetRawBody return raw http request body
func (handler Handler) GetRawBody(r *http.Request) ([]byte, error) {
content, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err != nil {
return nil, err
}
if len(content) == 0 {
return nil, errors.NewWithCode(err, errors.BodyEmpty, r.URL.String())
}
return content, nil
}
// Write response to client
func (handler Handler) Write(w http.ResponseWriter, b []byte) (int, error) {
return w.Write(b)
}
// Error404 output 404 response
func (handler Handler) Error404(w http.ResponseWriter) {
handler.WriteJSON(w, map[string]interface{}{"error": 404}, http.StatusNotFound)
}
// Error500 output 500 response
func (handler Handler) Error500(w http.ResponseWriter, msg string) {
handler.WriteJSON(w, map[string]interface{}{"error": msg}, http.StatusInternalServerError)
}
// Error output custom error
func (handler Handler) Error(w http.ResponseWriter, err error) {
handler.WriteJSON(w, map[string]interface{}{"error": err.Error()}, http.StatusInternalServerError)
}
// Flush flush response message
func (handler Handler) Flush(w http.ResponseWriter) {
flusher := w.(http.Flusher)
flusher.Flush()
}
// BasicAuth register api with basic auth
func BasicAuth(h httprouter.Handle, requiredUser, requiredPassword string) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
// Get the Basic Authentication credentials
user, password, hasAuth := r.BasicAuth()
if hasAuth && user == requiredUser && password == requiredPassword {
// Delegate request to the given handle
h(w, r, ps)
} else {
// Request Basic Authentication otherwise
w.Header().Set("WWW-Authenticate", "Basic realm=Restricted")
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
}
}
}
var authEnabled = false
func NeedPermission(permission string, h httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
if !authEnabled || CheckPermission(w, r, permission) {
// Delegate request to the given handle
h(w, r, ps)
} else {
//TODO redirect url configurable
http.Redirect(w, r, "/auth/login/?redirect_url="+util.UrlEncode(r.URL.String()), 302)
}
}
}
func EnableAuth(enable bool) {
authEnabled = enable
}
func IsAuthEnable() bool {
return authEnabled
}
func Login(w http.ResponseWriter, r *http.Request, user, role string) {
SetSession(w, r, "user", user)
SetSession(w, r, "role", role)
}
func Logout(w http.ResponseWriter, r *http.Request) {
SetSession(w, r, "user", "")
SetSession(w, r, "role", "")
}
func GetLoginInfo(w http.ResponseWriter, r *http.Request) (user, role string) {
ok1, u := GetSession(w, r, "user")
ok2, v := GetSession(w, r, "role")
if !(ok1 && ok2) {
return "", ""
}
return u.(string), v.(string)
}
func CheckPermission(w http.ResponseWriter, r *http.Request, requiredPermission string) bool {
permissions := []string{}
permissions = append(permissions, requiredPermission)
return CheckPermissions(w, r, permissions)
}
func CheckPermissions(w http.ResponseWriter, r *http.Request, requiredPermissions []string) bool {
user, role := GetLoginInfo(w, r)
log.Trace("check user, ", user, ",", role, ",", requiredPermissions)
if user != "" && role != "" {
//TODO remove hard-coded permission check
if role == ROLE_ADMIN {
return true
}
perms, err := GetPermissionsByRole(role)
if err != nil {
log.Error(err)
return false
}
for _, v := range requiredPermissions {
if v != "" && !perms.Contains(v) {
log.Tracef("user %s with role: %s do not have permission: %s", user, role, v)
return false
}
}
log.Trace("user logged in, ", user, ",", role, ",", requiredPermissions)
return true
}
log.Trace("user not logged in, ", user, ",", role, ",", requiredPermissions)
return false
}