From d29773cc4616afb3fe833cf21bb191451be2d101 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marko=20Tikvi=C4=87?= Date: Fri, 23 Mar 2018 10:37:44 +0100 Subject: [PATCH] ProcessRBAC --- auth_utility.go | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/auth_utility.go b/auth_utility.go index 2348f8b..333f629 100644 --- a/auth_utility.go +++ b/auth_utility.go @@ -140,7 +140,7 @@ func RefreshAuthToken(req *http.Request) (TokenClaims, error) { return CreateAuthToken(claims.Username, Role{claims.Role, claims.RoleID}) } -// RbacCheck returns true if role that made HTTP request is authorized to +// RbacCheck returns true if user that made HTTP request is authorized to // access the resource it is targeting. // It exctracts user's role from the JWT token located in Authorization header of // http.Request and then compares it with the list of supplied roles and returns @@ -172,6 +172,37 @@ func RbacCheck(req *http.Request, authRoles []string) bool { return false } +// ProcessRBAC returns token claims and boolean value based on user's rights to access resource specified in req. +// It exctracts user's role from the JWT token located in Authorization header of +// http.Request and then compares it with the list of supplied roles and returns +// true if there's a match, if "*" is provided or if the authRoles is nil. +// Otherwise it returns false. +func ProcessRBAC(req *http.Request, authRoles []string) (*TokenClaims, bool) { + if authRoles == nil { + return nil, true + } + + // validate token and check expiration date + claims, err := GetTokenClaims(req) + if err != nil { + return claims, false + } + // check if token has expired + if claims.ExpiresAt < (time.Now()).Unix() { + return claims, false + } + + // check if role extracted from token matches + // any of the provided (allowed) ones + for _, r := range authRoles { + if claims.Role == r || r == "*" { + return claims, true + } + } + + return claims, false +} + // GetTokenClaims extracts JWT claims from Authorization header of the request. // Returns token claims or an error. func GetTokenClaims(req *http.Request) (*TokenClaims, error) { -- 1.8.1.2