diff --git a/assembly/locator.go b/assembly/locator.go index df59f07..382a861 100644 --- a/assembly/locator.go +++ b/assembly/locator.go @@ -115,7 +115,6 @@ func (l Locator) Config( ) inactiveBlocker := inactive_worker.NewInactiveBlocker( - tokenRepo, userRepo, auditService, userRoleRepo, diff --git a/entity/user.go b/entity/user.go index 87865cd..d3d8c72 100644 --- a/entity/user.go +++ b/entity/user.go @@ -3,16 +3,17 @@ package entity import "time" type User struct { - SudirUserId *string - Id int64 - FirstName string - LastName string - Description string - Email string - Password string - Blocked bool - UpdatedAt time.Time - CreatedAt time.Time + SudirUserId *string + Id int64 + FirstName string + LastName string + Description string + Email string + Password string + Blocked bool + LastActiveAt time.Time + UpdatedAt time.Time + CreatedAt time.Time } type SudirUser struct { diff --git a/migrations/20250723023639_add_last_active_at_column.sql b/migrations/20250723023639_add_last_active_at_column.sql new file mode 100644 index 0000000..8ccc685 --- /dev/null +++ b/migrations/20250723023639_add_last_active_at_column.sql @@ -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; diff --git a/repository/token.go b/repository/token.go index 8d18758..a2f99e1 100644 --- a/repository/token.go +++ b/repository/token.go @@ -3,9 +3,9 @@ package repository import ( "context" "database/sql" + "github.com/Masterminds/squirrel" "time" - "github.com/Masterminds/squirrel" "github.com/pkg/errors" "github.com/txix-open/isp-kit/db" "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 } -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) { ctx = sql_metrics.OperationLabelToContext(ctx, "Token.LastAccessNotBlockedUsers") diff --git a/repository/user.go b/repository/user.go index f0b184d..45fe0b1 100644 --- a/repository/user.go +++ b/repository/user.go @@ -3,6 +3,7 @@ package repository import ( "context" "database/sql" + "time" "github.com/Masterminds/squirrel" "github.com/pkg/errors" @@ -233,6 +234,32 @@ func (u User) Block(ctx context.Context, userId int) (*entity.User, error) { 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 { ctx = sql_metrics.OperationLabelToContext(ctx, "User.ChangePassword") @@ -252,3 +279,14 @@ func (u User) ChangePassword(ctx context.Context, userId int64, newPassword stri 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 +} diff --git a/service/auth.go b/service/auth.go index e4c227d..ec10d21 100644 --- a/service/auth.go +++ b/service/auth.go @@ -31,6 +31,7 @@ type userRepository interface { GetUserByEmail(ctx context.Context, email string) (*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) + UpdateLastActiveAt(ctx context.Context, userId int64, lastActiveAt time.Time) error } 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") } + 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) return nil @@ -185,6 +192,12 @@ func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirReque 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 }) 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 { - err := a.tokenService.RevokeAllByUserId(ctx, adminId) - if err != nil { - return errors.WithMessage(err, "revoke all tokens by user id") - } + err := a.txRunner.AuthTransaction(ctx, func(ctx context.Context, tx AuthTransaction) error { + err := a.tokenService.RevokeAllByUserId(ctx, adminId) + 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 } diff --git a/service/inactive_worker/service.go b/service/inactive_worker/service.go index 0720ea2..cb60c03 100644 --- a/service/inactive_worker/service.go +++ b/service/inactive_worker/service.go @@ -19,11 +19,8 @@ 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 { + LastAccessNotBlockedUsers(ctx context.Context) (map[int64]time.Time, error) Block(ctx context.Context, userId int) (*entity.User, error) } @@ -36,7 +33,6 @@ type UserRoleRepo interface { } type Service struct { - tokenRepo TokenRepo userRepo UserRepo auditRepo AuditRepo userRoleRepo UserRoleRepo @@ -47,7 +43,6 @@ type Service struct { } func NewInactiveBlocker( - tokensRepo TokenRepo, userRepo UserRepo, auditRepo AuditRepo, userRoleRepo UserRoleRepo, @@ -56,7 +51,6 @@ func NewInactiveBlocker( logger log.Logger, ) Service { return Service{ - tokenRepo: tokensRepo, userRepo: userRepo, auditRepo: auditRepo, 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 { - lastAccess, err := w.tokenRepo.LastAccessNotBlockedUsers(ctx) + lastAccess, err := w.userRepo.LastAccessNotBlockedUsers(ctx) if err != nil { return errors.WithMessage(err, "get last access times") } diff --git a/service/user.go b/service/user.go index dced885..3df3a04 100644 --- a/service/user.go +++ b/service/user.go @@ -34,6 +34,7 @@ type UserRepo interface { Insert(ctx context.Context, user entity.User) (int, error) ChangeBlockStatus(ctx context.Context, userId int) (bool, error) ChangePassword(ctx context.Context, userId int64, newPassword string) error + UpdateLastActiveAt(ctx context.Context, userId int64, lastActiveAt time.Time) error } type TokenRepo interface { @@ -371,7 +372,7 @@ func (u User) Block(ctx context.Context, adminId int64, userId int) error { } if blocked { - err := tx.UpdateStatusByUserId(ctx, userId, entity.TokenStatusRevoked) + err = tx.UpdateStatusByUserId(ctx, userId, entity.TokenStatusRevoked) if err != nil { return errors.WithMessage(err, "revoke tokens") } @@ -379,6 +380,11 @@ func (u User) Block(ctx context.Context, adminId int64, userId int) error { if !blocked { 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 @@ -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 { - 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 { - 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 } diff --git a/tests/db_general_test.go b/tests/db_general_test.go index 1ddad9b..0e345fa 100644 --- a/tests/db_general_test.go +++ b/tests/db_general_test.go @@ -15,9 +15,9 @@ func InsertUser(db *dbt.TestDb, user entity.User) int64 { user.Password = string(passwordBytes) } var id int64 - db.Must().SelectRow(&id, `insert into users (first_name, last_name, email, password, blocked) - values($1,$2,$3,$4,$5) returning id`, - user.FirstName, user.LastName, user.Email, user.Password, user.Blocked) + db.Must().SelectRow(&id, `insert into users (first_name, last_name, email, password, blocked, last_active_at) + values($1,$2,$3,$4,$5,$6) returning id`, + user.FirstName, user.LastName, user.Email, user.Password, user.Blocked, user.LastActiveAt) return id } diff --git a/tests/inactive_test.go b/tests/inactive_test.go index b705621..5d4bd24 100644 --- a/tests/inactive_test.go +++ b/tests/inactive_test.go @@ -21,22 +21,8 @@ func TestInactiveWorker(t *testing.T) { test, require := test.New(t) db := dbt.New(test, dbx.WithMigrationRunner("../migrations", test.Logger())) - 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), - }) - InsertTokenEntity(db, entity.Token{ - Id: 0, - Token: "234", - UserId: userId, - Status: entity.TokenStatusAllowed, - CreatedAt: time.Now().UTC().Add(-5 * 24 * time.Hour), - }) + userId := InsertUser(db, entity.User{Email: "a@test", LastActiveAt: time.Now().UTC().Add(-5 * 24 * time.Hour)}) + InsertUser(db, entity.User{Email: "b@test", LastActiveAt: time.Now().UTC()}) config := assembly.NewLocator(test.Logger(), nil, db). Config(t.Context(), emptyLdap, conf.Remote{