MSP-2243 implement ldap integration
This commit is contained in:
1 parent
051dea1674
commit
cd04e996e1
20 files changed
+567
-184
No files matched your search
@@ -5,6 +5,7 @@
|
||||
* добавлен метод admin/log/set_events
|
||||
* добавлен метод admin/log/events
|
||||
* обновлены зависимости
|
||||
* исправлен сбор метрик
|
||||
### v5.0.0
|
||||
* изменён механизм ролей и пользователей
|
||||
### v4.3.0
|
||||
|
||||
+16
-20
@@ -2,7 +2,6 @@ package assembly
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/integration-system/isp-kit/app"
|
||||
"github.com/integration-system/isp-kit/bgjobx"
|
||||
@@ -14,10 +13,12 @@ import (
|
||||
"github.com/integration-system/isp-kit/http/httpcli"
|
||||
"github.com/integration-system/isp-kit/http/httpclix"
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"github.com/integration-system/isp-kit/worker"
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/conf"
|
||||
ldapRepo "msp-admin-service/repository/ldap"
|
||||
"msp-admin-service/service/delete_old_audit_worker"
|
||||
"msp-admin-service/service/inactive_worker"
|
||||
"msp-admin-service/service/ldap"
|
||||
)
|
||||
|
||||
type Assembly struct {
|
||||
@@ -25,7 +26,6 @@ type Assembly struct {
|
||||
db *dbrx.Client
|
||||
server *grpc.Server
|
||||
httpCli *httpcli.Client
|
||||
worker *worker.Worker
|
||||
logger *log.Adapter
|
||||
bgjobCli *bgjobx.Client
|
||||
}
|
||||
@@ -59,11 +59,17 @@ func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error
|
||||
|
||||
err = a.db.Upgrade(ctx, newCfg.Database)
|
||||
if err != nil {
|
||||
a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade db client"), log.Any("config", a.hiddenSecret(newCfg.Database)))
|
||||
a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade db client"))
|
||||
}
|
||||
|
||||
locator := NewLocator(a.logger, a.httpCli, a.db)
|
||||
config := locator.Config(ctx, newCfg)
|
||||
config := locator.Config(ctx, func(config *conf.Ldap) (ldap.Repo, error) {
|
||||
repo, err := ldapRepo.NewRepository(config)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "new repository")
|
||||
}
|
||||
return repo, nil
|
||||
}, newCfg)
|
||||
|
||||
a.server.Upgrade(config.Handler)
|
||||
|
||||
@@ -72,18 +78,13 @@ func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error
|
||||
a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade bgjob client"))
|
||||
}
|
||||
|
||||
if a.worker != nil {
|
||||
a.worker.Shutdown()
|
||||
}
|
||||
a.worker = worker.New(
|
||||
config.InactiveBlocker,
|
||||
worker.WithInterval(time.Duration(newCfg.BlockInactiveWorker.RunIntervalInMinutes)*time.Minute),
|
||||
)
|
||||
a.worker.Run(a.boot.App.Context())
|
||||
|
||||
err = delete_old_audit_worker.EnqueueSeedJob(ctx, a.bgjobCli)
|
||||
if err != nil {
|
||||
a.logger.Fatal(ctx, errors.WithMessage(err, "initial sync job"))
|
||||
a.logger.Fatal(ctx, errors.WithMessage(err, "seed delete old audit worker"))
|
||||
}
|
||||
err = inactive_worker.EnqueueSeedJob(ctx, a.bgjobCli)
|
||||
if err != nil {
|
||||
a.logger.Fatal(ctx, errors.WithMessage(err, "seed inactive user worker"))
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -124,8 +125,3 @@ func (a *Assembly) Closers() []app.Closer {
|
||||
a.db,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Assembly) hiddenSecret(conf dbx.Config) dbx.Config {
|
||||
conf.Password = "***"
|
||||
return conf
|
||||
}
|
||||
+25
-18
@@ -16,10 +16,15 @@ import (
|
||||
"msp-admin-service/routes"
|
||||
"msp-admin-service/service"
|
||||
"msp-admin-service/service/delete_old_audit_worker"
|
||||
"msp-admin-service/service/worker"
|
||||
"msp-admin-service/service/inactive_worker"
|
||||
"msp-admin-service/service/ldap"
|
||||
"msp-admin-service/transaction"
|
||||
)
|
||||
|
||||
var (
|
||||
JobPollInterval = 1 * time.Minute //nolint:gochecknoglobals
|
||||
)
|
||||
|
||||
type DB interface {
|
||||
db.DB
|
||||
db.Transactional
|
||||
@@ -40,12 +45,11 @@ func NewLocator(logger log.Logger, httpCli *httpcli.Client, db DB) Locator {
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Handler isp.BackendServiceServer
|
||||
InactiveBlocker worker.InactiveBlocker
|
||||
BgJobCfg []bgjobx.WorkerConfig
|
||||
Handler isp.BackendServiceServer
|
||||
BgJobCfg []bgjobx.WorkerConfig
|
||||
}
|
||||
|
||||
func (l Locator) Config(ctx context.Context, cfg conf.Remote) Config {
|
||||
func (l Locator) Config(ctx context.Context, ldapRepoSupplier ldap.RepoSupplier, cfg conf.Remote) Config {
|
||||
sudirRepo := repository.NewSudir(l.httpCli, cfg.SudirAuth)
|
||||
roleRepo := repository.NewRole(l.db)
|
||||
userRepo := repository.NewUser(l.db)
|
||||
@@ -93,24 +97,27 @@ func (l Locator) Config(ctx context.Context, cfg conf.Remote) Config {
|
||||
},
|
||||
)
|
||||
|
||||
inactiveBlocker := worker.NewInactiveBlocker(
|
||||
tokenRepo, userRepo, auditService,
|
||||
cfg.BlockInactiveWorker.DaysThreshold,
|
||||
ldapService := ldap.NewService(cfg.Ldap, ldapRepoSupplier, userRoleRepo, roleRepo, l.logger)
|
||||
inactiveBlocker := inactive_worker.NewInactiveBlocker(
|
||||
tokenRepo, userRepo, auditService, ldapService,
|
||||
cfg.BlockInactiveWorker,
|
||||
l.logger,
|
||||
)
|
||||
|
||||
deleteOldAuditWorker := delete_old_audit_worker.NewService(l.logger, auditRepo, cfg.Audit.AuditTTl)
|
||||
|
||||
return Config{
|
||||
Handler: handler,
|
||||
InactiveBlocker: inactiveBlocker,
|
||||
BgJobCfg: []bgjobx.WorkerConfig{
|
||||
{
|
||||
Queue: delete_old_audit_worker.QueueName,
|
||||
Concurrency: 1,
|
||||
PollInterval: 1 * time.Second,
|
||||
Handle: deleteOldAuditWorker,
|
||||
},
|
||||
},
|
||||
Handler: handler,
|
||||
BgJobCfg: []bgjobx.WorkerConfig{{
|
||||
Queue: delete_old_audit_worker.QueueName,
|
||||
Concurrency: 1,
|
||||
PollInterval: JobPollInterval,
|
||||
Handle: deleteOldAuditWorker,
|
||||
}, {
|
||||
Queue: inactive_worker.QueueName,
|
||||
Concurrency: 1,
|
||||
PollInterval: JobPollInterval,
|
||||
Handle: inactiveBlocker,
|
||||
}},
|
||||
}
|
||||
}
|
||||
+9
-1
@@ -26,7 +26,8 @@ type Remote struct {
|
||||
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
|
||||
AntiBruteforce AntiBruteforce `schema:"Настройки антибрут для admin login"`
|
||||
BlockInactiveWorker BlockInactiveWorker `valid:"required" schema:"Блокировка неактивных УЗ"`
|
||||
Permissions []Permission
|
||||
Permissions []Permission `schema:"Список разрешений"`
|
||||
Ldap *Ldap `schema:"Настройки LDAP"`
|
||||
}
|
||||
|
||||
type Audit struct {
|
||||
@@ -70,3 +71,10 @@ type Permission struct {
|
||||
Key string
|
||||
Name string
|
||||
}
|
||||
|
||||
type Ldap struct {
|
||||
Address string `valid:"required" schema:"Адрес LDAP"`
|
||||
Username string `valid:"required" schema:"Пользователь сервисной УЗ"`
|
||||
Password string `valid:"required" schema:"Пароль сервисной УЗ"`
|
||||
BaseDn string `valid:"required"`
|
||||
}
|
||||
@@ -4,7 +4,8 @@ go 1.21
|
||||
|
||||
require (
|
||||
github.com/Masterminds/squirrel v1.5.4
|
||||
github.com/google/uuid v1.3.0
|
||||
github.com/go-ldap/ldap/v3 v3.4.6
|
||||
github.com/google/uuid v1.3.1
|
||||
github.com/integration-system/bgjob v1.3.0
|
||||
github.com/integration-system/isp-kit v1.24.2
|
||||
github.com/integration-system/jsonschema v1.0.1
|
||||
@@ -16,10 +17,12 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 // indirect
|
||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.5 // indirect
|
||||
github.com/golang/protobuf v1.5.3 // indirect
|
||||
github.com/gorilla/websocket v1.4.2 // indirect
|
||||
github.com/iancoleman/strcase v0.3.0 // indirect
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 h1:mFRzDkZVAjdal+s7s0MwaRv9igoPqLRdzOLzw/8Xvq8=
|
||||
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU=
|
||||
github.com/Masterminds/squirrel v1.5.4 h1:uUcX/aBc8O7Fg9kaISIUsHXdKuqehiXAMQTYX8afzqM=
|
||||
github.com/Masterminds/squirrel v1.5.4/go.mod h1:NNaOrjSoIDfDA40n7sr2tPNZRfjzjA400rg+riTZj10=
|
||||
github.com/alexbrainman/sspi v0.0.0-20210105120005-909beea2cc74 h1:Kk6a4nehpJ3UuJRqlA3JxYxBZEqCeOmATOvrbT4p9RA=
|
||||
github.com/alexbrainman/sspi v0.0.0-20210105120005-909beea2cc74/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4=
|
||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
|
||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
@@ -16,6 +20,10 @@ github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE
|
||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||
github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14=
|
||||
github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.5 h1:MNHlNMBDgEKD4TcKr36vQN68BA00aDfjIt3/bD50WnA=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.5/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||
github.com/go-ldap/ldap/v3 v3.4.6 h1:ert95MdbiG7aWo/oPYp9btL3KJlMPKnP58r09rI8T+A=
|
||||
github.com/go-ldap/ldap/v3 v3.4.6/go.mod h1:IGMQANNtxpsOzj7uUAMjpGBaOVTC4DYyIy8VsTdxmtc=
|
||||
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q=
|
||||
github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
|
||||
@@ -45,8 +53,8 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
|
||||
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
|
||||
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
|
||||
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4=
|
||||
github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
|
||||
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
@@ -147,11 +155,14 @@ github.com/rabbitmq/amqp091-go v1.9.0/go.mod h1:+jPrT9iY2eLjRaMSRHUhc3z14E/l85kv
|
||||
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
|
||||
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo=
|
||||
@@ -165,6 +176,7 @@ github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHo
|
||||
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ=
|
||||
github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74=
|
||||
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A=
|
||||
go.uber.org/goleak v1.2.0 h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk=
|
||||
go.uber.org/goleak v1.2.0/go.mod h1:XJYK+MuIchqpmGmUSAzotztawfKvYLUIgg7guXrwVUo=
|
||||
@@ -173,30 +185,59 @@ go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN8
|
||||
go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo=
|
||||
go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
|
||||
golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
|
||||
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
|
||||
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||
golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM=
|
||||
golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
|
||||
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.4.0 h1:zxkM55ReGkDlKSM+Fu41A+zmbZuaPVbGMzvvdUPznYQ=
|
||||
golang.org/x/sync v0.4.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
|
||||
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||
golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=
|
||||
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
|
||||
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20231009173412-8bfb1ae86b6c h1:jHkCUWkseRf+W+edG5hMzr/Uh1xkDREY4caybAq4dpY=
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package ldap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/go-ldap/ldap/v3"
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/conf"
|
||||
)
|
||||
|
||||
const (
|
||||
dialTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
type Repository struct {
|
||||
baseDn string
|
||||
conn *ldap.Conn
|
||||
}
|
||||
|
||||
func NewRepository(config *conf.Ldap) (*Repository, error) {
|
||||
if config == nil {
|
||||
return nil, errors.New("ldap config is not initialized")
|
||||
}
|
||||
|
||||
c, err := net.DialTimeout("tcp", config.Address, dialTimeout)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "net dial to %s", config.Address)
|
||||
}
|
||||
|
||||
conn := ldap.NewConn(c, false)
|
||||
conn.Start()
|
||||
|
||||
err = conn.Bind(config.Username, config.Password)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessagef(err, "ldap auth, username: %s", config.Username)
|
||||
}
|
||||
|
||||
return &Repository{
|
||||
conn: conn,
|
||||
baseDn: config.BaseDn,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r Repository) IsExist(ctx context.Context, dn string) (bool, error) {
|
||||
request := ldap.NewSearchRequest(
|
||||
dn,
|
||||
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
||||
"(objectClass=*)",
|
||||
[]string{"name"},
|
||||
nil,
|
||||
)
|
||||
result, err := r.conn.Search(request)
|
||||
if err != nil {
|
||||
return false, errors.WithMessage(err, "search by full dn")
|
||||
}
|
||||
return len(result.Entries) > 0, nil
|
||||
}
|
||||
|
||||
func (r Repository) DnByUserPrincipalName(ctx context.Context, principalName string) (string, error) {
|
||||
filter := fmt.Sprintf("(&(userPrincipalName=%s))", principalName)
|
||||
request := ldap.NewSearchRequest(
|
||||
r.baseDn, // The base dn to search
|
||||
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
||||
filter,
|
||||
[]string{"name"},
|
||||
nil,
|
||||
)
|
||||
result, err := r.conn.Search(request)
|
||||
if err != nil {
|
||||
return "", errors.WithMessagef(err, "search by '%s'", filter)
|
||||
}
|
||||
if len(result.Entries) == 0 {
|
||||
return "", errors.Errorf("not found entities by principalName: %s", principalName)
|
||||
}
|
||||
|
||||
return result.Entries[0].DN, nil
|
||||
}
|
||||
|
||||
func (r Repository) RemoveFromGroup(ctx context.Context, userDn string, groupDn string) error {
|
||||
modifyReq := ldap.NewModifyRequest(groupDn, nil)
|
||||
modifyReq.Delete("member", []string{userDn})
|
||||
err := r.conn.Modify(modifyReq)
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "modify entity by dn %s", groupDn)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r Repository) Close() error {
|
||||
return errors.WithMessage(r.conn.Close(), "close ldap connection")
|
||||
}
|
||||
+6
-5
@@ -220,13 +220,14 @@ func (u User) ChangeBlockStatus(ctx context.Context, userId int) (bool, error) {
|
||||
return blocked, nil
|
||||
}
|
||||
|
||||
func (u User) Block(ctx context.Context, userId int) error {
|
||||
func (u User) Block(ctx context.Context, userId int) (*entity.User, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.Block")
|
||||
|
||||
query := "update users set blocked = true where id = $1"
|
||||
_, err := u.db.Exec(ctx, query, userId)
|
||||
var user entity.User
|
||||
query := "update users set blocked = true where id = $1 returning *"
|
||||
err := u.db.SelectRow(ctx, &user, query, userId)
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "select row: %s", query)
|
||||
return nil, errors.WithMessagef(err, "select row: %s", query)
|
||||
}
|
||||
return nil
|
||||
return &user, nil
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package inactive_worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/integration-system/bgjob"
|
||||
"github.com/integration-system/isp-kit/bgjobx"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
QueueName = "block_inactive_user"
|
||||
)
|
||||
|
||||
func EnqueueSeedJob(ctx context.Context, client *bgjobx.Client) error {
|
||||
err := client.Enqueue(ctx, bgjob.EnqueueRequest{
|
||||
Id: "block_inactive_user",
|
||||
Queue: QueueName,
|
||||
Type: "block_inactive_user",
|
||||
})
|
||||
if err != nil && !errors.Is(err, bgjob.ErrJobAlreadyExist) {
|
||||
return errors.WithMessage(err, "enqueue job")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package inactive_worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/integration-system/bgjob"
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultRetryTimeout = 5 * time.Minute
|
||||
)
|
||||
|
||||
type AuditRepo interface {
|
||||
SaveAuditAsync(ctx context.Context, userId int64, message string, event string)
|
||||
}
|
||||
|
||||
type TokenRepo interface {
|
||||
LastAccessNotBlockedUsers(ctx context.Context) (map[int64]time.Time, error)
|
||||
}
|
||||
|
||||
type UserRepo interface {
|
||||
Block(ctx context.Context, userId int) (*entity.User, error)
|
||||
}
|
||||
|
||||
type LdapService interface {
|
||||
RemoveGroups(ctx context.Context, user entity.User) error
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
tokenRepo TokenRepo
|
||||
userRepo UserRepo
|
||||
auditRepo AuditRepo
|
||||
ldapService LdapService
|
||||
threshold time.Duration
|
||||
syncPeriod time.Duration
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func NewInactiveBlocker(
|
||||
tokensRepo TokenRepo,
|
||||
userRepo UserRepo,
|
||||
auditRepo AuditRepo,
|
||||
ldapService LdapService,
|
||||
config conf.BlockInactiveWorker,
|
||||
logger log.Logger,
|
||||
) Service {
|
||||
return Service{
|
||||
tokenRepo: tokensRepo,
|
||||
userRepo: userRepo,
|
||||
auditRepo: auditRepo,
|
||||
ldapService: ldapService,
|
||||
threshold: time.Duration(config.DaysThreshold) * 24 * time.Hour,
|
||||
syncPeriod: time.Minute * time.Duration(config.RunIntervalInMinutes),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (w Service) Handle(ctx context.Context, _ bgjob.Job) bgjob.Result {
|
||||
ctx = log.ToContext(ctx, log.String("worker", "inactiveBlocker"))
|
||||
w.logger.Debug(ctx, "begin work")
|
||||
err := w.do(ctx)
|
||||
if err != nil {
|
||||
return bgjob.Retry(defaultRetryTimeout, errors.WithMessage(err, "sync state with worker"))
|
||||
}
|
||||
w.logger.Debug(ctx, "end work")
|
||||
return bgjob.Reschedule(w.syncPeriod)
|
||||
}
|
||||
|
||||
func (w Service) 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))
|
||||
user, err := w.userRepo.Block(ctx, int(userId))
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "block user %d", userId)
|
||||
}
|
||||
|
||||
err = w.ldapService.RemoveGroups(ctx, *user)
|
||||
if err != nil {
|
||||
w.logger.Error(ctx, errors.WithMessage(err, "remove ldap groups"))
|
||||
}
|
||||
|
||||
w.auditRepo.SaveAuditAsync(ctx, userId, "Блокировка неактивной УЗ", entity.EventUserChanged)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
package ldap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
type Repo interface {
|
||||
IsExist(ctx context.Context, dn string) (bool, error)
|
||||
DnByUserPrincipalName(ctx context.Context, principalName string) (string, error)
|
||||
RemoveFromGroup(ctx context.Context, userDn string, groupDn string) error
|
||||
Close() error
|
||||
}
|
||||
|
||||
type RoleRepo interface {
|
||||
All(ctx context.Context) ([]entity.Role, error)
|
||||
}
|
||||
|
||||
type UserRoleRepo interface {
|
||||
GetRolesByUserIds(ctx context.Context, identity []int) ([]entity.UserRole, error)
|
||||
UpdateUserRoleLinks(ctx context.Context, id int, roleIds []int) error
|
||||
}
|
||||
|
||||
type RepoSupplier func(config *conf.Ldap) (Repo, error)
|
||||
|
||||
type Service struct {
|
||||
config *conf.Ldap
|
||||
repoSuppler RepoSupplier
|
||||
userRoleRepo UserRoleRepo
|
||||
roleRepo RoleRepo
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func NewService(
|
||||
config *conf.Ldap,
|
||||
repoSuppler RepoSupplier,
|
||||
userRoleRepo UserRoleRepo,
|
||||
roleRepo RoleRepo,
|
||||
logger log.Logger,
|
||||
) Service {
|
||||
return Service{
|
||||
config: config,
|
||||
repoSuppler: repoSuppler,
|
||||
userRoleRepo: userRoleRepo,
|
||||
roleRepo: roleRepo,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Service) RemoveGroups(ctx context.Context, user entity.User) error {
|
||||
ctx = log.ToContext(ctx, log.String("process", "ldap"), log.Int64("userId", user.Id))
|
||||
|
||||
ldapRepo, err := s.repoSuppler(s.config)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "init ldap repository")
|
||||
}
|
||||
defer ldapRepo.Close()
|
||||
|
||||
if user.SudirUserId == nil || *user.SudirUserId == "" {
|
||||
s.logger.Info(ctx, "user has not sudir user id, skip")
|
||||
return nil
|
||||
}
|
||||
|
||||
userDn, err := ldapRepo.DnByUserPrincipalName(ctx, *user.SudirUserId)
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "get user dn by principal name %s", *user.SudirUserId)
|
||||
}
|
||||
|
||||
userRoles, err := s.userRoleRepo.GetRolesByUserIds(ctx, []int{int(user.Id)})
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "ger roles by user ids")
|
||||
}
|
||||
|
||||
allRoles, err := s.roleRepo.All(ctx)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "get all roles")
|
||||
}
|
||||
rolesById := make(map[int]entity.Role)
|
||||
for _, role := range allRoles {
|
||||
rolesById[role.Id] = role
|
||||
}
|
||||
|
||||
newUserRoles := make([]int, 0)
|
||||
for _, role := range userRoles {
|
||||
keepRole, err := s.handleRole(ctx, role.RoleId, rolesById, userDn, ldapRepo)
|
||||
if err != nil {
|
||||
s.logger.Error(ctx, errors.WithMessage(err, "handle role"))
|
||||
continue
|
||||
}
|
||||
if keepRole {
|
||||
newUserRoles = append(newUserRoles, role.RoleId)
|
||||
}
|
||||
}
|
||||
|
||||
err = s.userRoleRepo.UpdateUserRoleLinks(ctx, int(user.Id), newUserRoles)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "update user role links")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Service) handleRole(
|
||||
ctx context.Context,
|
||||
roleId int,
|
||||
rolesById map[int]entity.Role,
|
||||
userDn string,
|
||||
ldapRepo Repo,
|
||||
) (bool, error) {
|
||||
role, ok := rolesById[roleId]
|
||||
if !ok {
|
||||
return false, errors.Errorf("role with id %d not found", roleId)
|
||||
}
|
||||
|
||||
if role.ExternalGroup == "" {
|
||||
s.logger.Info(ctx, "role has not external group mapping, skip", log.Int("roleId", roleId))
|
||||
return true, nil
|
||||
}
|
||||
|
||||
exist, err := ldapRepo.IsExist(ctx, role.ExternalGroup)
|
||||
if err != nil {
|
||||
return false, errors.WithMessagef(err, "check dn %s is exist", role.ExternalGroup)
|
||||
}
|
||||
if !exist {
|
||||
s.logger.Info(ctx, "role doesn't exist in ldap, skip", log.Int("roleId", roleId))
|
||||
return true, nil
|
||||
}
|
||||
|
||||
err = ldapRepo.RemoveFromGroup(ctx, userDn, role.ExternalGroup)
|
||||
if err != nil {
|
||||
return false, errors.WithMessagef(err, "remove %s from group %s", userDn, role.ExternalGroup)
|
||||
}
|
||||
|
||||
s.logger.Info(ctx, fmt.Sprintf("user %s removed from group %s", userDn, role.ExternalGroup))
|
||||
|
||||
return false, nil
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
type AuditRepo interface {
|
||||
SaveAuditAsync(ctx context.Context, userId int64, message string, event 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, "Блокировка неактивной УЗ", entity.EventUserChanged)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
+1
-1
@@ -65,7 +65,7 @@ func (t *AuditSuite) SetupTest() {
|
||||
},
|
||||
}
|
||||
cfg := assembly.NewLocator(testInstance.Logger(), httpcli.New(), t.db).
|
||||
Config(context.Background(), remote)
|
||||
Config(context.Background(), emptyLdap, remote)
|
||||
|
||||
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
|
||||
t.grpcCli = apiCli
|
||||
|
||||
+13
-14
@@ -17,7 +17,6 @@ import (
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/repository"
|
||||
"msp-admin-service/tests"
|
||||
|
||||
"github.com/integration-system/isp-kit/dbx"
|
||||
"github.com/integration-system/isp-kit/grpc/client"
|
||||
@@ -66,7 +65,7 @@ func (s *AuthTestSuite) SetupTest() {
|
||||
},
|
||||
}
|
||||
cfg := assembly.NewLocator(testInstance.Logger(), s.httpCli, s.db).
|
||||
Config(context.Background(), remote)
|
||||
Config(context.Background(), emptyLdap, remote)
|
||||
|
||||
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
|
||||
s.grpcCli = apiCli
|
||||
@@ -78,7 +77,7 @@ func (s *AuthTestSuite) SetupTest() {
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestLoginHappyPath() {
|
||||
id := tests.InsertUser(s.db, entity.User{
|
||||
id := InsertUser(s.db, entity.User{
|
||||
FirstName: "John",
|
||||
LastName: "Doe",
|
||||
Email: "a@a.ru",
|
||||
@@ -95,7 +94,7 @@ func (s *AuthTestSuite) TestLoginHappyPath() {
|
||||
Do(context.Background())
|
||||
s.Require().NoError(err)
|
||||
|
||||
tokenInfo := tests.SelectTokenEntityByToken(s.db, response.Token)
|
||||
tokenInfo := SelectTokenEntityByToken(s.db, response.Token)
|
||||
s.Require().Equal(tokenInfo.UserId, id)
|
||||
}
|
||||
|
||||
@@ -113,7 +112,7 @@ func (s *AuthTestSuite) TestLoginNotFound() {
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestBlockedUser() {
|
||||
tests.InsertUser(s.db, entity.User{
|
||||
InsertUser(s.db, entity.User{
|
||||
FirstName: "John",
|
||||
LastName: "Doe",
|
||||
Email: "a@a.ru",
|
||||
@@ -134,7 +133,7 @@ func (s *AuthTestSuite) TestBlockedUser() {
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestLoginWrongPassword() {
|
||||
tests.InsertUser(s.db, entity.User{
|
||||
InsertUser(s.db, entity.User{
|
||||
FirstName: "John",
|
||||
LastName: "Doe",
|
||||
Email: "a@a.ru",
|
||||
@@ -167,7 +166,7 @@ func (s *AuthTestSuite) TestSudirLoginHappyPath() {
|
||||
s.db.Must().SelectRow(&user, "select id, email from users where sudir_user_id = $1", "sudirUser1")
|
||||
s.Require().Equal("sudir@email.ru", user.Email)
|
||||
|
||||
tokenInfo := tests.SelectTokenEntityByToken(s.db, response.Token)
|
||||
tokenInfo := SelectTokenEntityByToken(s.db, response.Token)
|
||||
s.Require().Equal(tokenInfo.UserId, user.Id)
|
||||
}
|
||||
|
||||
@@ -203,8 +202,8 @@ func (s *AuthTestSuite) initMockSudir() (*httptest.Server, string) {
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) Test_Logout_HappyPath() {
|
||||
userId := tests.InsertUser(s.db, entity.User{Email: "suslik@mail.ru"})
|
||||
tests.InsertTokenEntity(s.db, entity.Token{
|
||||
userId := InsertUser(s.db, entity.User{Email: "suslik@mail.ru"})
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "token-841297641213",
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusAllowed,
|
||||
@@ -216,7 +215,7 @@ func (s *AuthTestSuite) Test_Logout_HappyPath() {
|
||||
Do(context.Background())
|
||||
s.Require().NoError(err)
|
||||
|
||||
tokenInfo := tests.SelectTokenEntityByToken(s.db, "token-841297641213")
|
||||
tokenInfo := SelectTokenEntityByToken(s.db, "token-841297641213")
|
||||
s.Require().Equal(entity.TokenStatusRevoked, tokenInfo.Status)
|
||||
}
|
||||
|
||||
@@ -235,8 +234,8 @@ func (s *AuthTestSuite) Test_Logout_NotFound() {
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) Test_Logout_AlreadyRevoke() {
|
||||
userId := tests.InsertUser(s.db, entity.User{Email: "suslik@mail.ru"})
|
||||
tests.InsertTokenEntity(s.db, entity.Token{
|
||||
userId := InsertUser(s.db, entity.User{Email: "suslik@mail.ru"})
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "token-148623719462",
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusRevoked,
|
||||
@@ -248,12 +247,12 @@ func (s *AuthTestSuite) Test_Logout_AlreadyRevoke() {
|
||||
Do(context.Background())
|
||||
s.Require().NoError(err)
|
||||
|
||||
tokenInfo := tests.SelectTokenEntityByToken(s.db, "token-148623719462")
|
||||
tokenInfo := SelectTokenEntityByToken(s.db, "token-148623719462")
|
||||
s.Require().Equal(entity.TokenStatusRevoked, tokenInfo.Status)
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestBruteForceLogin() {
|
||||
_ = tests.InsertUser(s.db, entity.User{
|
||||
_ = InsertUser(s.db, entity.User{
|
||||
FirstName: "John",
|
||||
LastName: "Doe",
|
||||
Email: "a@a.ru",
|
||||
|
||||
@@ -39,7 +39,7 @@ func (s *CustomizationTestSuite) SetupTest() {
|
||||
ExpireSec: 0,
|
||||
}
|
||||
cfg := assembly.NewLocator(testInstance.Logger(), nil, s.db).
|
||||
Config(context.Background(), remote)
|
||||
Config(context.Background(), emptyLdap, remote)
|
||||
|
||||
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
|
||||
s.grpcCli = apiCli
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package tests
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"github.com/integration-system/isp-kit/db/query"
|
||||
+21
-10
@@ -5,6 +5,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/integration-system/isp-kit/bgjobx"
|
||||
"github.com/integration-system/isp-kit/dbx"
|
||||
"github.com/integration-system/isp-kit/test"
|
||||
"github.com/integration-system/isp-kit/test/dbt"
|
||||
@@ -12,7 +13,7 @@ import (
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/repository"
|
||||
"msp-admin-service/tests"
|
||||
"msp-admin-service/service/inactive_worker"
|
||||
)
|
||||
|
||||
func TestInactiveWorker(t *testing.T) {
|
||||
@@ -21,16 +22,16 @@ func TestInactiveWorker(t *testing.T) {
|
||||
test, require := test.New(t)
|
||||
db := dbt.New(test, dbx.WithMigration("../migrations"))
|
||||
|
||||
userId := tests.InsertUser(db, entity.User{Email: "a@test"})
|
||||
tests.InsertUser(db, entity.User{Email: "b@test"})
|
||||
tests.InsertTokenEntity(db, entity.Token{
|
||||
userId := InsertUser(db, entity.User{Email: "a@test"})
|
||||
InsertUser(db, entity.User{Email: "b@test"})
|
||||
InsertTokenEntity(db, entity.Token{
|
||||
Id: 0,
|
||||
Token: "123",
|
||||
UserId: userId,
|
||||
Status: entity.TokenStatusAllowed,
|
||||
CreatedAt: time.Now().UTC().Add(-48 * time.Hour),
|
||||
})
|
||||
tests.InsertTokenEntity(db, entity.Token{
|
||||
InsertTokenEntity(db, entity.Token{
|
||||
Id: 0,
|
||||
Token: "234",
|
||||
UserId: userId,
|
||||
@@ -38,11 +39,21 @@ func TestInactiveWorker(t *testing.T) {
|
||||
CreatedAt: time.Now().UTC().Add(-5 * 24 * time.Hour),
|
||||
})
|
||||
|
||||
worker := assembly.NewLocator(test.Logger(), nil, db).
|
||||
Config(context.Background(), conf.Remote{BlockInactiveWorker: conf.BlockInactiveWorker{DaysThreshold: 1}}).
|
||||
InactiveBlocker
|
||||
worker.Do(context.Background())
|
||||
time.Sleep(1 * time.Second)
|
||||
config := assembly.NewLocator(test.Logger(), nil, db).
|
||||
Config(context.Background(), emptyLdap, conf.Remote{
|
||||
BlockInactiveWorker: conf.BlockInactiveWorker{
|
||||
DaysThreshold: 1,
|
||||
RunIntervalInMinutes: 60,
|
||||
},
|
||||
})
|
||||
bgjobCli := bgjobx.NewClient(db, test.Logger())
|
||||
assembly.JobPollInterval = 1 * time.Second
|
||||
err := bgjobCli.Upgrade(context.Background(), config.BgJobCfg)
|
||||
require.NoError(err)
|
||||
err = inactive_worker.EnqueueSeedJob(context.Background(), bgjobCli)
|
||||
require.NoError(err)
|
||||
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
user, err := repository.NewUser(db).GetUserById(context.Background(), userId)
|
||||
require.NoError(err)
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/service/ldap"
|
||||
)
|
||||
|
||||
type mockLdap struct {
|
||||
}
|
||||
|
||||
func (m mockLdap) IsExist(ctx context.Context, dn string) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (m mockLdap) DnByUserPrincipalName(ctx context.Context, principalName string) (string, error) {
|
||||
return principalName, nil
|
||||
}
|
||||
|
||||
func (m mockLdap) RemoveFromGroup(ctx context.Context, userDn string, groupDn string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m mockLdap) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
var (
|
||||
//nolint:gochecknoglobals
|
||||
emptyLdap = ldap.RepoSupplier(func(config *conf.Ldap) (ldap.Repo, error) {
|
||||
return mockLdap{}, nil
|
||||
})
|
||||
)
|
||||
@@ -17,7 +17,6 @@ import (
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/tests"
|
||||
)
|
||||
|
||||
func TestSecureSuite(t *testing.T) {
|
||||
@@ -41,7 +40,7 @@ func (s *SecureSuite) SetupTest() {
|
||||
ExpireSec: 3600,
|
||||
}
|
||||
cfg := assembly.NewLocator(s.test.Logger(), httpCli, s.db).
|
||||
Config(context.Background(), remote)
|
||||
Config(context.Background(), emptyLdap, remote)
|
||||
|
||||
server, apiCli := grpct.TestServer(s.test, cfg.Handler)
|
||||
s.test.T().Cleanup(func() {
|
||||
@@ -51,7 +50,7 @@ func (s *SecureSuite) SetupTest() {
|
||||
}
|
||||
|
||||
func (s *SecureSuite) Test_Authenticate_HappyPath() {
|
||||
tests.InsertTokenEntity(s.db, entity.Token{
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "happy_path",
|
||||
UserId: 1,
|
||||
Status: entity.TokenStatusAllowed,
|
||||
@@ -75,7 +74,7 @@ func (s *SecureSuite) Test_Authenticate_HappyPath() {
|
||||
}
|
||||
|
||||
func (s *SecureSuite) Test_Authenticate_StatusRevoked() {
|
||||
tests.InsertTokenEntity(s.db, entity.Token{
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "revoked",
|
||||
UserId: 1,
|
||||
Status: entity.TokenStatusRevoked,
|
||||
@@ -99,7 +98,7 @@ func (s *SecureSuite) Test_Authenticate_StatusRevoked() {
|
||||
}
|
||||
|
||||
func (s *SecureSuite) Test_Authenticate_Expired() {
|
||||
tests.InsertTokenEntity(s.db, entity.Token{
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: "expired",
|
||||
UserId: 1,
|
||||
Status: entity.TokenStatusAllowed,
|
||||
|
||||
+24
-25
@@ -22,7 +22,6 @@ import (
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/repository"
|
||||
"msp-admin-service/service"
|
||||
"msp-admin-service/tests"
|
||||
)
|
||||
|
||||
type tokenService interface {
|
||||
@@ -53,7 +52,7 @@ func (s *UserTestSuite) SetupTest() {
|
||||
ExpireSec: 0,
|
||||
}
|
||||
cfg := assembly.NewLocator(testInstance.Logger(), s.httpCli, s.db).
|
||||
Config(context.Background(), remote)
|
||||
Config(context.Background(), emptyLdap, remote)
|
||||
|
||||
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
|
||||
s.grpcCli = apiCli
|
||||
@@ -67,19 +66,19 @@ func (s *UserTestSuite) SetupTest() {
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestGetProfileHappyPath() {
|
||||
id := tests.InsertUser(s.db, entity.User{
|
||||
id := InsertUser(s.db, entity.User{
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
Email: "a@a.ru",
|
||||
Password: "password",
|
||||
})
|
||||
|
||||
roleId, err := tests.InsertRole(s.db, entity.Role{
|
||||
roleId, err := InsertRole(s.db, entity.Role{
|
||||
Name: "admin",
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
err = tests.InsertUserRole(s.db, entity.UserRole{
|
||||
err = InsertUserRole(s.db, entity.UserRole{
|
||||
UserId: int(id),
|
||||
RoleId: int(roleId),
|
||||
})
|
||||
@@ -103,7 +102,7 @@ func (s *UserTestSuite) TestGetProfileHappyPath() {
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestGetProfileNotFound() {
|
||||
id := tests.InsertUser(s.db, entity.User{
|
||||
id := InsertUser(s.db, entity.User{
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
Email: "a@b.ru",
|
||||
@@ -120,7 +119,7 @@ func (s *UserTestSuite) TestGetProfileNotFound() {
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestGetProfileSudir() {
|
||||
id, err := tests.InsertSudirUser(s.db, entity.SudirUser{
|
||||
id, err := InsertSudirUser(s.db, entity.SudirUser{
|
||||
SudirUserId: "sudirUser1",
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
@@ -128,12 +127,12 @@ func (s *UserTestSuite) TestGetProfileSudir() {
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
roleId, err := tests.InsertRole(s.db, entity.Role{
|
||||
roleId, err := InsertRole(s.db, entity.Role{
|
||||
Name: "admin",
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
err = tests.InsertUserRole(s.db, entity.UserRole{
|
||||
err = InsertUserRole(s.db, entity.UserRole{
|
||||
UserId: int(id),
|
||||
RoleId: int(roleId),
|
||||
})
|
||||
@@ -158,10 +157,10 @@ func (s *UserTestSuite) TestGetProfileSudir() {
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestGetUsers() {
|
||||
tests.InsertUser(s.db, entity.User{Email: "a1@a.ru"})
|
||||
tests.InsertUser(s.db, entity.User{Email: "b1@a.ru"})
|
||||
tests.InsertUser(s.db, entity.User{Email: "a1@b.ru"})
|
||||
tests.InsertUser(s.db, entity.User{Email: "a1@c.ru"})
|
||||
InsertUser(s.db, entity.User{Email: "a1@a.ru"})
|
||||
InsertUser(s.db, entity.User{Email: "b1@a.ru"})
|
||||
InsertUser(s.db, entity.User{Email: "a1@b.ru"})
|
||||
InsertUser(s.db, entity.User{Email: "a1@c.ru"})
|
||||
|
||||
response := domain.UsersResponse{}
|
||||
err := s.grpcCli.Invoke("admin/user/get_users").
|
||||
@@ -180,7 +179,7 @@ func (s *UserTestSuite) TestGetUsers() {
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestCreateUserHappyPath() {
|
||||
admin := tests.InsertUser(s.db, entity.User{Email: "admin@a.ru"})
|
||||
admin := InsertUser(s.db, entity.User{Email: "admin@a.ru"})
|
||||
|
||||
preCount := 0
|
||||
s.db.Must().SelectRow(&preCount, "select count(*) from users")
|
||||
@@ -206,7 +205,7 @@ func (s *UserTestSuite) TestCreateUserHappyPath() {
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestCreateUserAlreadyExist() {
|
||||
id := tests.InsertUser(s.db, entity.User{Email: "exists@a.ru"})
|
||||
id := InsertUser(s.db, entity.User{Email: "exists@a.ru"})
|
||||
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/create_user").
|
||||
@@ -225,7 +224,7 @@ func (s *UserTestSuite) TestCreateUserAlreadyExist() {
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestUpdateUserHappyPath() {
|
||||
id := tests.InsertUser(s.db, entity.User{Email: "update@a.ru", Password: "password"})
|
||||
id := InsertUser(s.db, entity.User{Email: "update@a.ru", Password: "password"})
|
||||
req := domain.UpdateUserRequest{
|
||||
Id: id,
|
||||
FirstName: "name",
|
||||
@@ -250,7 +249,7 @@ func (s *AuthTestSuite) TestUpdateUserHappyPath() {
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestUpdateSudirUserHappyPath() {
|
||||
id, err := tests.InsertSudirUser(s.db, entity.SudirUser{Email: "sudir@a.ru"})
|
||||
id, err := InsertSudirUser(s.db, entity.SudirUser{Email: "sudir@a.ru"})
|
||||
s.Require().NoError(err)
|
||||
req := domain.UpdateUserRequest{
|
||||
Id: id,
|
||||
@@ -276,8 +275,8 @@ func (s *AuthTestSuite) TestUpdateSudirUserHappyPath() {
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestUpdateUserAlreadyExist() {
|
||||
admin := tests.InsertUser(s.db, entity.User{Email: "a_exists@a.ru", Password: "password"})
|
||||
id := tests.InsertUser(s.db, entity.User{Email: "b_exists@b.ru", Password: "password"})
|
||||
admin := InsertUser(s.db, entity.User{Email: "a_exists@a.ru", Password: "password"})
|
||||
id := InsertUser(s.db, entity.User{Email: "b_exists@b.ru", Password: "password"})
|
||||
req := domain.UpdateUserRequest{
|
||||
Id: id,
|
||||
FirstName: "name",
|
||||
@@ -296,10 +295,10 @@ func (s *AuthTestSuite) TestUpdateUserAlreadyExist() {
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestDeleteUsers() {
|
||||
admin := tests.InsertUser(s.db, entity.User{Email: "a_del@a.ru"})
|
||||
tests.InsertUser(s.db, entity.User{Email: "b_del@a.ru"})
|
||||
tests.InsertUser(s.db, entity.User{Email: "a_del@b.ru"})
|
||||
tests.InsertUser(s.db, entity.User{Email: "a_del@c.ru"})
|
||||
admin := InsertUser(s.db, entity.User{Email: "a_del@a.ru"})
|
||||
InsertUser(s.db, entity.User{Email: "b_del@a.ru"})
|
||||
InsertUser(s.db, entity.User{Email: "a_del@b.ru"})
|
||||
InsertUser(s.db, entity.User{Email: "a_del@c.ru"})
|
||||
|
||||
response := domain.DeleteResponse{}
|
||||
err := s.grpcCli.
|
||||
@@ -314,7 +313,7 @@ func (s *UserTestSuite) TestDeleteUsers() {
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestBlockUser() {
|
||||
id := tests.InsertUser(s.db, entity.User{
|
||||
id := InsertUser(s.db, entity.User{
|
||||
FirstName: "John",
|
||||
LastName: "Doe",
|
||||
Email: "a_block@a.ru",
|
||||
@@ -322,7 +321,7 @@ func (s *UserTestSuite) TestBlockUser() {
|
||||
Blocked: false,
|
||||
})
|
||||
token := uuid.New().String()
|
||||
tests.InsertTokenEntity(s.db, entity.Token{
|
||||
InsertTokenEntity(s.db, entity.Token{
|
||||
Token: token,
|
||||
UserId: id,
|
||||
Status: entity.TokenStatusAllowed,
|
||||
|
||||
Reference in new issue
Block a user