2025-09-16 17:00:10: merge [main:20f3fb7b5e4ca72a712c054d9a33187b91a5ed70];
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
Create and publish a Docker image / build-and-push-image (push) Canceled after 0s
This commit is contained in:
1 parent
14bd29e48f
commit
3029e084ce
16 files changed
+243
-29
No files matched your search
@@ -17,6 +17,7 @@ linters:
|
||||
- tagalign # не всегда имеет смысл
|
||||
- varnamelen # очень индивидуально (db)
|
||||
- wsl # расставление пробелов очень индивидуально
|
||||
- wsl_v5 # расставление пробелов очень индивидуально
|
||||
settings:
|
||||
cyclop:
|
||||
max-complexity: 15 # по умолчанию 10 мало
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
### v6.5.0
|
||||
* Изменена уникальность учетных записей с "email" на связку "email + sudir_id"
|
||||
* Добавлен метод `admin/auth/logout_with_reason` для вывода логов `Выхода по бездействию` в журнал ИБ
|
||||
### v6.4.0
|
||||
* Обнолвены зависимости
|
||||
### v6.3.1
|
||||
|
||||
+28
-2
@@ -16,7 +16,7 @@ import (
|
||||
type authService interface {
|
||||
Login(ctx context.Context, request domain.LoginRequest) (*domain.LoginResponse, error)
|
||||
LoginWithSudir(ctx context.Context, request domain.LoginSudirRequest) (*domain.LoginResponse, error)
|
||||
Logout(ctx context.Context, adminId int64) error
|
||||
Logout(ctx context.Context, adminId int64, request *domain.LogoutRequest) error
|
||||
}
|
||||
|
||||
type Auth struct {
|
||||
@@ -48,7 +48,33 @@ func (a Auth) Logout(ctx context.Context, authData grpc.AuthData) error {
|
||||
return err
|
||||
}
|
||||
|
||||
err = a.authService.Logout(ctx, adminId)
|
||||
err = a.authService.Logout(ctx, adminId, nil)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "logout")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// LogoutWithReason
|
||||
// @Tags auth
|
||||
// @Summary Выход по бездействию из авторизованной сессии
|
||||
// @Description Выход по бездействию из авторизованной сессии администрирования
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.LogoutRequest true "Тело запроса"
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Success 200
|
||||
// @Failure 400 {object} domain.GrpcError "Невалидный токен"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /auth/logout_with_reason [POST]
|
||||
func (a Auth) LogoutWithReason(ctx context.Context, authData grpc.AuthData, logoutRequest domain.LogoutRequest) error {
|
||||
adminId, err := getAdminId(authData)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = a.authService.Logout(ctx, adminId, &logoutRequest)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "logout")
|
||||
}
|
||||
|
||||
+38
-3
@@ -174,6 +174,11 @@ definitions:
|
||||
required:
|
||||
- authCode
|
||||
type: object
|
||||
domain.LogoutRequest:
|
||||
properties:
|
||||
reason:
|
||||
type: string
|
||||
type: object
|
||||
domain.PageRequest:
|
||||
properties:
|
||||
limit:
|
||||
@@ -228,7 +233,6 @@ definitions:
|
||||
domain.SecureAuthResponse:
|
||||
properties:
|
||||
adminId:
|
||||
format: int64
|
||||
type: integer
|
||||
authenticated:
|
||||
type: boolean
|
||||
@@ -310,7 +314,6 @@ definitions:
|
||||
firstName:
|
||||
type: string
|
||||
id:
|
||||
format: int64
|
||||
type: integer
|
||||
lastName:
|
||||
type: string
|
||||
@@ -329,7 +332,6 @@ definitions:
|
||||
type: string
|
||||
ids:
|
||||
items:
|
||||
format: int64
|
||||
type: integer
|
||||
type: array
|
||||
limit:
|
||||
@@ -448,6 +450,39 @@ paths:
|
||||
summary: Выход из авторизованной сессии
|
||||
tags:
|
||||
- auth
|
||||
/auth/logout_with_reason:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Выход по бездействию из авторизованной сессии администрирования
|
||||
parameters:
|
||||
- description: Тело запроса
|
||||
in: body
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/domain.LogoutRequest'
|
||||
- description: Токен администратора
|
||||
in: header
|
||||
name: X-AUTH-ADMIN
|
||||
required: true
|
||||
type: string
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
"400":
|
||||
description: Невалидный токен
|
||||
schema:
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
summary: Выход по бездействию из авторизованной сессии
|
||||
tags:
|
||||
- auth
|
||||
/log/all:
|
||||
post:
|
||||
consumes:
|
||||
|
||||
@@ -6,6 +6,10 @@ const (
|
||||
AdminAuthIdHeader = "x-admin-id"
|
||||
)
|
||||
|
||||
type LogoutRequest struct {
|
||||
Reason string
|
||||
}
|
||||
|
||||
type LoginRequest struct {
|
||||
Email string `validate:"required"`
|
||||
Password string ` validate:"required"`
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE users DROP CONSTRAINT users_email_key;
|
||||
ALTER TABLE users ADD CONSTRAINT users_email_sudir_user_id_key UNIQUE (email, sudir_user_id);
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE users DROP CONSTRAINT users_email_sudir_user_id_key;
|
||||
ALTER TABLE users ADD CONSTRAINT users_email_key UNIQUE (email);
|
||||
+58
-2
@@ -5,13 +5,14 @@ import (
|
||||
"database/sql"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"github.com/txix-open/isp-kit/db/query"
|
||||
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
@@ -72,6 +73,36 @@ func (u User) GetUserById(ctx context.Context, identity int64) (*entity.User, er
|
||||
}
|
||||
}
|
||||
|
||||
func (u User) GetUserByEmailAndSudirId(ctx context.Context, email string, sudir_user_id string) (*entity.User, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.GetUserByEmail")
|
||||
|
||||
equalClause := squirrel.Eq{"email": email, "sudir_user_id": nil}
|
||||
if sudir_user_id != "" {
|
||||
equalClause["sudir_user_id"] = sudir_user_id
|
||||
}
|
||||
|
||||
q, args, err := query.New().
|
||||
Select("*").
|
||||
From("users").
|
||||
Where(equalClause).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
}
|
||||
|
||||
user := entity.User{}
|
||||
err = u.db.SelectRow(ctx, &user, q, args...)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, sql.ErrNoRows):
|
||||
return nil, domain.ErrNotFound
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "db select")
|
||||
default:
|
||||
return &user, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (u User) UpsertBySudirUserId(ctx context.Context, user entity.User) (*entity.User, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.UpsertBySudirUserId")
|
||||
|
||||
@@ -134,6 +165,31 @@ func (u User) GetUsers(ctx context.Context, ids []int64, offset, limit int, emai
|
||||
return users, nil
|
||||
}
|
||||
|
||||
func (u User) GetUsersByEmail(ctx context.Context, email string) ([]entity.User, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.GetUserByEmail")
|
||||
|
||||
q, args, err := query.New().
|
||||
Select("*").
|
||||
From("users").
|
||||
Where(squirrel.Eq{"email": email}).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
}
|
||||
|
||||
users := make([]entity.User, 0)
|
||||
err = u.db.Select(ctx, &users, q, args...)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, sql.ErrNoRows) || len(users) == 0:
|
||||
return nil, domain.ErrNotFound
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "db select")
|
||||
default:
|
||||
return users, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (u User) Insert(ctx context.Context, user entity.User) (int, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.Insert")
|
||||
|
||||
|
||||
@@ -49,6 +49,11 @@ func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
|
||||
Inner: true,
|
||||
Handler: c.Auth.Logout,
|
||||
},
|
||||
{
|
||||
Path: "admin/auth/logout_with_reason",
|
||||
Inner: true,
|
||||
Handler: c.Auth.LogoutWithReason,
|
||||
},
|
||||
{
|
||||
Path: "admin/user/get_profile",
|
||||
Inner: true,
|
||||
|
||||
+6
-1
@@ -213,7 +213,7 @@ func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirReque
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a Auth) Logout(ctx context.Context, adminId int64) error {
|
||||
func (a Auth) Logout(ctx context.Context, adminId int64, request *domain.LogoutRequest) error {
|
||||
err := a.txRunner.AuthTransaction(ctx, func(ctx context.Context, tx AuthTransaction) error {
|
||||
err := a.tokenService.RevokeAllByUserId(ctx, adminId)
|
||||
if err != nil {
|
||||
@@ -226,6 +226,11 @@ func (a Auth) Logout(ctx context.Context, adminId int64) error {
|
||||
return errors.WithMessage(err, "update user last_active_at")
|
||||
}
|
||||
|
||||
if request != nil && request.Reason == "idle" {
|
||||
a.auditService.SaveAuditAsync(ctx, adminId, "Выход по бездействию", entity.EventSuccessLogout)
|
||||
return nil
|
||||
}
|
||||
|
||||
a.auditService.SaveAuditAsync(ctx, adminId, "Выход", entity.EventSuccessLogout)
|
||||
return nil
|
||||
})
|
||||
|
||||
+23
-9
@@ -8,11 +8,12 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
type UserTransaction interface {
|
||||
@@ -28,7 +29,8 @@ type UserTransactionRunner interface {
|
||||
type UserRepo interface {
|
||||
GetUserById(ctx context.Context, identity int64) (*entity.User, error)
|
||||
GetUsers(ctx context.Context, ids []int64, offset, limit int, email string) ([]entity.User, error)
|
||||
GetUserByEmail(ctx context.Context, email string) (*entity.User, error)
|
||||
GetUserByEmailAndSudirId(ctx context.Context, email string, sudir_user_id string) (*entity.User, error)
|
||||
GetUsersByEmail(ctx context.Context, email string) ([]entity.User, error)
|
||||
UpdateUser(ctx context.Context, id int64, user entity.UpdateUser) (*entity.User, error)
|
||||
DeleteUser(ctx context.Context, ids []int64) (int, error)
|
||||
Insert(ctx context.Context, user entity.User) (int, error)
|
||||
@@ -168,7 +170,7 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, admi
|
||||
var usr entity.User
|
||||
|
||||
err := u.txRunner.UserTransaction(ctx, func(ctx context.Context, tx UserTransaction) error {
|
||||
user, err := tx.GetUserByEmail(ctx, req.Email)
|
||||
user, err := tx.GetUserByEmailAndSudirId(ctx, req.Email, "")
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
break
|
||||
@@ -234,6 +236,7 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, admi
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
//nolint:cyclop,funlen
|
||||
func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, adminId int64) (*domain.User, error) {
|
||||
var (
|
||||
user *entity.User
|
||||
@@ -244,7 +247,7 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, admi
|
||||
return nil, errors.WithMessage(err, "get user roles")
|
||||
}
|
||||
err = u.txRunner.UserTransaction(ctx, func(ctx context.Context, tx UserTransaction) error {
|
||||
_, err := tx.GetUserById(ctx, req.Id)
|
||||
user, err = tx.GetUserById(ctx, req.Id)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return err // nolint:wrapcheck
|
||||
@@ -252,14 +255,24 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, admi
|
||||
return errors.WithMessage(err, "get user by id")
|
||||
}
|
||||
|
||||
user, err = tx.GetUserByEmail(ctx, req.Email)
|
||||
users, err := tx.GetUsersByEmail(ctx, req.Email)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
break
|
||||
case err != nil:
|
||||
return errors.WithMessage(err, "get user by email or phone")
|
||||
case user.Id != req.Id:
|
||||
return domain.ErrAlreadyExists
|
||||
}
|
||||
|
||||
for _, usr := range users {
|
||||
// check in internal user space
|
||||
if (user.SudirUserId == nil && usr.SudirUserId == nil) && (usr.Id != req.Id) {
|
||||
return domain.ErrAlreadyExists
|
||||
}
|
||||
|
||||
// check in sudir user space
|
||||
if usr.SudirUserId != nil && user.SudirUserId != nil && (*user.SudirUserId != *usr.SudirUserId) {
|
||||
return domain.ErrAlreadyExists
|
||||
}
|
||||
}
|
||||
|
||||
updateEntity := entity.UpdateUser{
|
||||
@@ -445,7 +458,8 @@ func (u User) ChangePassword(ctx context.Context, adminId int64, oldPassword str
|
||||
return errors.WithMessage(err, "user.service.ChangePassword: get user by id")
|
||||
}
|
||||
|
||||
if err = bcrypt.CompareHashAndPassword([]byte(admin.Password), []byte(oldPassword)); err != nil {
|
||||
err = bcrypt.CompareHashAndPassword([]byte(admin.Password), []byte(oldPassword))
|
||||
if err != nil {
|
||||
u.auditService.SaveAuditAsync(ctx, adminId, "Указан неверный старый пароль", entity.EventErrorPasswordChange)
|
||||
return domain.ErrInvalidPassword
|
||||
}
|
||||
|
||||
@@ -28,6 +28,7 @@ func TestAuditSuite(t *testing.T) {
|
||||
|
||||
type AuditSuite struct {
|
||||
suite.Suite
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
grpcCli *client.Client
|
||||
|
||||
+4
-2
@@ -11,14 +11,15 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"golang.org/x/sync/errgroup"
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/repository"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
@@ -38,6 +39,7 @@ func TestAuthTestSuite(t *testing.T) {
|
||||
|
||||
type AuthTestSuite struct {
|
||||
suite.Suite
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
grpcCli *client.Client
|
||||
|
||||
@@ -22,6 +22,7 @@ func TestCustomizationTestSuite(t *testing.T) {
|
||||
|
||||
type CustomizationTestSuite struct {
|
||||
suite.Suite
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
grpcCli *client.Client
|
||||
|
||||
@@ -26,6 +26,7 @@ func TestSecureSuite(t *testing.T) {
|
||||
|
||||
type SecureSuite struct {
|
||||
suite.Suite
|
||||
|
||||
test *test.Test
|
||||
require *require.Assertions
|
||||
db *dbt.TestDb
|
||||
|
||||
+62
-9
@@ -2,12 +2,20 @@ package tests_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/repository"
|
||||
"msp-admin-service/service"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
@@ -18,12 +26,6 @@ import (
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/repository"
|
||||
"msp-admin-service/service"
|
||||
)
|
||||
|
||||
type tokenService interface {
|
||||
@@ -37,6 +39,7 @@ func TestUserTestSuite(t *testing.T) {
|
||||
|
||||
type UserTestSuite struct {
|
||||
suite.Suite
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
grpcCli *client.Client
|
||||
@@ -201,6 +204,33 @@ func (s *UserTestSuite) TestCreateUserHappyPath() {
|
||||
s.Require().Equal(preCount+1, postCount)
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestCreateUserWithSameEmailSudirHappyPath() {
|
||||
firstSudirId := "user_a"
|
||||
admin := InsertSudirUser(s.db, entity.SudirUser{SudirUserId: firstSudirId, Email: "a2@a.ru"})
|
||||
|
||||
preCount := 0
|
||||
s.db.Must().SelectRow(&preCount, "select count(*) from users")
|
||||
|
||||
response := entity.User{}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/create_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
JsonRequestBody(domain.CreateUserRequest{
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
Email: "a2@a.ru",
|
||||
Password: "password",
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(context.Background())
|
||||
s.Require().NoError(err)
|
||||
|
||||
postCount := 0
|
||||
s.db.Must().SelectRow(&postCount, "select count(*) from users")
|
||||
|
||||
s.Require().Equal(preCount+1, postCount)
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestCreateUserAlreadyExist() {
|
||||
id := InsertUser(s.db, entity.User{Email: "exists@a.ru"})
|
||||
|
||||
@@ -246,7 +276,7 @@ func (s *AuthTestSuite) TestUpdateUserHappyPath() {
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestUpdateSudirUserHappyPath() {
|
||||
id := InsertSudirUser(s.db, entity.SudirUser{Email: "sudir@a.ru"})
|
||||
id := InsertSudirUser(s.db, entity.SudirUser{SudirUserId: "123", Email: "sudir@a.ru"})
|
||||
req := domain.UpdateUserRequest{
|
||||
Id: id,
|
||||
FirstName: "name",
|
||||
@@ -290,6 +320,29 @@ func (s *AuthTestSuite) TestUpdateUserAlreadyExist() {
|
||||
s.Require().Equal(codes.AlreadyExists, st.Code())
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestUpdateUserWithSudirAlreadyExist() {
|
||||
firstSudirId := "user_a"
|
||||
secondSudirId := "user_b"
|
||||
|
||||
admin := InsertSudirUser(s.db, entity.SudirUser{SudirUserId: firstSudirId, Email: "a_exists@a.ru"})
|
||||
id := InsertSudirUser(s.db, entity.SudirUser{SudirUserId: secondSudirId, Email: "b_exists@b.ru"})
|
||||
req := domain.UpdateUserRequest{
|
||||
Id: id,
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
Email: "a_exists@a.ru",
|
||||
}
|
||||
err := s.grpcCli.
|
||||
Invoke("admin/user/update_user").
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))).
|
||||
JsonRequestBody(req).
|
||||
Do(context.Background())
|
||||
s.Require().Error(err)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.AlreadyExists, st.Code())
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestDeleteUsers() {
|
||||
admin := InsertUser(s.db, entity.User{Email: "a_del@a.ru"})
|
||||
InsertUser(s.db, entity.User{Email: "b_del@a.ru"})
|
||||
|
||||
Reference in new issue
Block a user