github.com/dhax/go-base@v0.0.0-20231004214136-8be7e5c1972b/auth/authorize/roles.go (about) 1 package authorize 2 3 import ( 4 "net/http" 5 6 "github.com/go-chi/render" 7 8 "github.com/dhax/go-base/auth/jwt" 9 ) 10 11 // RequiresRole middleware restricts access to accounts having role parameter in their jwt claims. 12 func RequiresRole(role string) func(next http.Handler) http.Handler { 13 return func(next http.Handler) http.Handler { 14 hfn := func(w http.ResponseWriter, r *http.Request) { 15 claims := jwt.ClaimsFromCtx(r.Context()) 16 if !hasRole(role, claims.Roles) { 17 render.Render(w, r, ErrForbidden) 18 return 19 } 20 next.ServeHTTP(w, r) 21 } 22 return http.HandlerFunc(hfn) 23 } 24 } 25 26 func hasRole(role string, roles []string) bool { 27 for _, r := range roles { 28 if r == role { 29 return true 30 } 31 } 32 return false 33 }