Skip to content

Commit

Permalink
support multiple roles in RBAC middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
umputun committed Aug 17, 2020
1 parent eee8ba4 commit 963a023
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 4 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ func main() {
- `middleware.Auth` - requires authenticated user
- `middleware.Admin` - requires authenticated admin user
- `middleware.Trace` - doesn't require authenticated user, but adds user info to request
- `middleware.RBAC` - requires authenticated user with passed role
- `middleware.RBAC` - requires authenticated user with passed role(s)

Also, there is a special middleware `middleware.UpdateUser` for population and modifying UserInfo in every request. See "Customization" for more details.

Expand Down
11 changes: 9 additions & 2 deletions middleware/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ func (a *Authenticator) basicAdminUser(r *http.Request) bool {

// RBAC middleware allows role based control for routes
// this handler internally wrapped with auth(true) to avoid situation if RBAC defined without prior Auth
func (a *Authenticator) RBAC(role string) func(http.Handler) http.Handler {
func (a *Authenticator) RBAC(roles ...string) func(http.Handler) http.Handler {

f := func(h http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
Expand All @@ -201,7 +201,14 @@ func (a *Authenticator) RBAC(role string) func(http.Handler) http.Handler {
return
}

if !strings.EqualFold(role, user.Role) {
var matched bool
for _, role := range roles {
if strings.EqualFold(role, user.Role) {
matched = true
break
}
}
if !matched {
http.Error(w, "Access denied", http.StatusForbidden)
return
}
Expand Down
2 changes: 1 addition & 1 deletion middleware/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ func TestRBAC(t *testing.T) {
w.WriteHeader(201)
})

mux.Handle("/authForEmployees", a.RBAC("employee")(handler))
mux.Handle("/authForEmployees", a.RBAC("someone", "employee")(handler))
mux.Handle("/authForExternals", a.RBAC("external")(handler))
server := httptest.NewServer(mux)
defer server.Close()
Expand Down

0 comments on commit 963a023

Please sign in to comment.