MSP-1538 implement inactive user blocker
This commit is contained in:
1 parent
72e89b1c9f
commit
fdd46409cd
5 files changed
+162
-7
No files matched your search
@@ -12,5 +12,9 @@
|
|||||||
"maxInFlightLoginRequests" : 3,
|
"maxInFlightLoginRequests" : 3,
|
||||||
"delayLoginRequestInSec": 3
|
"delayLoginRequestInSec": 3
|
||||||
},
|
},
|
||||||
"expireSec": 3600
|
"expireSec": 3600,
|
||||||
|
"blockInactiveWorker" : {
|
||||||
|
"daysThreshold": 90,
|
||||||
|
"runIntervalInMinutes": 60
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+12
-6
@@ -17,12 +17,13 @@ func init() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type Remote struct {
|
type Remote struct {
|
||||||
Database dbx.Config
|
Database dbx.Config
|
||||||
ExpireSec int `valid:"required" schema:"Время жизни токена в секундах,in seconds"`
|
ExpireSec int `valid:"required" schema:"Время жизни токена в секундах,in seconds"`
|
||||||
UiDesign UIDesign `schema:"Кастомизация интерфейса"`
|
UiDesign UIDesign `schema:"Кастомизация интерфейса"`
|
||||||
SudirAuth *SudirAuth `schema:"СУДИР авторизация"`
|
SudirAuth *SudirAuth `schema:"СУДИР авторизация"`
|
||||||
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
|
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
|
||||||
AntiBruteforce AntiBruteforce `schema:"Настройки антибрут для admin login"`
|
AntiBruteforce AntiBruteforce `schema:"Настройки антибрут для admin login"`
|
||||||
|
BlockInactiveWorker BlockInactiveWorker `valid:"required" schema:"Блокировка неактивных УЗ"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type UIDesign struct {
|
type UIDesign struct {
|
||||||
@@ -41,3 +42,8 @@ type AntiBruteforce struct {
|
|||||||
MaxInFlightLoginRequests int `valid:"required~Required" schema:"Количество одновременных запросов /login"`
|
MaxInFlightLoginRequests int `valid:"required~Required" schema:"Количество одновременных запросов /login"`
|
||||||
DelayLoginRequestInSec int `valid:"required~Required" schema:"Задержка выполнения /login"`
|
DelayLoginRequestInSec int `valid:"required~Required" schema:"Задержка выполнения /login"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type BlockInactiveWorker struct {
|
||||||
|
DaysThreshold int `valid:"required" schema:"Кол-во дней"`
|
||||||
|
RunIntervalInMinutes int `valid:"required" schema:"Интервал запуска,в минутах"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package conf_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/integration-system/isp-kit/test/rct"
|
||||||
|
"msp-admin-service/conf"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDefaultRemoteConfig(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
rct.Test(t, "default_remote_config.json", conf.Remote{})
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
package worker
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/integration-system/isp-kit/log"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AuditRepo interface {
|
||||||
|
SaveAuditAsync(ctx context.Context, userId int64, message string)
|
||||||
|
}
|
||||||
|
|
||||||
|
type TokenRepo interface {
|
||||||
|
LastAccessNotBlockedUsers(ctx context.Context) (map[int64]time.Time, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type UserRepo interface {
|
||||||
|
Block(ctx context.Context, userId int) error
|
||||||
|
}
|
||||||
|
|
||||||
|
type InactiveBlocker struct {
|
||||||
|
tokenRepo TokenRepo
|
||||||
|
userRepo UserRepo
|
||||||
|
auditRepo AuditRepo
|
||||||
|
threshold time.Duration
|
||||||
|
logger log.Logger
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewInactiveBlocker(
|
||||||
|
tokensRepo TokenRepo,
|
||||||
|
userRepo UserRepo,
|
||||||
|
auditRepo AuditRepo,
|
||||||
|
inactiveThresholdInDays int,
|
||||||
|
logger log.Logger,
|
||||||
|
) InactiveBlocker {
|
||||||
|
return InactiveBlocker{
|
||||||
|
tokenRepo: tokensRepo,
|
||||||
|
userRepo: userRepo,
|
||||||
|
auditRepo: auditRepo,
|
||||||
|
threshold: time.Duration(inactiveThresholdInDays) * 24 * time.Hour,
|
||||||
|
logger: logger,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w InactiveBlocker) Do(ctx context.Context) {
|
||||||
|
ctx = log.ToContext(ctx, log.String("worker", "inactiveBlocker"))
|
||||||
|
w.logger.Debug(ctx, "begin work")
|
||||||
|
err := w.do(ctx)
|
||||||
|
if err != nil {
|
||||||
|
w.logger.Error(ctx, "error", log.Any("error", err))
|
||||||
|
}
|
||||||
|
w.logger.Debug(ctx, "end work")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w InactiveBlocker) do(ctx context.Context) error {
|
||||||
|
lastAccess, err := w.tokenRepo.LastAccessNotBlockedUsers(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessage(err, "get last access times")
|
||||||
|
}
|
||||||
|
|
||||||
|
now := time.Now().UTC()
|
||||||
|
for userId, lastAccess := range lastAccess {
|
||||||
|
dur := now.Sub(lastAccess)
|
||||||
|
if dur < w.threshold {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
w.logger.Info(ctx, "block inactive user", log.Int64("userId", userId), log.Any("lastAccessTime", lastAccess))
|
||||||
|
err := w.userRepo.Block(ctx, int(userId))
|
||||||
|
if err != nil {
|
||||||
|
return errors.WithMessagef(err, "block user %d", userId)
|
||||||
|
}
|
||||||
|
w.auditRepo.SaveAuditAsync(ctx, userId, "Блокировка неактивной УЗ")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package tests
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/integration-system/isp-kit/dbx"
|
||||||
|
"github.com/integration-system/isp-kit/test"
|
||||||
|
"github.com/integration-system/isp-kit/test/dbt"
|
||||||
|
"msp-admin-service/assembly"
|
||||||
|
"msp-admin-service/conf"
|
||||||
|
"msp-admin-service/entity"
|
||||||
|
"msp-admin-service/repository"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestInactiveWorker(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
|
test, require := test.New(t)
|
||||||
|
db := dbt.New(test, dbx.WithMigration("../migrations"))
|
||||||
|
|
||||||
|
userId := InsertUser(db, entity.User{RoleId: 1, Email: "a@test"})
|
||||||
|
InsertUser(db, entity.User{RoleId: 1, Email: "b@test"})
|
||||||
|
InsertTokenEntity(db, entity.Token{
|
||||||
|
Id: 0,
|
||||||
|
Token: "123",
|
||||||
|
UserId: userId,
|
||||||
|
Status: entity.TokenStatusAllowed,
|
||||||
|
CreatedAt: time.Now().UTC().Add(-48 * time.Hour),
|
||||||
|
})
|
||||||
|
InsertTokenEntity(db, entity.Token{
|
||||||
|
Id: 0,
|
||||||
|
Token: "234",
|
||||||
|
UserId: userId,
|
||||||
|
Status: entity.TokenStatusAllowed,
|
||||||
|
CreatedAt: time.Now().UTC().Add(-5 * 24 * time.Hour),
|
||||||
|
})
|
||||||
|
|
||||||
|
worker := assembly.NewLocator(test.Logger(), nil, db).
|
||||||
|
Config(conf.Remote{BlockInactiveWorker: conf.BlockInactiveWorker{DaysThreshold: 1}}).
|
||||||
|
InactiveBlocker
|
||||||
|
worker.Do(context.Background())
|
||||||
|
time.Sleep(1 * time.Second)
|
||||||
|
|
||||||
|
user, err := repository.NewUser(db).GetUserById(context.Background(), userId)
|
||||||
|
require.NoError(err)
|
||||||
|
require.True(user.Blocked)
|
||||||
|
|
||||||
|
list, err := repository.NewAudit(db).All(context.Background(), 10, 0)
|
||||||
|
require.NoError(err)
|
||||||
|
require.Len(list, 1)
|
||||||
|
}
|
||||||
Reference in new issue
Block a user