refactor auth pkg into libraries

This commit is contained in:
dhax 2017-10-31 19:10:09 +01:00
parent 521f081ba0
commit aaf0a0928d
26 changed files with 592 additions and 504 deletions

31
auth/authorize/errors.go Normal file
View file

@ -0,0 +1,31 @@
package authorize
import (
"net/http"
"github.com/go-chi/render"
)
// ErrResponse renderer type for handling all sorts of errors.
type ErrResponse struct {
Err error `json:"-"` // low-level runtime error
HTTPStatusCode int `json:"-"` // http response status code
StatusText string `json:"status"` // user-level status message
AppCode int64 `json:"code,omitempty"` // application-specific error code
ErrorText string `json:"error,omitempty"` // application-level error message, for debugging
}
// Render sets the application-specific error code in AppCode.
func (e *ErrResponse) Render(w http.ResponseWriter, r *http.Request) error {
render.Status(r, e.HTTPStatusCode)
return nil
}
// The list of default error types without specific error message.
var (
ErrForbidden = &ErrResponse{
HTTPStatusCode: http.StatusForbidden,
StatusText: http.StatusText(http.StatusForbidden),
}
)

33
auth/authorize/roles.go Normal file
View file

@ -0,0 +1,33 @@
package authorize
import (
"net/http"
"github.com/go-chi/render"
"github.com/dhax/go-base/auth/jwt"
)
// RequiresRole middleware restricts access to accounts having role parameter in their jwt claims.
func RequiresRole(role string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
hfn := func(w http.ResponseWriter, r *http.Request) {
claims := jwt.ClaimsFromCtx(r.Context())
if !hasRole(role, claims.Roles) {
render.Render(w, r, ErrForbidden)
return
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(hfn)
}
}
func hasRole(role string, roles []string) bool {
for _, r := range roles {
if r == role {
return true
}
}
return false
}