Mercurial > gemma
changeset 1340:97430d442909
Added comments to auth middleware.
author | Sascha L. Teichmann <sascha.teichmann@intevation.de> |
---|---|
date | Mon, 26 Nov 2018 10:32:37 +0100 |
parents | 1d1fc92fc3ea |
children | a0892b578553 |
files | pkg/auth/middleware.go |
diffstat | 1 files changed, 17 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- a/pkg/auth/middleware.go Mon Nov 26 10:10:10 2018 +0100 +++ b/pkg/auth/middleware.go Mon Nov 26 10:32:37 2018 +0100 @@ -26,16 +26,26 @@ tokenKey ) +// GetSession returns the session stored in the context of the request. func GetSession(req *http.Request) (*Session, bool) { session, ok := req.Context().Value(sessionKey).(*Session) return session, ok } +// GetToken returns the session token associated with given request. func GetToken(req *http.Request) (string, bool) { token, ok := req.Context().Value(tokenKey).(string) return token, ok } +// SessionMiddleware constructs a middleware to enforce the existence +// of the header X-Gemma-Auth in the incoming request and checks +// if a session is bound to it. +// Ihe the checks fail the constructed handler issues an http.StatusUnauthorized +// back to the invokation stacks and prevents the execution of the +// nested http.Handler next. +// Inside the http.Handler next calls to GetSession and GetToken are valid +// to fetch the respective information. func SessionMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { @@ -63,6 +73,10 @@ }) } +// SessionChecker constructs a middleware to check invariants about a session +// before calling the nested http.Handler next. +// This is useful when creating specialized middleware e.g. to enforce +// a role system. func SessionChecker(next http.Handler, check func(*Session) bool) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { if claims, ok := GetSession(req); !ok || !check(claims) { @@ -73,12 +87,15 @@ }) } +// HasRole is a checker function fitting into SessionChecker to check +// if the user is logged in with at least one of list of given roles. func HasRole(roles ...string) func(*Session) bool { return func(session *Session) bool { return session.Roles.HasAny(roles...) } } +// EnsureRole is a macro function to stitch SessionChecker and HasRole together. func EnsureRole(roles ...string) func(http.Handler) http.Handler { return func(handler http.Handler) http.Handler { return SessionMiddleware(SessionChecker(handler, HasRole(roles...)))