MSP-5083 fix blocking user

This commit is contained in:
yakovlevav committed 2025-07-25 10:33:53 +03:00
1 parent 40b37f8900
commit 558682da1e
10 files changed
+138 -92

No files matched your search

-1
View File
@@ -115,7 +115,6 @@ func (l Locator) Config(
) )
inactiveBlocker := inactive_worker.NewInactiveBlocker( inactiveBlocker := inactive_worker.NewInactiveBlocker(
tokenRepo,
userRepo, userRepo,
auditService, auditService,
userRoleRepo, userRoleRepo,
+11 -10
View File
@@ -3,16 +3,17 @@ package entity
import "time" import "time"
type User struct { type User struct {
SudirUserId *string SudirUserId *string
Id int64 Id int64
FirstName string FirstName string
LastName string LastName string
Description string Description string
Email string Email string
Password string Password string
Blocked bool Blocked bool
UpdatedAt time.Time LastActiveAt time.Time
CreatedAt time.Time UpdatedAt time.Time
CreatedAt time.Time
} }
type SudirUser struct { type SudirUser struct {
@@ -0,0 +1,7 @@
-- +goose Up
ALTER TABLE users
ADD COLUMN last_active_at TIMESTAMP DEFAULT (now() at time zone 'utc') NOT NULL;
-- +goose Down
ALTER TABLE users
DROP COLUMN last_active_at;
+1 -24
View File
@@ -3,9 +3,9 @@ package repository
import ( import (
"context" "context"
"database/sql" "database/sql"
"github.com/Masterminds/squirrel"
"time" "time"
"github.com/Masterminds/squirrel"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/txix-open/isp-kit/db" "github.com/txix-open/isp-kit/db"
"github.com/txix-open/isp-kit/db/query" "github.com/txix-open/isp-kit/db/query"
@@ -139,29 +139,6 @@ func (r Token) UpdateStatusByUserId(ctx context.Context, userId int, status stri
return nil return nil
} }
func (r Token) LastAccessNotBlockedUsers(ctx context.Context) (map[int64]time.Time, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.LastAccessNotBlockedUsers")
query := `
select t.user_id, max(t.created_at) as created_at from tokens t
join users u on t.user_id = u.id
where u.blocked = false
group by t.user_id
`
tokens := make([]entity.Token, 0)
err := r.db.Select(ctx, &tokens, query)
if err != nil {
return nil, errors.WithMessagef(err, "select query: %s", query)
}
result := make(map[int64]time.Time, 0)
for _, token := range tokens {
result[token.UserId] = token.CreatedAt
}
return result, nil
}
func (r Token) LastAccessByUserIds(ctx context.Context, userIds []int) (map[int64]*time.Time, error) { func (r Token) LastAccessByUserIds(ctx context.Context, userIds []int) (map[int64]*time.Time, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "Token.LastAccessNotBlockedUsers") ctx = sql_metrics.OperationLabelToContext(ctx, "Token.LastAccessNotBlockedUsers")
+38
View File
@@ -3,6 +3,7 @@ package repository
import ( import (
"context" "context"
"database/sql" "database/sql"
"time"
"github.com/Masterminds/squirrel" "github.com/Masterminds/squirrel"
"github.com/pkg/errors" "github.com/pkg/errors"
@@ -233,6 +234,32 @@ func (u User) Block(ctx context.Context, userId int) (*entity.User, error) {
return &user, nil return &user, nil
} }
func (u User) LastAccessNotBlockedUsers(ctx context.Context) (map[int64]time.Time, error) {
ctx = sql_metrics.OperationLabelToContext(ctx, "User.LastAccessNotBlockedUsers")
q, args, err := query.New().
Select("id, last_active_at").
From("users").
Where(squirrel.Eq{"blocked": false}).
ToSql()
if err != nil {
return nil, errors.WithMessage(err, "build query")
}
users := make([]entity.User, 0)
err = u.db.Select(ctx, &users, q, args...)
if err != nil {
return nil, errors.WithMessagef(err, "select query: %s", q)
}
result := make(map[int64]time.Time, 0)
for _, user := range users {
result[user.Id] = user.LastActiveAt
}
return result, nil
}
func (u User) ChangePassword(ctx context.Context, userId int64, newPassword string) error { func (u User) ChangePassword(ctx context.Context, userId int64, newPassword string) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "User.ChangePassword") ctx = sql_metrics.OperationLabelToContext(ctx, "User.ChangePassword")
@@ -252,3 +279,14 @@ func (u User) ChangePassword(ctx context.Context, userId int64, newPassword stri
return nil return nil
} }
func (u User) UpdateLastActiveAt(ctx context.Context, userId int64, lastActiveAt time.Time) error {
ctx = sql_metrics.OperationLabelToContext(ctx, "User.UpdateLastActiveAt")
q := "update users set last_active_at = $1 where id = $2"
_, err := u.db.Exec(ctx, q, lastActiveAt, userId)
if err != nil {
return errors.WithMessagef(err, "user.repo.UpdateLastActiveAt: exec query: %s", q)
}
return nil
}
+30 -5
View File
@@ -31,6 +31,7 @@ type userRepository interface {
GetUserByEmail(ctx context.Context, email string) (*entity.User, error) GetUserByEmail(ctx context.Context, email string) (*entity.User, error)
UpsertBySudirUserId(ctx context.Context, user entity.User) (*entity.User, error) UpsertBySudirUserId(ctx context.Context, user entity.User) (*entity.User, error)
UpdateUser(ctx context.Context, id int64, user entity.UpdateUser) (*entity.User, error) UpdateUser(ctx context.Context, id int64, user entity.UpdateUser) (*entity.User, error)
UpdateLastActiveAt(ctx context.Context, userId int64, lastActiveAt time.Time) error
} }
type tokenService interface { type tokenService interface {
@@ -118,6 +119,12 @@ func (a Auth) Login(ctx context.Context, request domain.LoginRequest) (*domain.L
return errors.WithMessage(err, "generate token") return errors.WithMessage(err, "generate token")
} }
lastActiveAt := time.Now().UTC()
err = tx.UpdateLastActiveAt(ctx, user.Id, lastActiveAt)
if err != nil {
return errors.WithMessage(err, "update user last_active_at")
}
a.auditService.SaveAuditAsync(ctx, user.Id, "Успешный вход через форму входа", entity.EventSuccessLogin) a.auditService.SaveAuditAsync(ctx, user.Id, "Успешный вход через форму входа", entity.EventSuccessLogin)
return nil return nil
@@ -185,6 +192,12 @@ func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirReque
return errors.WithMessage(err, "generate token") return errors.WithMessage(err, "generate token")
} }
lastActiveAt := time.Now().UTC()
err = tx.UpdateLastActiveAt(ctx, user.Id, lastActiveAt)
if err != nil {
return errors.WithMessage(err, "update user last_active_at")
}
return nil return nil
}) })
if err != nil { if err != nil {
@@ -201,12 +214,24 @@ func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirReque
} }
func (a Auth) Logout(ctx context.Context, adminId int64) error { func (a Auth) Logout(ctx context.Context, adminId int64) error {
err := a.tokenService.RevokeAllByUserId(ctx, adminId) err := a.txRunner.AuthTransaction(ctx, func(ctx context.Context, tx AuthTransaction) error {
if err != nil { err := a.tokenService.RevokeAllByUserId(ctx, adminId)
return errors.WithMessage(err, "revoke all tokens by user id") if err != nil {
} return errors.WithMessage(err, "revoke all tokens by user id")
}
a.auditService.SaveAuditAsync(ctx, adminId, "Выход", entity.EventSuccessLogout) lastActiveAt := time.Now().UTC()
err = tx.UpdateLastActiveAt(ctx, adminId, lastActiveAt)
if err != nil {
return errors.WithMessage(err, "update user last_active_at")
}
a.auditService.SaveAuditAsync(ctx, adminId, "Выход", entity.EventSuccessLogout)
return nil
})
if err != nil {
return errors.WithMessage(err, "auth transaction")
}
return nil return nil
} }
+2 -8
View File
@@ -19,11 +19,8 @@ type AuditRepo interface {
SaveAuditAsync(ctx context.Context, userId int64, message string, event string) 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 { type UserRepo interface {
LastAccessNotBlockedUsers(ctx context.Context) (map[int64]time.Time, error)
Block(ctx context.Context, userId int) (*entity.User, error) Block(ctx context.Context, userId int) (*entity.User, error)
} }
@@ -36,7 +33,6 @@ type UserRoleRepo interface {
} }
type Service struct { type Service struct {
tokenRepo TokenRepo
userRepo UserRepo userRepo UserRepo
auditRepo AuditRepo auditRepo AuditRepo
userRoleRepo UserRoleRepo userRoleRepo UserRoleRepo
@@ -47,7 +43,6 @@ type Service struct {
} }
func NewInactiveBlocker( func NewInactiveBlocker(
tokensRepo TokenRepo,
userRepo UserRepo, userRepo UserRepo,
auditRepo AuditRepo, auditRepo AuditRepo,
userRoleRepo UserRoleRepo, userRoleRepo UserRoleRepo,
@@ -56,7 +51,6 @@ func NewInactiveBlocker(
logger log.Logger, logger log.Logger,
) Service { ) Service {
return Service{ return Service{
tokenRepo: tokensRepo,
userRepo: userRepo, userRepo: userRepo,
auditRepo: auditRepo, auditRepo: auditRepo,
userRoleRepo: userRoleRepo, userRoleRepo: userRoleRepo,
@@ -79,7 +73,7 @@ func (w Service) Handle(ctx context.Context, _ bgjob.Job) bgjob.Result {
} }
func (w Service) do(ctx context.Context) error { func (w Service) do(ctx context.Context) error {
lastAccess, err := w.tokenRepo.LastAccessNotBlockedUsers(ctx) lastAccess, err := w.userRepo.LastAccessNotBlockedUsers(ctx)
if err != nil { if err != nil {
return errors.WithMessage(err, "get last access times") return errors.WithMessage(err, "get last access times")
} }
+44 -25
View File
@@ -34,6 +34,7 @@ type UserRepo interface {
Insert(ctx context.Context, user entity.User) (int, error) Insert(ctx context.Context, user entity.User) (int, error)
ChangeBlockStatus(ctx context.Context, userId int) (bool, error) ChangeBlockStatus(ctx context.Context, userId int) (bool, error)
ChangePassword(ctx context.Context, userId int64, newPassword string) error ChangePassword(ctx context.Context, userId int64, newPassword string) error
UpdateLastActiveAt(ctx context.Context, userId int64, lastActiveAt time.Time) error
} }
type TokenRepo interface { type TokenRepo interface {
@@ -371,7 +372,7 @@ func (u User) Block(ctx context.Context, adminId int64, userId int) error {
} }
if blocked { if blocked {
err := tx.UpdateStatusByUserId(ctx, userId, entity.TokenStatusRevoked) err = tx.UpdateStatusByUserId(ctx, userId, entity.TokenStatusRevoked)
if err != nil { if err != nil {
return errors.WithMessage(err, "revoke tokens") return errors.WithMessage(err, "revoke tokens")
} }
@@ -379,6 +380,11 @@ func (u User) Block(ctx context.Context, adminId int64, userId int) error {
if !blocked { if !blocked {
userBlocked = "разблокировка" userBlocked = "разблокировка"
lastActiveAt := time.Now().UTC()
err = tx.UpdateLastActiveAt(ctx, int64(userId), lastActiveAt)
if err != nil {
return errors.WithMessage(err, "update user last_active_at")
}
} }
return nil return nil
@@ -444,33 +450,46 @@ func diffToString(a map[string]any, b map[string]any) string {
} }
func (u User) ChangePassword(ctx context.Context, adminId int64, oldPassword string, newPassword string) error { func (u User) ChangePassword(ctx context.Context, adminId int64, oldPassword string, newPassword string) error {
admin, err := u.userRepo.GetUserById(ctx, adminId) err := u.txRunner.UserTransaction(ctx, func(ctx context.Context, tx UserTransaction) error {
admin, err := tx.GetUserById(ctx, adminId)
if err != nil {
return errors.WithMessage(err, "user.service.ChangePassword: get user by id")
}
if err = bcrypt.CompareHashAndPassword([]byte(admin.Password), []byte(oldPassword)); err != nil {
u.auditService.SaveAuditAsync(ctx, adminId, "Указан неверный старый пароль", entity.EventErrorPasswordChange)
return domain.ErrInvalidPassword
}
encryptedPassword, err := u.cryptPassword(newPassword)
if err != nil {
return errors.WithMessage(err, "user.service.ChangePassword: crypt new password")
}
err = tx.ChangePassword(ctx, adminId, encryptedPassword)
if err != nil {
return errors.WithMessage(err, "user.service.ChangePassword: change password ")
}
err = u.tokenService.RevokeAllByUserId(ctx, adminId)
if err != nil {
return errors.WithMessage(err, "revoke all tokens by user id")
}
lastActiveAt := time.Now().UTC()
err = tx.UpdateLastActiveAt(ctx, adminId, lastActiveAt)
if err != nil {
return errors.WithMessage(err, "update user last_active_at")
}
u.auditService.SaveAuditAsync(ctx, adminId, "Сменил пароль", entity.EventUserPasswordChanged)
return nil
})
if err != nil { if err != nil {
return errors.WithMessage(err, "user.service.ChangePassword: get user by id") return errors.WithMessage(err, "user transaction")
} }
if err := bcrypt.CompareHashAndPassword([]byte(admin.Password), []byte(oldPassword)); err != nil {
u.auditService.SaveAuditAsync(ctx, adminId, "Указан неверный старый пароль", entity.EventErrorPasswordChange)
return domain.ErrInvalidPassword
}
encryptedPassword, err := u.cryptPassword(newPassword)
if err != nil {
return errors.WithMessage(err, "user.service.ChangePassword: crypt new password")
}
err = u.userRepo.ChangePassword(ctx, adminId, encryptedPassword)
if err != nil {
return errors.WithMessage(err, "user.service.ChangePassword: change password ")
}
err = u.tokenService.RevokeAllByUserId(ctx, adminId)
if err != nil {
return errors.WithMessage(err, "revoke all tokens by user id")
}
u.auditService.SaveAuditAsync(ctx, adminId, "Сменил пароль", entity.EventUserPasswordChanged)
return nil return nil
} }
+3 -3
View File
@@ -15,9 +15,9 @@ func InsertUser(db *dbt.TestDb, user entity.User) int64 {
user.Password = string(passwordBytes) user.Password = string(passwordBytes)
} }
var id int64 var id int64
db.Must().SelectRow(&id, `insert into users (first_name, last_name, email, password, blocked) db.Must().SelectRow(&id, `insert into users (first_name, last_name, email, password, blocked, last_active_at)
values($1,$2,$3,$4,$5) returning id`, values($1,$2,$3,$4,$5,$6) returning id`,
user.FirstName, user.LastName, user.Email, user.Password, user.Blocked) user.FirstName, user.LastName, user.Email, user.Password, user.Blocked, user.LastActiveAt)
return id return id
} }
+2 -16
View File
@@ -21,22 +21,8 @@ func TestInactiveWorker(t *testing.T) {
test, require := test.New(t) test, require := test.New(t)
db := dbt.New(test, dbx.WithMigrationRunner("../migrations", test.Logger())) db := dbt.New(test, dbx.WithMigrationRunner("../migrations", test.Logger()))
userId := InsertUser(db, entity.User{Email: "a@test"}) userId := InsertUser(db, entity.User{Email: "a@test", LastActiveAt: time.Now().UTC().Add(-5 * 24 * time.Hour)})
InsertUser(db, entity.User{Email: "b@test"}) InsertUser(db, entity.User{Email: "b@test", LastActiveAt: time.Now().UTC()})
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),
})
config := assembly.NewLocator(test.Logger(), nil, db). config := assembly.NewLocator(test.Logger(), nil, db).
Config(t.Context(), emptyLdap, conf.Remote{ Config(t.Context(), emptyLdap, conf.Remote{