forked from qor/auth
-
Notifications
You must be signed in to change notification settings - Fork 1
/
authority.go
91 lines (74 loc) · 2.25 KB
/
authority.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
package authority
import (
"html/template"
"net/http"
"github.com/fahmibaswara/auth"
"github.com/qor/middlewares"
"github.com/qor/roles"
"github.com/qor/session"
)
var (
// AccessDeniedFlashMessage access denied message
AccessDeniedFlashMessage = template.HTML("Access Denied!")
)
// Authority authority struct
type Authority struct {
*Config
}
// AuthInterface auth interface
type AuthInterface interface {
auth.SessionStorerInterface
GetCurrentUser(req *http.Request) interface{}
}
// Config authority config
type Config struct {
Auth AuthInterface
Role *roles.Role
AccessDeniedHandler func(w http.ResponseWriter, req *http.Request)
}
// New initialize Authority
func New(config *Config) *Authority {
if config == nil {
config = &Config{}
}
if config.Auth == nil {
panic("Auth should not be nil for Authority")
}
if config.Role == nil {
config.Role = roles.Global
}
if config.AccessDeniedHandler == nil {
config.AccessDeniedHandler = NewAccessDeniedHandler(config.Auth, "/")
}
authority := &Authority{Config: config}
middlewares.Use(middlewares.Middleware{
Name: "authority",
InsertAfter: []string{"session"},
Handler: func(handler http.Handler) http.Handler {
return authority.Middleware(handler)
},
})
return authority
}
// Authorize authorize specfied roles or authenticated user to access wrapped handler
func (authority *Authority) Authorize(roles ...string) func(http.Handler) http.Handler {
return func(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
var currentUser interface{}
// Get current user from request
currentUser = authority.Auth.GetCurrentUser(req)
if (len(roles) == 0 && currentUser != nil) || authority.Role.HasRole(req, currentUser, roles...) {
handler.ServeHTTP(w, req)
return
}
authority.AccessDeniedHandler(w, req)
})
}
}
// NewAccessDeniedHandler new access denied handler
func NewAccessDeniedHandler(Auth AuthInterface, redirectPath string) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
Auth.Flash(w, req, session.Message{Message: AccessDeniedFlashMessage})
http.Redirect(w, req, redirectPath, http.StatusSeeOther)
}
}