Commit d388c72c authored by Akshay Bharambe's avatar Akshay Bharambe
Browse files

Update: JWT tests and logs

parent 60e4f0ff
Branches
Tags
2 merge requests!210Staging mepdeployment05072020,!201Update: JWT tests and logs
Showing with 93 additions and 53 deletions
......@@ -5,9 +5,7 @@ import (
"time"
"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/authmdl/sessionmdl"
"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/errormdl"
"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/loggermdl"
jwt "github.com/dgrijalva/jwt-go"
"github.com/tidwall/gjson"
)
......@@ -49,19 +47,19 @@ func extract(tokenReq string) (string, error) {
// decode accepts a parsed token and error from parse operation.
func decode(token *jwt.Token, err error) (jwt.MapClaims, error) {
if err != nil {
loggermdl.LogError("Error while parsing JWT Token: ", err)
// loggermdl.LogError("Error while parsing JWT Token: ", err)
return nil, err
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
loggermdl.LogError("Error while parsing claims to MapClaims")
// loggermdl.LogError("Error while parsing claims to MapClaims")
return nil, errormdl.Wrap("Error while getting claims")
}
// validate user session from session id present in token
if err := sessionmdl.ValidateSessionFromToken(claims); err != nil {
loggermdl.LogError("session validation failed with err:", err)
// loggermdl.LogError("session validation failed with err:", err)
return nil, sessionmdl.ErrSessionValidationFailed
}
......
......@@ -4,20 +4,30 @@ import (
"fmt"
"net/http"
"testing"
"time"
"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/authmdl/sessionmdl"
"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/cachemdl"
"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/utiliymdl/guidmdl"
jwt "github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/tidwall/gjson"
)
const (
TestKey = "vJUufKHyu2xiMYmDj1TmojHR11ciUaq3"
)
func checkToken(token string) error {
claims, err := decode(jwt.Parse(token, keyFunc(TestKey)))
if err != nil {
return err
}
return sessionmdl.ValidateSessionFromToken(claims)
}
func server() {
g := gin.Default()
g.GET("/status", func(c *gin.Context) {
......@@ -127,11 +137,55 @@ func TestGenerateTokenWithOptions(t *testing.T) {
return
}
if got != "" {
t.Error(got)
err = checkToken(got)
if (err != nil) != tt.wantErr {
t.Errorf("GenerateTokenWithOptions() error = %v, wantErr %v", err, tt.wantErr)
return
}
})
}
}
func TestGenerateTokenWithJWTKey(t *testing.T) {
type args struct {
loginID string
groups []string
clientIP string
metadata gjson.Result
expirationTime time.Duration
JWTKey string
}
tests := []struct {
name string
args args
// want string
wantErr bool
}{
{
name: "Test genrate token",
args: args{
JWTKey: TestKey,
expirationTime: time.Minute * 5,
groups: []string{"admin"},
loginID: "tom@company.org",
metadata: gjson.Parse(`{"name":"tom"}`),
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := GenerateTokenWithJWTKey(tt.args.loginID, tt.args.groups, tt.args.clientIP, tt.args.metadata, tt.args.expirationTime, tt.args.JWTKey)
if (err != nil) != tt.wantErr {
t.Errorf("GenerateTokenWithJWTKey() error = %v, wantErr %v", err, tt.wantErr)
return
}
fmt.Println(got)
err = checkToken(got)
if (err != nil) != tt.wantErr {
t.Errorf("GenerateTokenWithJWTKey() error = %v, wantErr %v", err, tt.wantErr)
return
}
})
}
}
......@@ -27,6 +27,7 @@ type Session struct {
var store cachemdl.Cacher
var (
ErrUserNotFound = errors.New("user not found")
ErrSessionNotFound = errors.New("session not found")
ErrInvalidSessionInstance = errors.New("got invalid session instance id")
ErrSessionValidationFailed = errors.New("session validation failed")
......@@ -83,13 +84,13 @@ func Get(userId string) ([]Session, error) {
i, ok = store.Get(userId)
if !ok {
return s, ErrSessionNotFound
return s, ErrUserNotFound
}
s, ok = i.([]Session)
if !ok {
return s, errors.New("failed to retrieve previous sessions")
}
s, _ = i.([]Session)
// if !ok {
// return s, errors.New("failed to retrieve previous sessions")
// }
return s, nil
}
......@@ -129,13 +130,13 @@ func ValidateSessionFromToken(claims map[string]interface{}) error {
// check for sessionId field, if not present then it is ignored at the time of token generation.
// This means user doesn't want to validate session.
i, ok := claims["sessionId"]
if !ok {
if !ok || i == nil {
return nil
}
sessionId, ok := i.(string)
if !ok {
return errors.New("\"sessionId\" field is not string")
sessionId, _ := i.(string)
if len(sessionId) == 0 {
return errors.New("\"sessionId\" field is empty")
}
i, ok = claims["userId"]
......@@ -143,9 +144,9 @@ func ValidateSessionFromToken(claims map[string]interface{}) error {
return errors.New("\"userId\" field not found in token")
}
userId, ok := i.(string)
if !ok {
return errors.New("\"userId\" field is not string")
userId, _ := i.(string)
if len(userId) == 0 {
return errors.New("\"userId\" field is empty")
}
sessions, err := Get(userId)
......@@ -153,38 +154,25 @@ func ValidateSessionFromToken(claims map[string]interface{}) error {
return err
}
var found bool
for i := range sessions {
if sessions[i].SessionId == sessionId {
found = true
break
return nil
}
}
if !found {
return ErrSessionNotFound
}
return nil
return ErrSessionNotFound
}
// CheckForSessionAvailability checks if the user has active session for provided `sessionFor`. Returns true if session is available.
func CheckForSessionAvailability(userId, sessionFor string) bool {
sessions, err := Get(userId)
if err != nil {
return false
}
var found bool
sessions, _ := Get(userId)
for i := range sessions {
if sessions[i].SessionFor == sessionFor {
found = true
break
return true
}
}
return found
return false
}
......@@ -7,7 +7,7 @@ import (
)
func init() {
InitSessionManagerCache(cachemdl.TypeFastCache)
InitUserSessionCache(cachemdl.TypeFastCache)
}
func TestSet(t *testing.T) {
......
......@@ -315,7 +315,7 @@ func extractPricipalObject(c *routing.Context) (servicebuildermdl.Principal, err
claim, decodeError := jwtmdl.DecodeToken(&c.Request)
if errormdl.CheckErr(decodeError) != nil {
loggermdl.LogError(decodeError)
// loggermdl.LogError(decodeError)
return principal, errormdl.CheckErr(decodeError)
}
......@@ -324,11 +324,11 @@ func extractPricipalObject(c *routing.Context) (servicebuildermdl.Principal, err
loggermdl.LogError(grperr)
return principal, errormdl.CheckErr(grperr)
}
userID, ok := claim["userId"].(string)
if !ok {
loggermdl.LogError("Unable to parse UserID from JWT Token")
return principal, errormdl.Wrap("Unable to parse UserID from JWT Token")
}
userID, _ := claim["userId"].(string)
// if !ok {
// loggermdl.LogError("Unable to parse UserID from JWT Token")
// return principal, errormdl.Wrap("Unable to parse UserID from JWT Token")
// }
if len(userID) < 2 {
loggermdl.LogError("UserID length is less than 2")
......
......@@ -287,7 +287,7 @@ func extractPricipalObject(c *gin.Context) (servicebuildermdl.Principal, error)
}
claim, decodeError := jwtmdl.DecodeToken(c.Request)
if errormdl.CheckErr(decodeError) != nil {
loggermdl.LogError(decodeError)
// loggermdl.LogError(decodeError)
return principal, errormdl.CheckErr(decodeError)
}
......@@ -296,11 +296,11 @@ func extractPricipalObject(c *gin.Context) (servicebuildermdl.Principal, error)
loggermdl.LogError(grperr)
return principal, errormdl.CheckErr(grperr)
}
userID, ok := claim["userId"].(string)
if !ok {
loggermdl.LogError("Unable to parse UserID from JWT Token")
return principal, errormdl.Wrap("Unable to parse UserID from JWT Token")
}
userID, _ := claim["userId"].(string)
// if !ok {
// loggermdl.LogError("Unable to parse UserID from JWT Token")
// return principal, errormdl.Wrap("Unable to parse UserID from JWT Token")
// }
if len(userID) < 2 {
loggermdl.LogError("UserID length is less than 2")
......
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment