Merge pull request #4 from integration-system/update-auth

update auth
This commit is contained in:
Yan authored and GitHub committed 2019-11-15 13:32:33 +03:00
commit bad913e339
16 files changed
+317 -155

No files matched your search

+1 -1
View File
@@ -1 +1 @@
1.0.0
1.1.0
+4
View File
@@ -0,0 +1,4 @@
## 1.1.0
* add token verification via JWT
* add accounting for applications
* add optional cache for application tokens
+6 -6
View File
@@ -2,14 +2,14 @@ package accounting
import (
log "github.com/integration-system/isp-log"
"github.com/integration-system/isp-log/stdcodes"
"isp-gate-service/accounting/state"
"isp-gate-service/conf"
"isp-gate-service/log_code"
"isp-gate-service/service/matcher"
"sync"
)
var accountingByApplicationId = make(map[int64]*accounting)
var accountingByApplicationId = make(map[int32]*accounting)
type accounting struct {
mx sync.Mutex
@@ -18,12 +18,12 @@ type accounting struct {
}
func ReceiveConfiguration(conf conf.Accounting) {
newAccountingByApplicationId := make(map[int64]*accounting)
newAccountingByApplicationId := make(map[int32]*accounting)
if conf.Enable {
for _, s := range conf.Setting {
limitState, patternArray, err := state.InitLimitState(s.Limits)
if err != nil {
log.Fatal(log_code.FatalConfigApproveSetting, err)
log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err)
}
newAccountingByApplicationId[s.ApplicationId] = &accounting{
@@ -36,11 +36,11 @@ func ReceiveConfiguration(conf conf.Accounting) {
accountingByApplicationId = newAccountingByApplicationId
}
func GetAccounting(appId int64) *accounting {
func GetAccounting(appId int32) *accounting {
return accountingByApplicationId[appId]
}
func (app *accounting) TakeAccount(method string) bool {
func (app *accounting) Check(method string) bool {
patternArray := app.matcher.Match(method)
stateStorage := make([]state.LimitState, len(patternArray))
for i, pattern := range patternArray {
+5 -5
View File
@@ -24,7 +24,7 @@ var (
}
reqExample = []struct {
appId int64
appId int32
path []string
}{
0: {appId: 1, path: []string{
@@ -55,7 +55,7 @@ func TestApprove(t *testing.T) {
expected := true
req := reqExample[0]
for _, path := range req.path {
a.Equal(expected, GetAccounting(req.appId).TakeAccount(path))
a.Equal(expected, GetAccounting(req.appId).Check(path))
expected = !expected
time.Sleep(150 * time.Millisecond)
}
@@ -63,19 +63,19 @@ func TestApprove(t *testing.T) {
//expected == true
req = reqExample[1]
for _, path := range req.path {
a.Equal(expected, GetAccounting(req.appId).TakeAccount(path))
a.Equal(expected, GetAccounting(req.appId).Check(path))
expected = !expected
}
req = reqExample[2]
expectedArray := []bool{true, true, true, true, true, false}
for key, path := range req.path {
a.Equal(expectedArray[key], GetAccounting(req.appId).TakeAccount(path))
a.Equal(expectedArray[key], GetAccounting(req.appId).Check(path))
}
//expected == true
req = reqExample[3]
for _, path := range req.path {
a.Equal(expected, GetAccounting(req.appId).TakeAccount(path))
a.Equal(expected, GetAccounting(req.appId).Check(path))
}
}
+58 -35
View File
@@ -1,75 +1,98 @@
package authenticate
import (
"github.com/integration-system/isp-lib/config"
"github.com/integration-system/isp-lib/utils"
log "github.com/integration-system/isp-log"
"github.com/integration-system/isp-log/stdcodes"
"github.com/pkg/errors"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
"isp-gate-service/conf"
"isp-gate-service/log_code"
"isp-gate-service/routing"
"isp-gate-service/service/veritification"
"strconv"
"strings"
"time"
)
var (
verifiableKeyHeaderKeyMap = map[string]string{
systemIdentity: utils.SystemIdHeader,
domainIdentity: utils.DomainIdHeader,
serviceIdentity: utils.ServiceIdHeader,
applicationIdentity: utils.ApplicationIdHeader,
var notExpectedHeaders = []string{
utils.SystemIdHeader, utils.DomainIdHeader, utils.ServiceIdHeader, utils.ApplicationIdHeader,
}
var auth = authenticate{}
type authenticate struct {
verify veritification.Verify
}
func ReceiveConfiguration(conf conf.Cache) {
if conf.EnableCash {
if timeout, err := time.ParseDuration(conf.EvictTimeout); err != nil {
log.Fatalf(stdcodes.ModuleInvalidRemoteConfig, "invalid timeout '%s'", timeout)
} else {
auth.verify = veritification.NewCacheableVerify(timeout)
}
} else {
auth.verify = veritification.NewRuntimeVerify()
}
)
}
func Do(ctx *fasthttp.RequestCtx) (int64, error) {
func Do(ctx *fasthttp.RequestCtx) (int32, error) {
path := ctx.Path()
uri := strings.Replace(strings.ToLower(string(path)), "/", "", -1)
path = getPathWithoutPrefix(path)
pathStr := getPathWithoutPrefix(path)
if _, ok := routing.AddressMap[string(path)]; !ok {
if _, ok := routing.AllMethods[pathStr]; !ok {
return 0, createError(codes.Unimplemented)
}
for _, notExpectedHeader := range verifiableKeyHeaderKeyMap {
for _, notExpectedHeader := range notExpectedHeaders {
ctx.Request.Header.Del(notExpectedHeader)
}
appToken := ctx.Request.Header.Peek(utils.ApplicationTokenHeader)
var (
err error
appId int32 = -1
)
if len(appToken) == 0 {
return 0, createError(codes.Unauthenticated)
} else if config.GetRemote().(*conf.RemoteConfig).Secrets.VerifyAppToken {
if appId, err = verifyToken.Application(string(appToken)); err != nil || appId == 0 {
return 0, createError(codes.Unauthenticated, "invalid token")
}
}
keys, err := verification.appToken(string(appToken))
verifiableKeys, err := auth.verify.ApplicationToken(string(appToken))
if err != nil {
log.Error(log_code.ErrorAuthenticate, err)
return 0, createError(codes.Internal)
}
if len(keys) != 4 {
return 0, createError(codes.Unauthenticated)
if len(verifiableKeys) != 4 {
return 0, createError(codes.Unauthenticated, "unknown token")
}
verifiableKeys := make(map[string]string)
for i, value := range keys {
verifiableKeys[verifiableKeyHeaderKeyMap[i]] = value
applicationId, err := strconv.Atoi(verifiableKeys[utils.ApplicationIdHeader])
if err != nil {
log.Error(log_code.ErrorAuthenticate, errors.WithMessagef(err, "parse appId from redis"))
return 0, createError(codes.Internal)
}
if appId != -1 && int32(applicationId) != appId {
return 0, createError(codes.Unauthenticated, "unknown application identity")
}
verifiableKeys[utils.DeviceTokenHeader] = string(ctx.Request.Header.Peek(utils.DeviceTokenHeader))
verifiableKeys[utils.UserTokenHeader] = string(ctx.Request.Header.Peek(utils.UserTokenHeader))
verifiableKeys, err = verification.keys(verifiableKeys, uri)
permittedToCall := false
verifiableKeys, permittedToCall, err = auth.verify.Identity(verifiableKeys, pathStr)
if err != nil {
log.Error(log_code.ErrorAuthenticate, err)
return 0, createError(codes.Internal)
}
if verifiableKeys[permittedToCallInfo] == "0" {
if permittedToCall {
return 0, createError(codes.PermissionDenied)
} else {
delete(verifiableKeys, permittedToCallInfo)
}
applicationId, err := strconv.Atoi(verifiableKeys[utils.ApplicationIdHeader])
if err != nil {
log.Error(log_code.ErrorAuthenticate, err)
return 0, createError(codes.Internal)
}
for key, value := range verifiableKeys {
@@ -78,26 +101,26 @@ func Do(ctx *fasthttp.RequestCtx) (int64, error) {
}
}
if _, ok := routing.InnerAddressMap[string(path)]; ok {
if _, ok := routing.InnerMethods[pathStr]; ok {
adminToken := ctx.Request.Header.Peek("x-auth-admin") //todo const key
if token.Check(string(adminToken)) != nil {
if verifyToken.Admin(string(adminToken)) != nil {
return 0, createError(codes.PermissionDenied)
}
}
return int64(applicationId), nil
return appId, nil
}
func getPathWithoutPrefix(path []byte) []byte {
func getPathWithoutPrefix(path []byte) string {
firstFound := false
for i, value := range path {
if value == '/' {
if firstFound {
return path[i+1:]
return string(path[i+1:])
} else {
firstFound = true
}
}
}
return []byte{}
return ""
}
+7 -2
View File
@@ -5,12 +5,13 @@ import (
"google.golang.org/grpc/codes"
)
func createError(status codes.Code) ErrorDescription {
return ErrorDescription{grpcStatus: status}
func createError(status codes.Code, details ...interface{}) ErrorDescription {
return ErrorDescription{grpcStatus: status, details: details}
}
type ErrorDescription struct {
grpcStatus codes.Code
details []interface{}
}
func (e ErrorDescription) Error() string {
@@ -20,3 +21,7 @@ func (e ErrorDescription) Error() string {
func (e ErrorDescription) ConvertToGrpcStatus() codes.Code {
return e.grpcStatus
}
func (e ErrorDescription) Details() []interface{} {
return e.details
}
+30 -9
View File
@@ -7,23 +7,44 @@ import (
"isp-gate-service/conf"
)
var token tokenHelper
var verifyToken token
type tokenHelper struct{}
type appClaims struct {
*jwt.StandardClaims
AppId int32
}
func (tokenHelper) Check(token string) error {
secret := config.GetRemote().(*conf.RemoteConfig).SecretKey
type token struct{}
if parsed, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
func (t token) Admin(token string) error {
secret := config.GetRemote().(*conf.RemoteConfig).Secrets.Admin
_, err := t.parse(token, secret, jwt.MapClaims{})
return err
}
func (t token) Application(token string) (int32, error) {
secret := config.GetRemote().(*conf.RemoteConfig).Secrets.Application
if parsed, err := t.parse(token, secret, &appClaims{StandardClaims: &jwt.StandardClaims{}}); err != nil {
return 0, err
} else if claims, ok := parsed.Claims.(*appClaims); !ok {
return 0, errors.New("token is invalid")
} else {
return claims.AppId, nil
}
}
func (token) parse(token, secret string, claims jwt.Claims) (*jwt.Token, error) {
if parsed, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, errors.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(secret), nil
}); err != nil {
return err
return nil, err
} else if !parsed.Valid {
return errors.New("token is invalid")
return nil, errors.New("token is invalid")
} else {
return parsed, nil
}
return nil
}
+30 -25
View File
@@ -1,13 +1,4 @@
{
"journal": {
"enableRemoteTransfer": true,
"enable": false,
"compress": true,
"filename": "/var/log/isp-gate-service/runtime.log",
"maxSizeMb": 512,
"bufferSize": 4096,
"rotateTimeoutMs": 86400000
},
"metrics": {
"gc": true,
"memory": true,
@@ -17,28 +8,42 @@
"ip": "0.0.0.0"
}
},
"secretKey": "secret key",
"grpcSetting": {},
"serverSetting": {},
"grpcSetting": {
"enableOriginalProtoErrors": false,
"proxyGrpcErrorDetails": false
},
"serverSetting": {
"maxRequestBodySizeBytes": 0
},
"accountingSetting": {
"enable": false,
"setting": [
{
"limits": [
{
"pattern": "/healthcheck/module/group/method",
"timeout": "1s",
"maxCount": 1000
}
],
"applicationId": 1
}
]
"setting": []
},
"redis": {
"address": {
"ip": "127.0.0.1",
"port": "6379"
}
},
"authCacheSetting": {
"evictTimeout": "1m",
"enableCash": false
},
"secrets": {
"admin": "secret",
"application": "SECRET_ACCESS_KEY",
"verifyAppToken": false
},
"journalSetting": {
"journal": {
"rotateTimeoutMs": 86400000,
"enableRemoteTransfer": true,
"enable": false,
"compress": true,
"filename": "/var/log/isp-gate-service/runtime.log",
"maxSizeMb": 512,
"bufferSize": 4096
},
"methodsPatterns": []
}
}
}
+33 -10
View File
@@ -20,14 +20,30 @@ const (
type (
RemoteConfig struct {
SecretKey string `schema:"Секрет"`
ServerSetting ServerSetting `schema:"Настройка сервера"`
GrpcSetting GrpcSetting `schema:"Настройка grpc соединения"`
Metrics structure.MetricConfiguration `schema:"Настройка метрик"`
Journal rx.Config `schema:"Настройка логирования"`
JournalingMethodsPatterns []string `schema:"Список методов для логирования,список строк вида: 'module/group/method'(* - для частичного совпадения). При обработке запроса, если вызываемый метод совпадает со строкой из списка, тела запроса и ответа записываются в лог"`
Redis structure.RedisConfiguration `schema:"Настройка Redis" valid:"required~Required"`
AccountingSetting Accounting `schema:"Настройка учета запросов"`
Secrets SecretSetting `schema:"Настройка секретов"`
ServerSetting HttpSetting `schema:"Настройка сервера"`
GrpcSetting GrpcSetting `schema:"Настройка grpc соединения"`
Metrics structure.MetricConfiguration `schema:"Настройка метрик"`
JournalSetting Journal `schema:"Настройка журалирования"`
Redis structure.RedisConfiguration `schema:"Настройка Redis" valid:"required~Required"`
AccountingSetting Accounting `schema:"Настройка учета запросов"`
AuthCacheSetting Cache `schema:"Настройка кеширования данных аутентификации приложений" valid:"required~Required"`
}
Cache struct {
EnableCash bool `schema:"Кеширование,включает кеширования для токена приложения"`
EvictTimeout string `schema:"Время жизни записи в кеше"`
}
Journal struct {
Journal rx.Config `schema:"Настройка конфигурации"`
MethodsPatterns []string `schema:"Список методов для логирования,список строк вида: 'module/group/method'(* - для частичного совпадения). При обработке запроса, если вызываемый метод совпадает со строкой из списка, тела запроса и ответа записываются в лог"`
}
SecretSetting struct {
Admin string `schema:"Секрет для проверки токена администратора"`
Application string `schema:"Секрет для проверки токена приложений"`
VerifyAppToken bool `schema:"Проверка подписи токена приложений"`
}
Accounting struct {
@@ -36,7 +52,7 @@ type (
}
AccountingSetting struct {
ApplicationId int64 `valid:"required~Required" schema:"Идентификатор приложения"`
ApplicationId int32 `valid:"required~Required" schema:"Идентификатор приложения"`
Limits []LimitSetting `schema:"Настройка ограничений на запросы"`
}
@@ -46,7 +62,7 @@ type (
Timeout string `schema:"Время жизни одного запроса"`
}
ServerSetting struct {
HttpSetting struct {
MaxRequestBodySizeBytes int64 `schema:"Максимальный размер тела запроса,в байтайх, по умолчанию: 512 MB"`
}
@@ -79,3 +95,10 @@ func (cfg GrpcSetting) GetTransferFileBufferSize() int64 {
}
return cfg.MultipartDataTransferBufferSizeBytes
}
func (cfg HttpSetting) GetMaxRequestBodySize() int64 {
if cfg.MaxRequestBodySizeBytes <= 0 {
return defaultMaxRequestBodySize
}
return cfg.MaxRequestBodySizeBytes
}
+23 -21
View File
@@ -39,7 +39,7 @@ func CompleteRequest(ctx *fasthttp.RequestCtx) {
}
requestBody, responseBody, err := resp.Get()
if config.GetRemote().(*conf.RemoteConfig).Journal.Enable {
if config.GetRemote().(*conf.RemoteConfig).JournalSetting.Journal.Enable {
if matcher.JournalMethods.Match(uri) {
if err != nil {
if err := journal.Client.Error(uri, requestBody, responseBody, err); err != nil {
@@ -57,31 +57,33 @@ func CompleteRequest(ctx *fasthttp.RequestCtx) {
func (handlerHelper) AuthenticateApproveProxy(ctx *fasthttp.RequestCtx) domain.ProxyResponse {
path := string(ctx.Path())
applicationId, err := authenticate.Do(ctx)
if err != nil {
status := codes.Unknown
switch e := err.(type) {
case authenticate.ErrorDescription:
status = e.ConvertToGrpcStatus()
}
utils.WriteError(ctx, "unauthorized", status, nil)
return domain.Create().SetError(err)
}
if approver := accounting.GetAccounting(applicationId); approver != nil && !approver.TakeAccount(path) {
err := errors.New("accounting error")
utils.WriteError(ctx, "forbidden", codes.PermissionDenied, nil)
return domain.Create().SetError(err)
}
p := proxy.Find(path)
if p != nil {
return p.ProxyRequest(ctx)
} else {
if p == nil {
err := errors.Errorf("unknown path %s", path)
utils.WriteError(ctx, "not found", codes.NotFound, nil)
return domain.Create().SetError(err)
}
applicationId, err := authenticate.Do(ctx)
if err != nil {
status := codes.Unknown
details := make([]interface{}, 0)
switch e := err.(type) {
case authenticate.ErrorDescription:
status = e.ConvertToGrpcStatus()
details = e.Details()
}
utils.WriteError(ctx, "unauthorized", status, details)
return domain.Create().SetError(err)
}
if approver := accounting.GetAccounting(applicationId); approver != nil && !approver.Check(path) {
err := errors.New("accounting error")
utils.WriteError(ctx, "forbidden", codes.ResourceExhausted, nil)
return domain.Create().SetError(err)
}
return p.ProxyRequest(ctx)
}
func (handlerHelper) SetMetricStatus(statusCode int) string {
+3 -5
View File
@@ -8,13 +8,11 @@ const (
WarnHttpServerShutdown = 602
ErrorHttpServerListen = 603
FatalLocalConfig = 610
ErrorClientGrpc = 606
ErrorClientHttp = 611
ErrorClientGrpc = 606
ErrorClientHttp = 611
ErrorClientJournal = 608
ErrorClientRedis = 609
ErrorAuthenticate = 612
FatalConfigApproveSetting = 613
ErrorAuthenticate = 612
)
+11 -9
View File
@@ -8,10 +8,11 @@ import (
"github.com/integration-system/isp-lib/metric"
"github.com/integration-system/isp-lib/structure"
log "github.com/integration-system/isp-log"
"github.com/integration-system/isp-log/stdcodes"
"isp-gate-service/accounting"
"isp-gate-service/authenticate"
"isp-gate-service/conf"
"isp-gate-service/journal"
"isp-gate-service/log_code"
"isp-gate-service/proxy"
"isp-gate-service/redis"
"isp-gate-service/routing"
@@ -40,7 +41,7 @@ func main() {
for _, location := range cfg.Locations {
if p, err := proxy.Init(location); err != nil {
log.Fatal(log_code.FatalLocalConfig, err)
log.Fatal(stdcodes.ModuleInvalidLocalConfig, err)
} else if location.TargetModule != "" {
bs.RequireModule(location.TargetModule, p.Consumer, false)
}
@@ -58,17 +59,18 @@ func onLocalConfigLoad(cfg *conf.Configuration) {
func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) {
localCfg := config.Get().(*conf.Configuration)
journal.Client.ReceiveConfiguration(remoteConfig.Journal, localCfg.ModuleName)
redis.Client.ReceiveConfiguration(remoteConfig.Redis)
server.Http.Init(remoteConfig.ServerSetting.MaxRequestBodySizeBytes)
accounting.ReceiveConfiguration(remoteConfig.AccountingSetting)
journal.Client.ReceiveConfiguration(remoteConfig.JournalSetting.Journal, localCfg.ModuleName)
matcher.JournalMethods = matcher.NewAtLeastOneMatcher(remoteConfig.JournalSetting.MethodsPatterns)
matcher.JournalMethods = matcher.NewAtLeastOneMatcher(remoteConfig.JournalingMethodsPatterns)
redis.Client.ReceiveConfiguration(remoteConfig.Redis)
accounting.ReceiveConfiguration(remoteConfig.AccountingSetting)
authenticate.ReceiveConfiguration(remoteConfig.AuthCacheSetting)
metric.InitCollectors(remoteConfig.Metrics, oldRemoteConfig.Metrics)
metric.InitHttpServer(remoteConfig.Metrics)
//metric.InitStatusChecker("router-grpc", helper.GetRoutersAndStatus)
service.Metrics.Init()
server.Http.Init(remoteConfig.ServerSetting.GetMaxRequestBodySize())
}
func socketConfiguration(cfg interface{}) structure.SocketConfiguration {
@@ -85,9 +87,9 @@ func socketConfiguration(cfg interface{}) structure.SocketConfiguration {
}
func onShutdown(_ context.Context, _ os.Signal) {
server.Http.Close()
proxy.Close()
redis.Client.Close()
server.Http.Close()
}
func handleRouteUpdate(configs structure.RoutingConfig) bool {
+4 -4
View File
@@ -5,8 +5,8 @@ import (
)
var (
InnerAddressMap = make(map[string]bool)
AddressMap = make(map[string]bool)
InnerMethods = make(map[string]bool)
AllMethods = make(map[string]bool)
)
func InitRoutes(configs structure.RoutingConfig) {
@@ -23,6 +23,6 @@ func InitRoutes(configs structure.RoutingConfig) {
}
}
}
AddressMap = newAddressMap
InnerAddressMap = newInnerAddressMap
AllMethods = newAddressMap
InnerMethods = newInnerAddressMap
}
@@ -0,0 +1,52 @@
package veritification
import (
"sync"
"time"
)
type (
cacheableVerify struct {
cache map[string]cacheInfo
timeout time.Duration
rv *runtimeVerify
lock sync.RWMutex
}
cacheInfo struct {
created time.Time
identity map[string]string
}
)
func (cv *cacheableVerify) ApplicationToken(token string) (map[string]string, error) {
cv.lock.RLock()
cache, ok := cv.cache[token]
cv.lock.RUnlock()
if ok {
if time.Now().Sub(cache.created) > cv.timeout {
return cache.identity, nil
}
}
cv.lock.Lock()
defer cv.lock.Unlock()
if cache, ok = cv.cache[token]; ok {
if time.Now().Sub(cache.created) > cv.timeout {
return cache.identity, nil
} else {
delete(cv.cache, token)
}
}
if identity, err := cv.rv.ApplicationToken(token); err != nil {
return nil, err
} else {
cv.cache[token] = cacheInfo{created: time.Now(), identity: identity}
resp := identity
return resp, nil
}
}
func (cv *cacheableVerify) Identity(identity map[string]string, uri string) (map[string]string, bool, error) {
return cv.rv.Identity(identity, uri)
}
@@ -1,4 +1,4 @@
package authenticate
package veritification
import (
"fmt"
@@ -11,20 +11,18 @@ import (
rdClient "isp-gate-service/redis"
)
const (
systemIdentity = "1"
domainIdentity = "2"
serviceIdentity = "3"
applicationIdentity = "4"
const permittedToCallInfo = "0"
permittedToCallInfo = "permittedToCallInfo"
)
var headerKeyByRedisIdentity = map[string]string{
"1": utils.SystemIdHeader,
"2": utils.DomainIdHeader,
"3": utils.ServiceIdHeader,
"4": utils.ApplicationIdHeader,
}
var verification verificationHelper
type runtimeVerify struct{}
type verificationHelper struct{}
func (v verificationHelper) appToken(token string) (map[string]string, error) {
func (v *runtimeVerify) ApplicationToken(token string) (map[string]string, error) {
instanceUuid := config.Get().(*conf.Configuration).InstanceUuid
key := fmt.Sprintf("%s|%s", token, instanceUuid)
@@ -46,15 +44,20 @@ func (v verificationHelper) appToken(token string) (map[string]string, error) {
} else if stringStringMapCmd, ok := resp[1].(*rd.StringStringMapCmd); !ok {
return nil, nil
} else {
return stringStringMapCmd.Val(), nil
identityMap := make(map[string]string)
for i, value := range stringStringMapCmd.Val() {
identityMap[headerKeyByRedisIdentity[i]] = value
}
return identityMap, nil
}
}
}
func (v *verificationHelper) keys(t map[string]string, uri string) (map[string]string, error) {
func (v *runtimeVerify) Identity(t map[string]string, uri string) (map[string]string, bool, error) {
secondDbKey := fmt.Sprintf("%s|%s", t[utils.ApplicationIdHeader], uri)
thirdDbKey := fmt.Sprintf("%s|%s", t[utils.UserTokenHeader], t[utils.DomainIdHeader])
fifthDbKey := fmt.Sprintf("%s|%s", t[utils.DeviceTokenHeader], t[utils.DomainIdHeader])
permittedToCall := false
if resp, err := rdClient.Client.Get().Pipelined(func(p rd.Pipeliner) error {
if cmd := p.Select(int(redis.ApplicationPermissionDb)); v.notEmptyError(cmd.Err()) {
@@ -79,35 +82,35 @@ func (v *verificationHelper) keys(t map[string]string, uri string) (map[string]s
}
return nil
}); v.notEmptyError(err) {
return t, err
return t, false, err
} else {
// It is not permitted to call this methodParts
if msg, err := v.findStringCmd(resp, 1); err != nil {
return t, err
} else {
t[permittedToCallInfo] = msg
return t, false, err
} else if msg == permittedToCallInfo {
permittedToCall = true
}
// ===== CHECK USER TOKEN =====
if msg, err := v.findStringCmd(resp, 3); err != nil {
return t, err
return t, false, err
} else {
t[utils.UserIdHeader] = msg
}
// ===== CHECK DEVICE TOKEN =====
if msg, err := v.findStringCmd(resp, 5); err != nil {
return t, err
return t, false, err
} else {
t[utils.DeviceIdHeader] = msg
}
}
return t, nil
return t, permittedToCall, nil
}
func (v *verificationHelper) notEmptyError(err error) bool {
func (v *runtimeVerify) notEmptyError(err error) bool {
return err != nil && err != rd.Nil
}
func (v *verificationHelper) findStringCmd(cmders []rd.Cmder, arrayKey int) (string, error) {
func (v *runtimeVerify) findStringCmd(cmders []rd.Cmder, arrayKey int) (string, error) {
if len(cmders) > arrayKey {
cmd := cmders[arrayKey]
if cmd != nil {
+24
View File
@@ -0,0 +1,24 @@
package veritification
import (
"time"
)
var Default = NewRuntimeVerify()
type Verify interface {
ApplicationToken(string) (map[string]string, error)
Identity(map[string]string, string) (map[string]string, bool, error)
}
func NewRuntimeVerify() Verify {
return &runtimeVerify{}
}
func NewCacheableVerify(timeout time.Duration) Verify {
return &cacheableVerify{
cache: make(map[string]cacheInfo),
timeout: timeout,
rv: &runtimeVerify{},
}
}