Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • MKCLOS/coredevelopmentplatform/corepkgv2
Show changes
Commits on Source (14)
Showing with 835 additions and 467 deletions
......@@ -2,6 +2,7 @@ package jwtmdl
import (
"strings"
"sync"
"time"
"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/authmdl/sessionmdl"
......@@ -10,12 +11,48 @@ import (
"github.com/tidwall/gjson"
)
// map to store kid
type Jwtkid struct {
jwtKidMap map[string]string
mu sync.Mutex
}
func (j *Jwtkid) Get(kid string) (string, bool) {
j.mu.Lock()
defer j.mu.Unlock()
key, ok := j.jwtKidMap[kid]
return key, ok
}
func (j *Jwtkid) Set(kid, key string) {
j.mu.Lock()
defer j.mu.Unlock()
j.jwtKidMap[kid] = key
}
// jwtKidStore - store to keep kid and jwtKey
var jwtKidStore = Jwtkid{jwtKidMap: make(map[string]string)}
// GlobalJWTKey - key to decode and encode token
var GlobalJWTKey string
var keyFunc = func(key string) jwt.Keyfunc {
return func(*jwt.Token) (interface{}, error) {
return []byte(key), nil
return func(token *jwt.Token) (interface{}, error) {
if kid, ok := token.Header["kid"].(string); ok {
if jwtKey, ok := jwtKidStore.Get(kid); ok && jwtKey == "DEFAULTKEY" {
return ([]byte(key)), nil
}
if jwtKey, exists := jwtKidStore.Get(kid); exists {
return ([]byte(jwtKey)), nil
}
}
b := ([]byte(key))
return b, nil
}
}
func InitJwtKidStore(kidConfig gjson.Result) {
for _, kid := range kidConfig.Array() {
jwtKidStore.Set(kid.Get("kid").String(), kid.Get("jwtKey").String())
}
}
......@@ -118,7 +155,7 @@ func GenerateTokenWithJWTKey(loginID string, groups []string, clientIP string, m
return generate(claims, JWTKey)
}
//GeneratePricipleObjUsingToken GeneratePricipleObjUsingToken
// GeneratePricipleObjUsingToken GeneratePricipleObjUsingToken
func GeneratePricipleObjUsingToken(tokenReq string, jwtKey string) (jwt.MapClaims, error) {
token, err := extract(tokenReq)
......
......@@ -40,16 +40,18 @@ type RedisCache struct {
addPrefix bool //
connected bool // will be enabled if redis client connects to server
Addr string // redis server address, default "127.0.0.1:6379"
DB int // redis DB on provided server, default 0
Addr string // redis server address, default "127.0.0.1:6379"
DB int // redis DB on provided server, default 0
Username string
Password string //
Expiration time.Duration // this duration will be used for Set() method
Prefix string // this will be used for storing keys for provided project
}
type configRedis struct {
addr string // redis server address, default "127.0.0.1:6379"
db int // redis DB on provided server, default 0
addr string // redis server address, default "127.0.0.1:6379"
db int // redis DB on provided server, default 0
username string
password string //
expiration time.Duration // this duration will be used for Set() method
prefix string // this will be used for storing keys for provided project
......@@ -82,9 +84,14 @@ func RedisWithExpiration(exp time.Duration) redisOption {
cfg.expiration = exp
}
}
func RedisWithUsername(username string) redisOption {
return func(cfg *configRedis) {
cfg.username = username
}
}
// Setup initializes redis cache for application. Must be called only once.
func (rc *RedisCache) Setup(addr, password, prefix string, db int, exp time.Duration) {
func (rc *RedisCache) Setup(addr, username, password, prefix string, db int, exp time.Duration) {
if rc == nil {
rc = new(RedisCache)
......@@ -92,6 +99,7 @@ func (rc *RedisCache) Setup(addr, password, prefix string, db int, exp time.Dura
rc.Addr = addr
rc.Password = password
rc.Username = username
rc.DB = db
rc.Expiration = exp
rc.Prefix = prefix
......@@ -99,6 +107,7 @@ func (rc *RedisCache) Setup(addr, password, prefix string, db int, exp time.Dura
Addr: addr,
Password: password,
DB: db,
Username: username,
}
rc.opt = &opt
......@@ -132,6 +141,7 @@ func SetupRedisCache(opts ...redisOption) (*RedisCache, error) {
rc.Addr = cfg.addr
rc.Password = cfg.password
rc.Username = cfg.username
rc.DB = cfg.db
rc.Expiration = cfg.expiration
rc.Prefix = cfg.prefix
......@@ -140,6 +150,7 @@ func SetupRedisCache(opts ...redisOption) (*RedisCache, error) {
Addr: cfg.addr,
Password: cfg.password,
DB: cfg.db,
Username: cfg.username,
}
rc.cli = redis.NewClient(rc.opt)
......
......@@ -5,7 +5,6 @@ import (
"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/filemdl"
"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/securitymdl"
"github.com/BurntSushi/toml"
pellgotoml "github.com/pelletier/go-toml"
)
// InitConfig initConfig
......@@ -39,7 +38,8 @@ func InitConfigSecure(fpath string, config interface{}, key []byte) (toml.MetaDa
// SaveConfig - SaveConfig
func SaveConfig(fpath string, config interface{}) error {
bytes, tomlMarshalError := pellgotoml.Marshal(config)
// bytes, tomlMarshalError := pellgotoml.Marshal(config)
bytes, tomlMarshalError := toml.Marshal(config)
if errormdl.CheckErr(tomlMarshalError) != nil {
return errormdl.CheckErr(tomlMarshalError)
}
......@@ -52,7 +52,7 @@ func SaveConfig(fpath string, config interface{}) error {
// SaveConfigSecure - SaveConfigSecure
func SaveConfigSecure(fpath string, config interface{}, key []byte) error {
configBytes, tomlMarshalError := pellgotoml.Marshal(config)
configBytes, tomlMarshalError := toml.Marshal(config)
if errormdl.CheckErr(tomlMarshalError) != nil {
return errormdl.CheckErr(tomlMarshalError)
}
......
// Deprecated: As of corepkgv2 tag 1.2.15 onwards no longer maintained,simply use coremongo and in future it will be removed.
package mongodb
import (
......@@ -159,7 +160,7 @@ func InitNewSession(hostDetails MongoHost) error {
return nil
}
//GetMongoConnection method
// GetMongoConnection method
func GetMongoConnection(hostName string) (*mgo.Session, error) {
defer mutex.Unlock()
mutex.Lock()
......
This diff is collapsed.
This diff is collapsed.
syntax = "proto3";
package grpcbuildermdl;
option go_package = "grpcbuildermdl";
option go_package = "/grpcbuildermdl";
message GRPCMessage {
string name =1 ;
......
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.2.0
// - protoc v3.6.1
// source: grpcbuildermdl.proto
package grpcbuildermdl
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.32.0 or later.
const _ = grpc.SupportPackageIsVersion7
// GRPCServiceClient is the client API for GRPCService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type GRPCServiceClient interface {
GRPCHandler(ctx context.Context, in *GRPCRequest, opts ...grpc.CallOption) (*GRPCByteResponse, error)
}
type gRPCServiceClient struct {
cc grpc.ClientConnInterface
}
func NewGRPCServiceClient(cc grpc.ClientConnInterface) GRPCServiceClient {
return &gRPCServiceClient{cc}
}
func (c *gRPCServiceClient) GRPCHandler(ctx context.Context, in *GRPCRequest, opts ...grpc.CallOption) (*GRPCByteResponse, error) {
out := new(GRPCByteResponse)
err := c.cc.Invoke(ctx, "/grpcbuildermdl.GRPCService/GRPCHandler", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// GRPCServiceServer is the server API for GRPCService service.
// All implementations must embed UnimplementedGRPCServiceServer
// for forward compatibility
type GRPCServiceServer interface {
GRPCHandler(context.Context, *GRPCRequest) (*GRPCByteResponse, error)
mustEmbedUnimplementedGRPCServiceServer()
}
// UnimplementedGRPCServiceServer must be embedded to have forward compatible implementations.
type UnimplementedGRPCServiceServer struct {
}
func (UnimplementedGRPCServiceServer) GRPCHandler(context.Context, *GRPCRequest) (*GRPCByteResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GRPCHandler not implemented")
}
func (UnimplementedGRPCServiceServer) mustEmbedUnimplementedGRPCServiceServer() {}
// UnsafeGRPCServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to GRPCServiceServer will
// result in compilation errors.
type UnsafeGRPCServiceServer interface {
mustEmbedUnimplementedGRPCServiceServer()
}
func RegisterGRPCServiceServer(s grpc.ServiceRegistrar, srv GRPCServiceServer) {
s.RegisterService(&GRPCService_ServiceDesc, srv)
}
func _GRPCService_GRPCHandler_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GRPCRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(GRPCServiceServer).GRPCHandler(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpcbuildermdl.GRPCService/GRPCHandler",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(GRPCServiceServer).GRPCHandler(ctx, req.(*GRPCRequest))
}
return interceptor(ctx, in, info, handler)
}
// GRPCService_ServiceDesc is the grpc.ServiceDesc for GRPCService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var GRPCService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "grpcbuildermdl.GRPCService",
HandlerType: (*GRPCServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "GRPCHandler",
Handler: _GRPCService_GRPCHandler_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "grpcbuildermdl.proto",
}
// GRPCCheckClient is the client API for GRPCCheck service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type GRPCCheckClient interface {
GRPCCheck(ctx context.Context, in *GRPCRequest, opts ...grpc.CallOption) (*GRPCResponse, error)
}
type gRPCCheckClient struct {
cc grpc.ClientConnInterface
}
func NewGRPCCheckClient(cc grpc.ClientConnInterface) GRPCCheckClient {
return &gRPCCheckClient{cc}
}
func (c *gRPCCheckClient) GRPCCheck(ctx context.Context, in *GRPCRequest, opts ...grpc.CallOption) (*GRPCResponse, error) {
out := new(GRPCResponse)
err := c.cc.Invoke(ctx, "/grpcbuildermdl.GRPCCheck/GRPCCheck", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// GRPCCheckServer is the server API for GRPCCheck service.
// All implementations must embed UnimplementedGRPCCheckServer
// for forward compatibility
type GRPCCheckServer interface {
GRPCCheck(context.Context, *GRPCRequest) (*GRPCResponse, error)
mustEmbedUnimplementedGRPCCheckServer()
}
// UnimplementedGRPCCheckServer must be embedded to have forward compatible implementations.
type UnimplementedGRPCCheckServer struct {
}
func (UnimplementedGRPCCheckServer) GRPCCheck(context.Context, *GRPCRequest) (*GRPCResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GRPCCheck not implemented")
}
func (UnimplementedGRPCCheckServer) mustEmbedUnimplementedGRPCCheckServer() {}
// UnsafeGRPCCheckServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to GRPCCheckServer will
// result in compilation errors.
type UnsafeGRPCCheckServer interface {
mustEmbedUnimplementedGRPCCheckServer()
}
func RegisterGRPCCheckServer(s grpc.ServiceRegistrar, srv GRPCCheckServer) {
s.RegisterService(&GRPCCheck_ServiceDesc, srv)
}
func _GRPCCheck_GRPCCheck_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GRPCRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(GRPCCheckServer).GRPCCheck(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpcbuildermdl.GRPCCheck/GRPCCheck",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(GRPCCheckServer).GRPCCheck(ctx, req.(*GRPCRequest))
}
return interceptor(ctx, in, info, handler)
}
// GRPCCheck_ServiceDesc is the grpc.ServiceDesc for GRPCCheck service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var GRPCCheck_ServiceDesc = grpc.ServiceDesc{
ServiceName: "grpcbuildermdl.GRPCCheck",
HandlerType: (*GRPCCheckServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "GRPCCheck",
Handler: _GRPCCheck_GRPCCheck_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "grpcbuildermdl.proto",
}
package otpmanagermdl
import (
"errors"
"time"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/cachemdl"
)
// Entry is a data to be stored against a key.
type Entry struct {
Data gjson.Result `json:"data,omitempty"`
Expiration int64 `json:"expiration,omitempty"`
ExpiredAT int64 `json:"expiredAt,omitempty"`
}
const (
// keys for the entry object
KEY_DATA = "data"
KEY_EXPIREDAT = "expiredAt"
KEY_EXPIRATION = "expiration"
)
var store cachemdl.Cacher
var ErrOtpNotFound = errors.New("OTP_NOT_FOUND")
var ErrInvalidDataType = errors.New("INVALID_DATA_Type")
// Init initializes otp manager with provided cache. Subsequent calls will not have any effect after first initialization.
func Init(cache cachemdl.Cacher) {
if store != nil {
return
}
store = cache
}
// NewEntry prepares the object required to store data in session.
//
// The `exp` field interprets time in seconds. Ex. For 5 seconds, set `5`
func NewOTPEntry(val gjson.Result, exp int64) Entry {
duration := time.Duration(exp) * time.Second
deadLine := time.Now().Add(duration).Unix()
return Entry{
Data: val,
Expiration: exp,
ExpiredAT: deadLine,
}
}
// NewRedisEntry prepares the entry for redis cache. This is required because redis accepts a byte array.
func NewRedisEntry(entry Entry) string {
var data string
data, _ = sjson.Set(data, KEY_DATA, entry.Data.Value())
data, _ = sjson.Set(data, KEY_EXPIRATION, entry.Expiration)
data, _ = sjson.Set(data, KEY_EXPIREDAT, entry.ExpiredAT)
return data
}
// Store adds/ updates the entry against the provided key.
func Store(key string, entry Entry) {
duration := time.Duration(entry.Expiration) * time.Second
// if otp manager uses redis cache, the data field (gjson.Result) is saved as is.
// This adds irrelevant fields in redis cache and we get them on retrieve operation.
// The following operation needs to be performed so that the data is marshaled correctly. Redis only accepts []byte{}.
if store.Type() == cachemdl.TypeRedisCache {
store.SetWithExpiration(key, NewRedisEntry(entry), duration)
return
}
store.SetWithExpiration(key, entry, duration)
}
// // Delete removes the otp entry. If the key is not present, error `ErrOtpNotFound` will be thrown. Caller can ignore error if this is acceptable.
func DeleteOTP(key string) error {
_, ok := store.Get(key)
if !ok {
return ErrOtpNotFound
}
store.Delete(key)
return nil
}
func GetOTP(key string) (Entry, bool) {
data, ok := store.Get(key)
if !ok {
return Entry{}, false
}
switch v := data.(type) {
case string: // for result from redis cache
res := gjson.Parse(v)
return Entry{
Data: res.Get(KEY_DATA),
Expiration: res.Get(KEY_EXPIRATION).Int(),
ExpiredAT: res.Get(KEY_EXPIREDAT).Int(),
}, true
case Entry: // for result from fastcache
return v, true
default:
return Entry{}, false
}
}
......@@ -16,7 +16,10 @@ import (
)
// Server server
type Server struct{}
type Server struct {
grpcbuildermdl.UnimplementedGRPCCheckServer
grpcbuildermdl.UnimplementedGRPCServiceServer
}
// GRPCInit init
func GRPCInit(GRPCPort net.Listener) {
......