-
Notifications
You must be signed in to change notification settings - Fork 8
/
authorizer.go
76 lines (66 loc) · 1.77 KB
/
authorizer.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
package filter
import (
"net/http"
"net/url"
"github.com/cuigh/auxo/data"
"github.com/cuigh/auxo/net/web"
)
type Authorizer struct {
Checker func(user web.User, handler web.HandlerInfo) bool
LoginURL string
UnauthorizedMsg string
ForbiddenMsg string
}
func NewAuthorizer(checker func(user web.User, handler web.HandlerInfo) bool) *Authorizer {
return &Authorizer{
Checker: checker,
}
}
// Apply implements `web.Filter` interface.
func (a *Authorizer) Apply(next web.HandlerFunc) web.HandlerFunc {
if a.Checker == nil {
panic("Authorizer requires an checker function")
}
if a.LoginURL == "" {
a.LoginURL = "/login"
}
if a.UnauthorizedMsg == "" {
a.UnauthorizedMsg = "You are not logged in"
}
if a.ForbiddenMsg == "" {
a.ForbiddenMsg = "You do not have access to this URL"
}
return func(ctx web.Context) error {
auth := ctx.Handler().Authorize()
if auth == web.AuthAnonymous {
return next(ctx)
}
user := ctx.User()
if user == nil || user.Anonymous() {
ct := ctx.ContentType()
if ct == web.MIMEApplicationJSON {
//return web.NewError(http.StatusUnauthorized)
return ctx.Status(http.StatusUnauthorized).JSON(data.Map{
"url": ctx.Route(),
"code": http.StatusUnauthorized,
"message": a.UnauthorizedMsg,
"login_url": a.LoginURL,
})
} else if ctx.IsAJAX() {
return ctx.Status(http.StatusUnauthorized).HTML(a.UnauthorizedMsg)
}
u, err := url.Parse(a.LoginURL)
if err != nil {
return err
}
q := u.Query()
q.Set("from", ctx.Request().RequestURI)
u.RawQuery = q.Encode()
return ctx.Redirect(u.String())
}
if auth != web.AuthAuthenticated && !a.Checker(user, ctx.Handler()) {
return web.NewError(http.StatusForbidden, a.ForbiddenMsg)
}
return next(ctx)
}
}