-
Notifications
You must be signed in to change notification settings - Fork 189
/
route.go
385 lines (338 loc) · 11.2 KB
/
route.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
375
376
377
378
379
380
381
382
383
384
385
package admin
import (
"fmt"
"log"
"net/http"
"net/url"
"path"
"regexp"
"sort"
"strings"
"time"
"github.com/qor/qor"
"github.com/qor/qor/utils"
"github.com/qor/roles"
)
// Middleware is a way to filter a request and response coming into your application
// Register new middleware with `admin.GetRouter().Use(Middleware{
// Name: "middleware name", // use middleware with same name will overwrite old one
// Handler: func(*Context, *Middleware) {
// // do something
// // run next middleware
// middleware.Next(context)
// },
// })`
// It will be called in order, it need to be registered before `admin.MountTo`
type Middleware struct {
Name string
Handler func(*Context, *Middleware)
next *Middleware
}
// Next will call the next middleware
func (middleware Middleware) Next(context *Context) {
if next := middleware.next; next != nil {
next.Handler(context, next)
}
}
func newRouter() *Router {
return &Router{routers: map[string][]*routeHandler{
"GET": {},
"PUT": {},
"POST": {},
"DELETE": {},
}}
}
// Router contains registered routers
type Router struct {
Prefix string
routers map[string][]*routeHandler
middlewares []*Middleware
}
// PrintRoutes print all routes in the terminal
func (r *Router) PrintRoutes() {
fmt.Println("==================== Routes in Admin =======================")
for k, routes := range r.routers {
fmt.Println("\n********************************************")
fmt.Printf(" %+v", k)
fmt.Println("\n********************************************")
for _, route := range routes {
fmt.Printf("%+v\n", route.Path)
}
}
fmt.Println("==================== Middlewares =======================")
for _, m := range r.middlewares {
fmt.Printf("%+v\n", m.Name)
}
fmt.Println("==================== End =======================")
}
// Use reigster a middleware to the router
func (r *Router) Use(middleware *Middleware) {
// compile middleware
for index, m := range r.middlewares {
// replace middleware have same name
if m.Name == middleware.Name {
middleware.next = m.next
r.middlewares[index] = middleware
if index > 1 {
r.middlewares[index-1].next = middleware
}
return
} else if len(r.middlewares) > index+1 {
m.next = r.middlewares[index+1]
} else if len(r.middlewares) == index+1 {
m.next = middleware
}
}
r.middlewares = append(r.middlewares, middleware)
}
// GetMiddleware get registered middleware
func (r *Router) GetMiddleware(name string) *Middleware {
for _, middleware := range r.middlewares {
if middleware.Name == name {
return middleware
}
}
return nil
}
// Get register a GET request handle with the given path
func (r *Router) Get(path string, handle requestHandler, config ...*RouteConfig) {
r.routers["GET"] = append(r.routers["GET"], newRouteHandler(path, handle, config...))
r.sortRoutes(r.routers["GET"])
}
// Post register a POST request handle with the given path
func (r *Router) Post(path string, handle requestHandler, config ...*RouteConfig) {
r.routers["POST"] = append(r.routers["POST"], newRouteHandler(path, handle, config...))
r.sortRoutes(r.routers["POST"])
}
// Put register a PUT request handle with the given path
func (r *Router) Put(path string, handle requestHandler, config ...*RouteConfig) {
r.routers["PUT"] = append(r.routers["PUT"], newRouteHandler(path, handle, config...))
r.sortRoutes(r.routers["PUT"])
}
// Delete register a DELETE request handle with the given path
func (r *Router) Delete(path string, handle requestHandler, config ...*RouteConfig) {
r.routers["DELETE"] = append(r.routers["DELETE"], newRouteHandler(path, handle, config...))
r.sortRoutes(r.routers["DELETE"])
}
var wildcardRouter = regexp.MustCompile("/:\\w+")
func (r *Router) sortRoutes(routes []*routeHandler) {
sort.SliceStable(routes, func(i, j int) bool {
iMatchedWildCards := wildcardRouter.FindAllStringSubmatch(routes[i].Path, -1)
jMatchedWildCards := wildcardRouter.FindAllStringSubmatch(routes[j].Path, -1)
// i regexp (2), j static (0) => less is true
// i regexp (1), j regexp (2) => less is false
if len(iMatchedWildCards) != len(jMatchedWildCards) {
return len(iMatchedWildCards) < len(jMatchedWildCards)
}
return len(routes[i].Path) > len(routes[j].Path)
})
}
// MountTo mount the service into mux (HTTP request multiplexer) with given path
func (admin *Admin) MountTo(mountTo string, mux *http.ServeMux) {
prefix := "/" + strings.Trim(mountTo, "/")
serveMux := admin.NewServeMux(prefix)
mux.Handle(prefix, serveMux) // /:prefix
mux.Handle(prefix+"/", serveMux) // /:prefix/:xxx
}
// NewServeMux generate http.Handler for admin
func (admin *Admin) NewServeMux(prefix string) http.Handler {
// Register default routes & middlewares
router := admin.router
router.Prefix = prefix
adminController := &Controller{Admin: admin}
router.Get("", adminController.Dashboard)
router.Get("/!search", adminController.SearchCenter)
browserUserAgentRegexp := regexp.MustCompile("Mozilla|Gecko|WebKit|MSIE|Opera")
router.Use(&Middleware{
Name: "csrf_check",
Handler: func(context *Context, middleware *Middleware) {
request := context.Request
if request.Method != "GET" {
if browserUserAgentRegexp.MatchString(request.UserAgent()) {
if referrer := request.Referer(); referrer != "" {
if r, err := url.Parse(referrer); err == nil {
if r.Host == request.Host {
middleware.Next(context)
return
}
}
}
context.Writer.Write([]byte("Could not authorize you because 'CSRF detected'"))
return
}
}
middleware.Next(context)
},
})
router.Use(&Middleware{
Name: "qor_handler",
Handler: func(context *Context, middleware *Middleware) {
context.Writer.Header().Set("Cache-control", "no-store")
context.Writer.Header().Set("Pragma", "no-cache")
if context.RouteHandler != nil {
context.RouteHandler.Handle(context)
return
}
http.NotFound(context.Writer, context.Request)
},
})
return &serveMux{admin: admin}
}
type serveMux struct {
admin *Admin
}
// ServeHTTP dispatches the handler registered in the matched route
func (serveMux *serveMux) ServeHTTP(w http.ResponseWriter, req *http.Request) {
var (
admin = serveMux.admin
RelativePath = "/" + strings.Trim(strings.TrimPrefix(req.URL.Path, admin.router.Prefix), "/")
context = admin.NewContext(w, req)
)
// Parse Request Form
req.ParseMultipartForm(2 * 1024 * 1024)
defer func() {
if req.MultipartForm != nil {
req.MultipartForm.RemoveAll()
}
}()
// Set Request Method
if method := req.Form.Get("_method"); method != "" {
req.Method = strings.ToUpper(method)
}
if regexp.MustCompile("^/assets/.*$").MatchString(RelativePath) && strings.ToUpper(req.Method) == "GET" {
(&Controller{Admin: admin}).Asset(context)
return
}
defer func() func() {
begin := time.Now()
return func() {
log.Printf("Finish [%s] %s Took %.2fms\n", req.Method, req.RequestURI, time.Now().Sub(begin).Seconds()*1000)
}
}()()
// Set Current User
var currentUser qor.CurrentUser
var permissionMode roles.PermissionMode
if admin.Auth != nil {
if currentUser = admin.Auth.GetCurrentUser(context); currentUser == nil {
http.Redirect(w, req, admin.Auth.LoginURL(context), http.StatusSeeOther)
return
}
context.CurrentUser = currentUser
context.SetDB(context.GetDB().Set("qor:current_user", context.CurrentUser))
}
context.Roles = roles.MatchedRoles(req, currentUser)
switch req.Method {
case "GET":
permissionMode = roles.Read
case "PUT":
permissionMode = roles.Update
case "POST":
permissionMode = roles.Create
case "DELETE":
permissionMode = roles.Delete
}
handlers := admin.router.routers[strings.ToUpper(req.Method)]
for _, handler := range handlers {
if params, _, ok := utils.ParamsMatch(handler.Path, RelativePath); ok && handler.HasPermission(permissionMode, context.Context) {
if len(params) > 0 {
req.URL.RawQuery = url.Values(params).Encode() + "&" + req.URL.RawQuery
}
context.RouteHandler = handler
context.setResource(handler.Config.Resource)
if context.Resource == nil {
if matches := regexp.MustCompile(path.Join(admin.router.Prefix, `([^/]+)`)).FindStringSubmatch(req.URL.Path); len(matches) > 1 {
context.setResource(admin.GetResource(matches[1]))
}
}
break
}
}
// Call first middleware
for _, middleware := range admin.router.middlewares {
middleware.Handler(context, middleware)
break
}
}
// RegisterResourceRouters register resource to router
func (admin *Admin) RegisterResourceRouters(res *Resource, actions ...string) {
var (
primaryKeyParams = res.ParamIDName()
adminController = &Controller{Admin: admin}
)
for _, action := range actions {
switch strings.ToLower(action) {
case "create":
if !res.Config.Singleton {
// New
res.RegisterRoute("GET", "/new", adminController.New, &RouteConfig{PermissionMode: roles.Create})
}
// Create
res.RegisterRoute("POST", "/", adminController.Create, &RouteConfig{PermissionMode: roles.Create})
case "update":
if res.Config.Singleton {
// Edit
res.RegisterRoute("GET", "/edit", adminController.Edit, &RouteConfig{PermissionMode: roles.Update})
// Update
res.RegisterRoute("PUT", "/", adminController.Update, &RouteConfig{PermissionMode: roles.Update})
} else {
// Edit
res.RegisterRoute("GET", path.Join(primaryKeyParams, "edit"), adminController.Edit, &RouteConfig{PermissionMode: roles.Update})
// Update
res.RegisterRoute("POST", primaryKeyParams, adminController.Update, &RouteConfig{PermissionMode: roles.Update})
res.RegisterRoute("PUT", primaryKeyParams, adminController.Update, &RouteConfig{PermissionMode: roles.Update})
}
case "read":
if res.Config.Singleton {
// Index
res.RegisterRoute("GET", "/", adminController.Show, &RouteConfig{PermissionMode: roles.Read})
} else {
// Index
res.RegisterRoute("GET", "/", adminController.Index, &RouteConfig{PermissionMode: roles.Read})
// Show
res.RegisterRoute("GET", primaryKeyParams, adminController.Show, &RouteConfig{PermissionMode: roles.Read})
}
case "delete":
if !res.Config.Singleton {
// Delete
res.RegisterRoute("DELETE", primaryKeyParams, adminController.Delete, &RouteConfig{PermissionMode: roles.Delete})
}
}
}
}
// RegisterRoute register route
func (res *Resource) RegisterRoute(method string, relativePath string, handler requestHandler, config *RouteConfig) {
if config == nil {
config = &RouteConfig{}
}
config.Resource = res
var (
prefix string
param = res.ToParam()
router = res.GetAdmin().router
)
if prefix = func(r *Resource) string {
currentParam := param
for r.ParentResource != nil {
parentPath := r.ParentResource.ToParam()
// don't register same resource as nested routes
if parentPath == param {
return ""
}
currentParam = path.Join(parentPath, r.ParentResource.ParamIDName(), currentParam)
r = r.ParentResource
}
return "/" + strings.Trim(currentParam, "/")
}(res); prefix == "" {
return
}
switch strings.ToUpper(method) {
case "GET":
router.Get(path.Join(prefix, relativePath), handler, config)
case "POST":
router.Post(path.Join(prefix, relativePath), handler, config)
case "PUT":
router.Put(path.Join(prefix, relativePath), handler, config)
case "DELETE":
router.Delete(path.Join(prefix, relativePath), handler, config)
}
}