fix(token revoke)

This commit is contained in:
DeniskaRediska committed 2019-11-12 16:17:37 +03:00
1 parent 0aec014161
commit 0aa1dc40fd
9 files changed
+149 -98

No files matched your search

+1
View File
@@ -1,5 +1,6 @@
### v1.2.0
* add `access list` methods
* fix revoke token
### v1.1.3
* update to new log
* migrate to new db client
+2 -1
View File
@@ -23,5 +23,6 @@
"path": "/metrics",
"port": "9555"
}
}
},
"secretKey": "SECRET_ACCESS_KEY"
}
+1
View File
@@ -9,4 +9,5 @@ type RemoteConfig struct {
Redis structure.RedisConfiguration `schema:"Настройка Redis" valid:"required~Required"`
DefaultTokenExpireTime int64 `schema:"Время жизни токена по умолчанию,время жизни токена в миллисекундах с момента его создания. если = -1 - время жизни неограниченно"`
Metrics structure.MetricConfiguration `schema:"Настройка метрик"`
SecretKey string `valid:"required~Required"`
}
+33 -26
View File
@@ -4,6 +4,8 @@ import (
"fmt"
rd "github.com/go-redis/redis"
rdLib "github.com/integration-system/isp-lib/redis"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-system-service/domain"
"isp-system-service/entity"
"isp-system-service/model"
@@ -21,14 +23,21 @@ type accessListController struct{}
// @Accept json
// @Produce json
// @Param body body domain.Identity false "идентификатор приложения"
// @Success 200 {array} domain.ModuleMethods "список методов по названию модуля"
// @Success 200 {array} domain.MethodInfo "список доступности методов"
// @Failure 404 {object} structure.GrpcError
// @Failure 500 {object} structure.GrpcError
// @Router /access_list/get_by_id [POST]
func (a accessListController) GetById(req domain.Identity) (domain.ModuleMethods, error) {
func (c accessListController) GetById(req domain.Identity) ([]domain.MethodInfo, error) {
if app, err := model.AppRep.GetApplicationById(req.Id); err != nil {
return nil, err
} else if app == nil {
return nil, status.Errorf(codes.NotFound, "application '%d' not found", req.Id)
}
if accessList, err := model.AccessListRep.GetByAppId(req.Id); err != nil {
return nil, err
} else {
return a.convertAccessList(accessList), nil
return c.convertAccessList(accessList), nil
}
}
@@ -40,9 +49,16 @@ func (a accessListController) GetById(req domain.Identity) (domain.ModuleMethods
// @Produce json
// @Param body body entity.AccessList false "объект для настройки доступа"
// @Success 200 {object} domain.CountResponse "количество измененных строк"
// @Failure 404 {object} structure.GrpcError
// @Failure 500 {object} structure.GrpcError
// @Router /access_list/set_one [POST]
func (c accessListController) SetOne(request entity.AccessList) (*domain.CountResponse, error) {
if app, err := model.AppRep.GetApplicationById(request.AppId); err != nil {
return nil, err
} else if app == nil {
return nil, status.Errorf(codes.NotFound, "application '%d' not found", request.AppId)
}
var (
resp = 0
err error
@@ -78,9 +94,16 @@ func (c accessListController) SetOne(request entity.AccessList) (*domain.CountRe
// @Produce json
// @Param body body domain.SetListRequest false "объект настройки доступа"
// @Success 200 {object} domain.CountResponse "количество добавленных строк"
// @Failure 404 {object} structure.GrpcError
// @Failure 500 {object} structure.GrpcError
// @Router /access_list/set_list [POST]
func (c accessListController) SetList(request domain.SetListRequest) (*domain.CountResponse, error) {
if app, err := model.AppRep.GetApplicationById(request.AppId); err != nil {
return nil, err
} else if app == nil {
return nil, status.Errorf(codes.NotFound, "application '%d' not found", request.AppId)
}
resp := 0
if err := model.DbClient.RunInTransaction(func(repository model.AccessListRepository) error {
@@ -132,29 +155,13 @@ func (c accessListController) SetList(request domain.SetListRequest) (*domain.Co
}
}
func (c accessListController) convertAccessList(accessLists []entity.AccessList) domain.ModuleMethods {
response := make(map[string][]domain.MethodInfo)
for _, access := range accessLists {
moduleName, method := c.extractModuleName(access.Method)
if methodStore, ok := response[moduleName]; ok {
response[moduleName] = append(methodStore, domain.MethodInfo{Value: access.Value, Method: method})
} else {
response[moduleName] = []domain.MethodInfo{{Value: access.Value, Method: method}}
func (accessListController) convertAccessList(accessLists []entity.AccessList) []domain.MethodInfo {
methodInfos := make([]domain.MethodInfo, len(accessLists))
for i, access := range accessLists {
methodInfos[i] = domain.MethodInfo{
Method: access.Method,
Value: access.Value,
}
}
return response
}
func (accessListController) extractModuleName(method string) (string, string) {
firstFound := false
for i, value := range method {
if value == '/' {
if firstFound {
return method[:i], method[i:]
} else {
firstFound = true
}
}
}
return method, ""
return methodInfos
}
+1 -1
View File
@@ -162,7 +162,7 @@ func (applicationController) DeleteApplications(list []int32) (domain.DeleteResp
appRep model.AppRepository, tokenRep model.TokenRepository, accessRep model.AccessListRepository) error {
for _, appId := range list {
if _, err := Token.revokeTokensForApp(domain.Identity{appId}, &tokenRep); err != nil {
if _, err := Token.revokeTokensForApp(domain.Identity{Id: appId}, &tokenRep); err != nil {
return err
}
}
+56 -55
View File
@@ -5,7 +5,6 @@ import (
rd "github.com/go-redis/redis"
"github.com/integration-system/isp-lib/config"
redisLib "github.com/integration-system/isp-lib/redis"
"github.com/integration-system/isp-lib/token-gen"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"isp-system-service/conf"
@@ -13,6 +12,7 @@ import (
"isp-system-service/entity"
"isp-system-service/model"
"isp-system-service/redis"
"isp-system-service/service"
"time"
)
@@ -23,10 +23,7 @@ const (
ApplicationIdentityFieldInDb = "4"
)
var (
Token tokenController
generator = tg.NewGenerator(tg.DefaultAlphabet)
)
var Token tokenController
type tokenController struct{}
@@ -46,38 +43,29 @@ func (c tokenController) CreateToken(req domain.CreateTokenRequest) (*domain.App
return nil, err
}
cfg := config.GetRemote().(*conf.RemoteConfig)
var id string
var existed = true
for existed {
id = generator.Next(tg.DefaultTokenLength)
t, err := model.TokenRep.GetTokenById(id)
if err != nil {
return nil, err
}
existed = t != nil
}
expTime := req.ExpireTimeMs
if expTime == 0 {
expTime = cfg.DefaultTokenExpireTime
expTime = config.GetRemote().(*conf.RemoteConfig).DefaultTokenExpireTime
}
token := entity.Token{
Token: id,
token, err := service.Jwt.Generate(req.AppId, expTime)
if err != nil {
return nil, err
}
tokenInfo := entity.Token{
Token: token,
ExpireTime: expTime,
AppId: req.AppId,
CreatedAt: time.Now(),
}
err = c.setIdentityMapForToken(token, m)
if err != nil {
return nil, err
}
token, err = model.TokenRep.SaveToken(token)
if err != nil {
redis.Client.Get().Del(token.Token)
if err := model.DbClient.RunInTransaction(func(repository model.TokenRepository) error {
tokenInfo, err = repository.SaveToken(tokenInfo)
if err != nil {
return err
}
return c.setIdentityMapForToken(tokenInfo, m)
}); err != nil {
return nil, err
}
@@ -104,14 +92,17 @@ func (c tokenController) RevokeTokens(req domain.RevokeTokensRequest) (*domain.A
if err != nil {
return nil, err
}
_, err = c.revokeTokens(req.Tokens, &model.TokenRep)
if err != nil {
return nil, err
}
res, err := Application.enrichWithTokens(*app)
if err != nil {
return nil, err
}
return res[0], nil
}
@@ -148,10 +139,10 @@ func (c tokenController) setIdentityMapForToken(token entity.Token, idMap map[st
}
func (tokenController) SetIdentityMapForTokenV2(token string, expireTime int64, idMap map[string]interface{}) error {
cfg := config.Get().(*conf.Configuration)
instanceUuid := config.Get().(*conf.Configuration).InstanceUuid
_, e := redis.Client.Get().UseDbTx(redisLib.ApplicationTokenDb, func(p rd.Pipeliner) error {
t := fmt.Sprintf("%s|%s", token, cfg.InstanceUuid)
stat := p.HMSet(t, idMap)
key := fmt.Sprintf("%s|%s", token, instanceUuid)
stat := p.HMSet(key, idMap)
err := stat.Err()
if err != nil {
return err
@@ -165,44 +156,44 @@ func (tokenController) SetIdentityMapForTokenV2(token string, expireTime int64,
}
func (tokenController) getIdMap(appId int32) (map[string]interface{}, error, *entity.Application) {
app, err := model.AppRep.GetApplicationById(appId)
appInfo, err := model.AppRep.GetApplicationById(appId)
if err != nil {
return nil, err, nil
}
if app == nil {
if appInfo == nil {
return nil, status.Errorf(codes.NotFound, "Application with id %d not found", appId), nil
}
service, err := model.ServiceRep.GetServiceById(app.ServiceId)
serviceInfo, err := model.ServiceRep.GetServiceById(appInfo.ServiceId)
if err != nil {
return nil, err, app
return nil, err, appInfo
}
if service == nil {
return nil, status.Errorf(codes.NotFound, "Service with id %d not found", app.ServiceId), app
if serviceInfo == nil {
return nil, status.Errorf(codes.NotFound, "Service with id %d not found", appInfo.ServiceId), appInfo
}
domainInfo, err := model.DomainRep.GetDomainById(service.DomainId)
domainInfo, err := model.DomainRep.GetDomainById(serviceInfo.DomainId)
if err != nil {
return nil, err, app
return nil, err, appInfo
}
if domainInfo == nil {
return nil, status.Errorf(codes.NotFound, "Domain with id %d not found", service.DomainId), app
return nil, status.Errorf(codes.NotFound, "Domain with id %d not found", serviceInfo.DomainId), appInfo
}
system, err := model.SystemRep.GetSystemById(domainInfo.SystemId)
systemInfo, err := model.SystemRep.GetSystemById(domainInfo.SystemId)
if err != nil {
return nil, err, app
return nil, err, appInfo
}
if system == nil {
return nil, status.Errorf(codes.NotFound, "System with id %d not found", domainInfo.SystemId), app
if systemInfo == nil {
return nil, status.Errorf(codes.NotFound, "System with id %d not found", domainInfo.SystemId), appInfo
}
return map[string]interface{}{
SystemIdentityFieldInDb: system.Id,
SystemIdentityFieldInDb: systemInfo.Id,
DomainIdentityFieldInDb: domainInfo.Id,
ServiceIdentityFieldInDb: service.Id,
ApplicationIdentityFieldInDb: app.Id,
}, nil, app
ServiceIdentityFieldInDb: serviceInfo.Id,
ApplicationIdentityFieldInDb: appInfo.Id,
}, nil, appInfo
}
func (c tokenController) revokeTokensForApp(identity domain.Identity, tokenRep *model.TokenRepository) (*domain.DeleteResponse, error) {
@@ -222,18 +213,28 @@ func (c tokenController) revokeTokensForApp(identity domain.Identity, tokenRep *
}
func (tokenController) revokeTokens(tokens []string, tokenRep *model.TokenRepository) (*domain.DeleteResponse, error) {
var count = 0
if len(tokens) == 0 {
return &domain.DeleteResponse{Deleted: 0}, nil
}
instanceUuid := config.Get().(*conf.Configuration).InstanceUuid
var count = 0
keys := make([]string, len(tokens))
for i, token := range tokens {
keys[i] = fmt.Sprintf("%s|%s", token, instanceUuid)
}
_, e := redis.Client.Get().UseDbTx(redisLib.ApplicationTokenDb, func(p rd.Pipeliner) error {
deleted, err := tokenRep.DeleteTokens(tokens)
count = deleted
if err != nil {
if _, err := p.Del(keys...).Result(); err != nil {
return err
}
res := p.Del(tokens...)
return res.Err()
if deleted, err := tokenRep.DeleteTokens(tokens); err != nil {
return err
} else {
count = deleted
return nil
}
})
if e != nil {
return nil, e
+14 -13
View File
@@ -56,17 +56,6 @@ definitions:
value:
type: boolean
type: object
domain.ModuleMethods:
additionalProperties:
items:
properties:
method:
type: string
value:
type: boolean
type: object
type: array
type: object
domain.RevokeTokensRequest:
properties:
appId:
@@ -249,11 +238,15 @@ paths:
- application/json
responses:
"200":
description: список методов по названию модуля
description: список доступности методов
schema:
items:
$ref: '#/definitions/domain.ModuleMethods'
$ref: '#/definitions/domain.MethodInfo'
type: array
"404":
description: Not Found
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
@@ -280,6 +273,10 @@ paths:
description: количество добавленных строк
schema:
$ref: '#/definitions/domain.CountResponse'
"404":
description: Not Found
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
@@ -306,6 +303,10 @@ paths:
description: количество измененных строк
schema:
$ref: '#/definitions/domain.CountResponse'
"404":
description: Not Found
schema:
$ref: '#/definitions/structure.GrpcError'
"500":
description: Internal Server Error
schema:
-2
View File
@@ -38,8 +38,6 @@ type (
Tokens []entity.Token
}
ModuleMethods map[string][]MethodInfo
MethodInfo struct {
Method string
Value bool
+41
View File
@@ -0,0 +1,41 @@
package service
import (
"encoding/hex"
"github.com/dgrijalva/jwt-go"
"github.com/integration-system/isp-lib/config"
"isp-system-service/conf"
"math/rand"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
var Jwt jwtService
type jwtService struct{}
func (s jwtService) Generate(appId int32, expTime int64) (string, error) {
var (
claims = jwt.MapClaims{}
created = time.Now()
secret = config.GetRemote().(*conf.RemoteConfig).SecretKey
)
claims["appId"] = appId
claims["iat"] = created.Unix()
claims["salt"] = s.getSalt()
if expTime > 0 {
claims["exp"] = created.Add(time.Millisecond * time.Duration(expTime)).Unix()
}
return jwt.NewWithClaims(jwt.SigningMethodHS512, claims).SignedString([]byte(secret))
}
func (jwtService) getSalt() string {
salt := make([]byte, rand.Intn(30)+10)
rand.Read(salt)
return hex.EncodeToString(salt)
}