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

Add: New JWT options API

parent 55d056f9
Branches kunal_SQLServer
Tags
2 merge requests!210Staging mepdeployment05072020,!200Add: Session control
Showing with 174 additions and 20 deletions
......@@ -6,7 +6,6 @@ import (
"time"
"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/authmdl/sessionmdl"
"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/utiliymdl/guidmdl"
"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/errormdl"
"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/loggermdl"
......@@ -66,6 +65,42 @@ type jwtCustomClaim struct {
jwt.StandardClaims
}
func generate(claims jwtCustomClaim, key string) (string, error) {
return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(key))
}
func GenerateTokenWithOptions(args ...Option) (string, error) {
options := new(Options)
options.Key = GlobalJWTKey
for i := range args {
args[i](options)
}
claims := jwtCustomClaim{
ClientIP: options.ClientIP,
Groups: options.Groups,
Metadata: options.Metadata,
SessionId: options.Session.SessionId,
UserID: options.UserID,
StandardClaims: jwt.StandardClaims{
ExpiresAt: options.ExpiresAt,
},
}
t, err := generate(claims, options.Key)
if err != nil {
return "", err
}
if len(options.Session.SessionId) > 0 {
sessionmdl.Set(options.UserID, options.Session)
}
return t, nil
}
// GenerateToken generates JWT token from Login object
func GenerateToken(loginID string, groups []string, clientIP string, metadata gjson.Result, expirationTime time.Duration) (string, error) {
// claims := jwtCustomClaim{
......@@ -100,26 +135,16 @@ func GenerateTokenWithJWTKey(loginID string, groups []string, clientIP string, m
},
}
var sessionId string
if sessionmdl.ValidateSession {
sessionId = guidmdl.GetGUID()
claims.SessionId = sessionId
}
// Create token with claims
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Generate encoded token and send it as response.
t, err := token.SignedString([]byte(JWTKey))
if errormdl.CheckErr(err) != nil {
loggermdl.LogError(err)
return t, errormdl.CheckErr(err)
}
if sessionmdl.ValidateSession {
sessionmdl.Set(loginID, sessionmdl.Session{SessionFor: metadata.Get(sessionmdl.SessionForKey).String(), SessionId: sessionId})
}
// // Create token with claims
// token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// // Generate encoded token and send it as response.
// t, err := token.SignedString([]byte(JWTKey))
// if errormdl.CheckErr(err) != nil {
// loggermdl.LogError(err)
// return t, errormdl.CheckErr(err)
// }
return t, nil
return generate(claims, JWTKey)
}
//GeneratePricipleObjUsingToken GeneratePricipleObjUsingToken
......
......@@ -5,10 +5,19 @@ import (
"net/http"
"testing"
"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/authmdl/sessionmdl"
"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/cachemdl"
"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/utiliymdl/guidmdl"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
const (
TestKey = "vJUufKHyu2xiMYmDj1TmojHR11ciUaq3"
)
func server() {
g := gin.Default()
g.GET("/status", func(c *gin.Context) {
......@@ -71,3 +80,54 @@ func TestDecodeTokenvalid(t *testing.T) {
// assert.Error(t, derror, "error occured")
// errormdl.IsTestingNegetiveCaseOnCheckBool1 = false
// }
func TestGenerateTokenWithOptions(t *testing.T) {
sessionmdl.InitSessionManagerCache(cachemdl.TypeFastCache)
type args struct {
args []Option
}
tests := []struct {
name string
args args
want string
wantErr bool
}{
{
name: "Token without session",
args: args{
args: []Option{
WithUserID("tom@company.org"),
WithExpiration(0),
WithKey(TestKey),
WithMetaData(`{"name":"tom"}`),
},
},
wantErr: false,
},
{
name: "Token with session",
args: args{
args: []Option{
WithUserID("tom@company.org"),
WithExpiration(0),
WithKey(TestKey),
WithMetaData(`{"name":"tom"}`),
WithSession(guidmdl.GetGUID(), "me"),
},
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := GenerateTokenWithOptions(tt.args.args...)
if (err != nil) != tt.wantErr {
t.Errorf("GenerateTokenWithOptions() error = %v, wantErr %v", err, tt.wantErr)
return
}
fmt.Println(got)
})
}
}
package jwtmdl
import (
"time"
"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/authmdl/sessionmdl"
)
type Options struct {
Key string
UserID string
ClientIP string
Metadata string
Groups []string
ExpiresAt int64
Session sessionmdl.Session
}
type Option func(*Options)
func WithKey(k string) Option {
return func(args *Options) {
args.Key = k
}
}
func WithUserID(uid string) Option {
return func(args *Options) {
args.UserID = uid
}
}
func WithSession(sid, sessionFor string) Option {
return func(args *Options) {
args.Session = sessionmdl.Session{
SessionId: sid,
SessionFor: sessionFor,
}
}
}
func WithClientIP(ip string) Option {
return func(args *Options) {
args.ClientIP = ip
}
}
func WithMetaData(data string) Option {
return func(args *Options) {
args.Metadata = data
}
}
func WithGroups(gs []string) Option {
return func(args *Options) {
args.Groups = gs
}
}
func WithExpiration(e time.Duration) Option {
return func(args *Options) {
if e == 0 {
args.ExpiresAt = 0
return
}
args.ExpiresAt = time.Now().Add(e).Unix()
}
}
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